book.tex 828 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{0}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. %% For multiple indices:
  35. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  36. \makeindex{subject}
  37. %\makeindex{authors}
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. \if\edition\racketEd
  40. \lstset{%
  41. language=Lisp,
  42. basicstyle=\ttfamily\small,
  43. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  44. deletekeywords={read,mapping,vector},
  45. escapechar=|,
  46. columns=flexible,
  47. %moredelim=[is][\color{red}]{~}{~},
  48. showstringspaces=false
  49. }
  50. \fi
  51. \if\edition\pythonEd
  52. \lstset{%
  53. language=Python,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  56. deletekeywords={},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. %%% Any shortcut own defined macros place here
  64. %% sample of author macro:
  65. \input{defs}
  66. \newtheorem{exercise}[theorem]{Exercise}
  67. \numberwithin{theorem}{chapter}
  68. \numberwithin{definition}{chapter}
  69. \numberwithin{equation}{chapter}
  70. % Adjusted settings
  71. \setlength{\columnsep}{4pt}
  72. %% \begingroup
  73. %% \setlength{\intextsep}{0pt}%
  74. %% \setlength{\columnsep}{0pt}%
  75. %% \begin{wrapfigure}{r}{0.5\textwidth}
  76. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  77. %% \caption{Basic layout}
  78. %% \end{wrapfigure}
  79. %% \lipsum[1]
  80. %% \endgroup
  81. \newbox\oiintbox
  82. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  83. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  84. \def\oiint{\copy\oiintbox}
  85. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  86. %\usepackage{showframe}
  87. \def\ShowFrameLinethickness{0.125pt}
  88. \addbibresource{book.bib}
  89. \if\edition\pythonEd
  90. \addbibresource{python.bib}
  91. \fi
  92. \begin{document}
  93. \frontmatter
  94. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  95. \HalfTitle{Essentials of Compilation}
  96. \halftitlepage
  97. \clearemptydoublepage
  98. \Title{Essentials of Compilation}
  99. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  100. %\edition{First Edition}
  101. \BookAuthor{Jeremy G. Siek}
  102. \imprint{The MIT Press\\
  103. Cambridge, Massachusetts\\
  104. London, England}
  105. \begin{copyrightpage}
  106. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  107. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  108. Subject to such license, all rights are reserved. \\[2ex]
  109. \includegraphics{CCBY-logo}
  110. The MIT Press would like to thank the anonymous peer reviewers who
  111. provided comments on drafts of this book. The generous work of
  112. academic experts is essential for establishing the authority and
  113. quality of our publications. We acknowledge with gratitude the
  114. contributions of these otherwise uncredited readers.
  115. This book was set in Times LT Std Roman by the author. Printed and
  116. bound in the United States of America.
  117. {\if\edition\racketEd
  118. Library of Congress Cataloging-in-Publication Data\\
  119. \ \\
  120. Names: Siek, Jeremy, author. \\
  121. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  122. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  123. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  124. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  125. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  126. LC record available at https://lccn.loc.gov/2022015399\\
  127. LC ebook record available at https://lccn.loc.gov/2022015400\\
  128. \ \\
  129. \fi}
  130. 10 9 8 7 6 5 4 3 2 1
  131. %% Jeremy G. Siek. Available for free viewing
  132. %% or personal downloading under the
  133. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  134. %% license.
  135. %% Copyright in this monograph has been licensed exclusively to The MIT
  136. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  137. %% version to the public in 2022. All inquiries regarding rights should
  138. %% be addressed to The MIT Press, Rights and Permissions Department.
  139. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  140. %% All rights reserved. No part of this book may be reproduced in any
  141. %% form by any electronic or mechanical means (including photocopying,
  142. %% recording, or information storage and retrieval) without permission in
  143. %% writing from the publisher.
  144. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  145. %% United States of America.
  146. %% Library of Congress Cataloging-in-Publication Data is available.
  147. %% ISBN:
  148. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  149. \end{copyrightpage}
  150. \dedication{This book is dedicated to Katie, my partner in everything,
  151. my children, who grew up during the writing of this book, and the
  152. programming language students at Indiana University, whose
  153. thoughtful questions made this a better book.}
  154. %% \begin{epigraphpage}
  155. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  156. %% \textit{Book Name if any}}
  157. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  158. %% \end{epigraphpage}
  159. \tableofcontents
  160. %\listoffigures
  161. %\listoftables
  162. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  163. \chapter*{Preface}
  164. \addcontentsline{toc}{fmbm}{Preface}
  165. There is a magical moment when a programmer presses the \emph{run}
  166. button and the software begins to execute. Somehow a program written
  167. in a high-level language is running on a computer that is capable only
  168. of shuffling bits. Here we reveal the wizardry that makes that moment
  169. possible. Beginning with the groundbreaking work of Backus and
  170. colleagues in the 1950s, computer scientists developed techniques for
  171. constructing programs called \emph{compilers} that automatically
  172. translate high-level programs into machine code.
  173. We take you on a journey through constructing your own compiler for a
  174. small but powerful language. Along the way we explain the essential
  175. concepts, algorithms, and data structures that underlie compilers. We
  176. develop your understanding of how programs are mapped onto computer
  177. hardware, which is helpful in reasoning about properties at the
  178. junction of hardware and software, such as execution time, software
  179. errors, and security vulnerabilities. For those interested in
  180. pursuing compiler construction as a career, our goal is to provide a
  181. stepping-stone to advanced topics such as just-in-time compilation,
  182. program analysis, and program optimization. For those interested in
  183. designing and implementing programming languages, we connect language
  184. design choices to their impact on the compiler and the generated code.
  185. A compiler is typically organized as a sequence of stages that
  186. progressively translate a program to the code that runs on
  187. hardware. We take this approach to the extreme by partitioning our
  188. compiler into a large number of \emph{nanopasses}, each of which
  189. performs a single task. This enables the testing of each pass in
  190. isolation and focuses our attention, making the compiler far easier to
  191. understand.
  192. The most familiar approach to describing compilers is to dedicate each
  193. chapter to one pass. The problem with that approach is that it
  194. obfuscates how language features motivate design choices in a
  195. compiler. We instead take an \emph{incremental} approach in which we
  196. build a complete compiler in each chapter, starting with a small input
  197. language that includes only arithmetic and variables. We add new
  198. language features in subsequent chapters, extending the compiler as
  199. necessary.
  200. Our choice of language features is designed to elicit fundamental
  201. concepts and algorithms used in compilers.
  202. \begin{itemize}
  203. \item We begin with integer arithmetic and local variables in
  204. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  205. the fundamental tools of compiler construction: \emph{abstract
  206. syntax trees} and \emph{recursive functions}.
  207. {\if\edition\pythonEd\pythonColor
  208. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  209. parser framework to create a parser for the language of integer
  210. arithmetic and local variables. We learn about the parsing
  211. algorithms inside Lark, including Earley and LALR(1).
  212. %
  213. \fi}
  214. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  215. \emph{graph coloring} to assign variables to machine registers.
  216. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  217. motivates an elegant recursive algorithm for translating them into
  218. conditional \code{goto} statements.
  219. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  220. variables}. This elicits the need for \emph{dataflow
  221. analysis} in the register allocator.
  222. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  223. \emph{garbage collection}.
  224. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  225. without lexical scoping, similar to functions in the C programming
  226. language~\citep{Kernighan:1988nx}. The reader learns about the
  227. procedure call stack and \emph{calling conventions} and how they interact
  228. with register allocation and garbage collection. The chapter also
  229. describes how to generate efficient tail calls.
  230. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  231. scoping, that is, \emph{lambda} expressions. The reader learns about
  232. \emph{closure conversion}, in which lambdas are translated into a
  233. combination of functions and tuples.
  234. % Chapter about classes and objects?
  235. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  236. point the input languages are statically typed. The reader extends
  237. the statically typed language with an \code{Any} type that serves
  238. as a target for compiling the dynamically typed language.
  239. %% {\if\edition\pythonEd\pythonColor
  240. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  241. %% \emph{classes}.
  242. %% \fi}
  243. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  244. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  245. in which different regions of a program may be static or dynamically
  246. typed. The reader implements runtime support for \emph{proxies} that
  247. allow values to safely move between regions.
  248. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  249. leveraging the \code{Any} type and type casts developed in chapters
  250. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  251. \end{itemize}
  252. There are many language features that we do not include. Our choices
  253. balance the incidental complexity of a feature versus the fundamental
  254. concepts that it exposes. For example, we include tuples and not
  255. records because although they both elicit the study of heap allocation and
  256. garbage collection, records come with more incidental complexity.
  257. Since 2009, drafts of this book have served as the textbook for
  258. sixteen-week compiler courses for upper-level undergraduates and
  259. first-year graduate students at the University of Colorado and Indiana
  260. University.
  261. %
  262. Students come into the course having learned the basics of
  263. programming, data structures and algorithms, and discrete
  264. mathematics.
  265. %
  266. At the beginning of the course, students form groups of two to four
  267. people. The groups complete approximately one chapter every two
  268. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  269. according to the students interests while respecting the dependencies
  270. between chapters shown in
  271. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  272. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  273. implementation of efficient tail calls.
  274. %
  275. The last two weeks of the course involve a final project in which
  276. students design and implement a compiler extension of their choosing.
  277. The last few chapters can be used in support of these projects. Many
  278. chapters include a challenge problem that we assign to the graduate
  279. students.
  280. For compiler courses at universities on the quarter system
  281. (about ten weeks in length), we recommend completing the course
  282. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  283. some scaffolding code to the students for each compiler pass.
  284. %
  285. The course can be adapted to emphasize functional languages by
  286. skipping chapter~\ref{ch:Lwhile} (loops) and including
  287. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  288. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  289. %
  290. %% \python{A course that emphasizes object-oriented languages would
  291. %% include Chapter~\ref{ch:Lobject}.}
  292. This book has been used in compiler courses at California Polytechnic
  293. State University, Portland State University, Rose–Hulman Institute of
  294. Technology, University of Freiburg, University of Massachusetts
  295. Lowell, and the University of Vermont.
  296. \begin{figure}[tp]
  297. \begin{tcolorbox}[colback=white]
  298. {\if\edition\racketEd
  299. \begin{tikzpicture}[baseline=(current bounding box.center)]
  300. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  301. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  302. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  303. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  304. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  305. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  306. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  307. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  308. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  309. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  310. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  311. \path[->] (C1) edge [above] node {} (C2);
  312. \path[->] (C2) edge [above] node {} (C3);
  313. \path[->] (C3) edge [above] node {} (C4);
  314. \path[->] (C4) edge [above] node {} (C5);
  315. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  316. \path[->] (C5) edge [above] node {} (C7);
  317. \path[->] (C6) edge [above] node {} (C7);
  318. \path[->] (C4) edge [above] node {} (C8);
  319. \path[->] (C4) edge [above] node {} (C9);
  320. \path[->] (C7) edge [above] node {} (C10);
  321. \path[->] (C8) edge [above] node {} (C10);
  322. \path[->] (C10) edge [above] node {} (C11);
  323. \end{tikzpicture}
  324. \fi}
  325. {\if\edition\pythonEd\pythonColor
  326. \begin{tikzpicture}[baseline=(current bounding box.center)]
  327. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  328. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  329. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  330. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  331. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  332. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  333. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  334. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  335. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  336. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  337. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  338. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  339. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  340. \path[->] (Prelim) edge [above] node {} (Var);
  341. \path[->] (Var) edge [above] node {} (Reg);
  342. \path[->] (Var) edge [above] node {} (Parse);
  343. \path[->] (Reg) edge [above] node {} (Cond);
  344. \path[->] (Cond) edge [above] node {} (Tuple);
  345. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  346. \path[->] (Cond) edge [above] node {} (Fun);
  347. \path[->] (Tuple) edge [above] node {} (Lam);
  348. \path[->] (Fun) edge [above] node {} (Lam);
  349. \path[->] (Cond) edge [above] node {} (Dyn);
  350. \path[->] (Cond) edge [above] node {} (Loop);
  351. \path[->] (Lam) edge [above] node {} (Gradual);
  352. \path[->] (Dyn) edge [above] node {} (Gradual);
  353. % \path[->] (Dyn) edge [above] node {} (CO);
  354. \path[->] (Gradual) edge [above] node {} (Generic);
  355. \end{tikzpicture}
  356. \fi}
  357. \end{tcolorbox}
  358. \caption{Diagram of chapter dependencies.}
  359. \label{fig:chapter-dependences}
  360. \end{figure}
  361. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  362. the implementation of the compiler and for the input language, so the
  363. reader should be proficient with Racket or Scheme. There are many
  364. excellent resources for learning Scheme and
  365. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  366. %
  367. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  368. both for the implementation of the compiler and for the input language, so the
  369. reader should be proficient with Python. There are many
  370. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  371. %
  372. The support code for this book is in the GitHub repository at
  373. the following location:
  374. \begin{center}\small\texttt
  375. https://github.com/IUCompilerCourse/
  376. \end{center}
  377. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  378. is helpful but not necessary for the reader to have taken a computer
  379. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  380. assembly language that are needed in the compiler.
  381. %
  382. We follow the System V calling
  383. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  384. that we generate works with the runtime system (written in C) when it
  385. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  386. operating systems on Intel hardware.
  387. %
  388. On the Windows operating system, \code{gcc} uses the Microsoft x64
  389. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  390. assembly code that we generate does \emph{not} work with the runtime
  391. system on Windows. One workaround is to use a virtual machine with
  392. Linux as the guest operating system.
  393. \section*{Acknowledgments}
  394. The tradition of compiler construction at Indiana University goes back
  395. to research and courses on programming languages by Daniel Friedman in
  396. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  397. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  398. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  399. the compiler course and continued the development of Chez Scheme.
  400. %
  401. The compiler course evolved to incorporate novel pedagogical ideas
  402. while also including elements of real-world compilers. One of
  403. Friedman's ideas was to split the compiler into many small
  404. passes. Another idea, called ``the game,'' was to test the code
  405. generated by each pass using interpreters.
  406. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  407. developed infrastructure to support this approach and evolved the
  408. course to use even smaller
  409. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  410. design decisions in this book are inspired by the assignment
  411. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  412. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  413. organization of the course made it difficult for students to
  414. understand the rationale for the compiler design. Ghuloum proposed the
  415. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  416. based.
  417. I thank the many students who served as teaching assistants for the
  418. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  419. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  420. garbage collector and x86 interpreter, Michael Vollmer for work on
  421. efficient tail calls, and Michael Vitousek for help with the first
  422. offering of the incremental compiler course at IU.
  423. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  424. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  425. Michael Wollowski for teaching courses based on drafts of this book
  426. and for their feedback. I thank the National Science Foundation for
  427. the grants that helped to support this work: Grant Numbers 1518844,
  428. 1763922, and 1814460.
  429. I thank Ronald Garcia for helping me survive Dybvig's compiler
  430. course in the early 2000s and especially for finding the bug that
  431. sent our garbage collector on a wild goose chase!
  432. \mbox{}\\
  433. \noindent Jeremy G. Siek \\
  434. Bloomington, Indiana
  435. \mainmatter
  436. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  437. \chapter{Preliminaries}
  438. \label{ch:trees-recur}
  439. \setcounter{footnote}{0}
  440. In this chapter we review the basic tools needed to implement a
  441. compiler. Programs are typically input by a programmer as text, that
  442. is, a sequence of characters. The program-as-text representation is
  443. called \emph{concrete syntax}. We use concrete syntax to concisely
  444. write down and talk about programs. Inside the compiler, we use
  445. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  446. that efficiently supports the operations that the compiler needs to
  447. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  448. syntax}\index{subject}{abstract syntax
  449. tree}\index{subject}{AST}\index{subject}{program}
  450. The process of translating concrete syntax to abstract syntax is
  451. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  452. chapter~\ref{ch:parsing}}.
  453. \racket{This book does not cover the theory and implementation of parsing.
  454. We refer the readers interested in parsing to the thorough treatment
  455. of parsing by \citet{Aho:2006wb}.}%
  456. %
  457. \racket{A parser is provided in the support code for translating from
  458. concrete to abstract syntax.}%
  459. %
  460. \python{For now we use Python's \code{ast} module to translate from concrete
  461. to abstract syntax.}
  462. ASTs can be represented inside the compiler in many different ways,
  463. depending on the programming language used to write the compiler.
  464. %
  465. \racket{We use Racket's
  466. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  467. feature to represent ASTs (section~\ref{sec:ast}).}
  468. %
  469. \python{We use Python classes and objects to represent ASTs, especially the
  470. classes defined in the standard \code{ast} module for the Python
  471. source language.}
  472. %
  473. We use grammars to define the abstract syntax of programming languages
  474. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  475. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  476. recursive functions to construct and deconstruct ASTs
  477. (section~\ref{sec:recursion}). This chapter provides a brief
  478. introduction to these components.
  479. \racket{\index{subject}{struct}}
  480. \python{\index{subject}{class}\index{subject}{object}}
  481. \section{Abstract Syntax Trees}
  482. \label{sec:ast}
  483. Compilers use abstract syntax trees to represent programs because they
  484. often need to ask questions such as, for a given part of a program,
  485. what kind of language feature is it? What are its subparts? Consider
  486. the program on the left and the diagram of its AST on the
  487. right~\eqref{eq:arith-prog}. This program is an addition operation
  488. that has two subparts, a \racket{read}\python{input} operation and a
  489. negation. The negation has another subpart, the integer constant
  490. \code{8}. By using a tree to represent the program, we can easily
  491. follow the links to go from one part of a program to its subparts.
  492. \begin{center}
  493. \begin{minipage}{0.4\textwidth}
  494. {\if\edition\racketEd
  495. \begin{lstlisting}
  496. (+ (read) (- 8))
  497. \end{lstlisting}
  498. \fi}
  499. {\if\edition\pythonEd\pythonColor
  500. \begin{lstlisting}
  501. input_int() + -8
  502. \end{lstlisting}
  503. \fi}
  504. \end{minipage}
  505. \begin{minipage}{0.4\textwidth}
  506. \begin{equation}
  507. \begin{tikzpicture}
  508. \node[draw] (plus) at (0 , 0) {\key{+}};
  509. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  510. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  511. \node[draw] (8) at (1 , -2) {\key{8}};
  512. \draw[->] (plus) to (read);
  513. \draw[->] (plus) to (minus);
  514. \draw[->] (minus) to (8);
  515. \end{tikzpicture}
  516. \label{eq:arith-prog}
  517. \end{equation}
  518. \end{minipage}
  519. \end{center}
  520. We use the standard terminology for trees to describe ASTs: each
  521. rectangle above is called a \emph{node}. The arrows connect a node to its
  522. \emph{children}, which are also nodes. The top-most node is the
  523. \emph{root}. Every node except for the root has a \emph{parent} (the
  524. node of which it is the child). If a node has no children, it is a
  525. \emph{leaf} node; otherwise it is an \emph{internal} node.
  526. \index{subject}{node}
  527. \index{subject}{children}
  528. \index{subject}{root}
  529. \index{subject}{parent}
  530. \index{subject}{leaf}
  531. \index{subject}{internal node}
  532. %% Recall that an \emph{symbolic expression} (S-expression) is either
  533. %% \begin{enumerate}
  534. %% \item an atom, or
  535. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  536. %% where $e_1$ and $e_2$ are each an S-expression.
  537. %% \end{enumerate}
  538. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  539. %% null value \code{'()}, etc. We can create an S-expression in Racket
  540. %% simply by writing a backquote (called a quasi-quote in Racket)
  541. %% followed by the textual representation of the S-expression. It is
  542. %% quite common to use S-expressions to represent a list, such as $a, b
  543. %% ,c$ in the following way:
  544. %% \begin{lstlisting}
  545. %% `(a . (b . (c . ())))
  546. %% \end{lstlisting}
  547. %% Each element of the list is in the first slot of a pair, and the
  548. %% second slot is either the rest of the list or the null value, to mark
  549. %% the end of the list. Such lists are so common that Racket provides
  550. %% special notation for them that removes the need for the periods
  551. %% and so many parenthesis:
  552. %% \begin{lstlisting}
  553. %% `(a b c)
  554. %% \end{lstlisting}
  555. %% The following expression creates an S-expression that represents AST
  556. %% \eqref{eq:arith-prog}.
  557. %% \begin{lstlisting}
  558. %% `(+ (read) (- 8))
  559. %% \end{lstlisting}
  560. %% When using S-expressions to represent ASTs, the convention is to
  561. %% represent each AST node as a list and to put the operation symbol at
  562. %% the front of the list. The rest of the list contains the children. So
  563. %% in the above case, the root AST node has operation \code{`+} and its
  564. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  565. %% diagram \eqref{eq:arith-prog}.
  566. %% To build larger S-expressions one often needs to splice together
  567. %% several smaller S-expressions. Racket provides the comma operator to
  568. %% splice an S-expression into a larger one. For example, instead of
  569. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  570. %% we could have first created an S-expression for AST
  571. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  572. %% S-expression.
  573. %% \begin{lstlisting}
  574. %% (define ast1.4 `(- 8))
  575. %% (define ast1_1 `(+ (read) ,ast1.4))
  576. %% \end{lstlisting}
  577. %% In general, the Racket expression that follows the comma (splice)
  578. %% can be any expression that produces an S-expression.
  579. {\if\edition\racketEd
  580. We define a Racket \code{struct} for each kind of node. For this
  581. chapter we require just two kinds of nodes: one for integer constants
  582. (aka literals\index{subject}{literals})
  583. and one for primitive operations. The following is the \code{struct}
  584. definition for integer constants.\footnote{All the AST structures are
  585. defined in the file \code{utilities.rkt} in the support code.}
  586. \begin{lstlisting}
  587. (struct Int (value))
  588. \end{lstlisting}
  589. An integer node contains just one thing: the integer value.
  590. We establish the convention that \code{struct} names, such
  591. as \code{Int}, are capitalized.
  592. To create an AST node for the integer $8$, we write \INT{8}.
  593. \begin{lstlisting}
  594. (define eight (Int 8))
  595. \end{lstlisting}
  596. We say that the value created by \INT{8} is an
  597. \emph{instance} of the
  598. \code{Int} structure.
  599. The following is the \code{struct} definition for primitive operations.
  600. \begin{lstlisting}
  601. (struct Prim (op args))
  602. \end{lstlisting}
  603. A primitive operation node includes an operator symbol \code{op} and a
  604. list of child arguments called \code{args}. For example, to create an
  605. AST that negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. (define neg-eight (Prim '- (list eight)))
  608. \end{lstlisting}
  609. Primitive operations may have zero or more children. The \code{read}
  610. operator has zero:
  611. \begin{lstlisting}
  612. (define rd (Prim 'read '()))
  613. \end{lstlisting}
  614. The addition operator has two children:
  615. \begin{lstlisting}
  616. (define ast1_1 (Prim '+ (list rd neg-eight)))
  617. \end{lstlisting}
  618. We have made a design choice regarding the \code{Prim} structure.
  619. Instead of using one structure for many different operations
  620. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  621. structure for each operation, as follows:
  622. \begin{lstlisting}
  623. (struct Read ())
  624. (struct Add (left right))
  625. (struct Neg (value))
  626. \end{lstlisting}
  627. The reason that we choose to use just one structure is that many parts
  628. of the compiler can use the same code for the different primitive
  629. operators, so we might as well just write that code once by using a
  630. single structure.
  631. %
  632. \fi}
  633. {\if\edition\pythonEd\pythonColor
  634. We use a Python \code{class} for each kind of node.
  635. The following is the class definition for
  636. constants (aka literals\index{subject}{literals})
  637. from the Python \code{ast} module.
  638. \begin{lstlisting}
  639. class Constant:
  640. def __init__(self, value):
  641. self.value = value
  642. \end{lstlisting}
  643. An integer constant node includes just one thing: the integer value.
  644. To create an AST node for the integer $8$, we write \INT{8}.
  645. \begin{lstlisting}
  646. eight = Constant(8)
  647. \end{lstlisting}
  648. We say that the value created by \INT{8} is an
  649. \emph{instance} of the \code{Constant} class.
  650. The following is the class definition for unary operators.
  651. \begin{lstlisting}
  652. class UnaryOp:
  653. def __init__(self, op, operand):
  654. self.op = op
  655. self.operand = operand
  656. \end{lstlisting}
  657. The specific operation is specified by the \code{op} parameter. For
  658. example, the class \code{USub} is for unary subtraction.
  659. (More unary operators are introduced in later chapters.) To create an AST that
  660. negates the number $8$, we write the following.
  661. \begin{lstlisting}
  662. neg_eight = UnaryOp(USub(), eight)
  663. \end{lstlisting}
  664. The call to the \code{input\_int} function is represented by the
  665. \code{Call} and \code{Name} classes.
  666. \begin{lstlisting}
  667. class Call:
  668. def __init__(self, func, args):
  669. self.func = func
  670. self.args = args
  671. class Name:
  672. def __init__(self, id):
  673. self.id = id
  674. \end{lstlisting}
  675. To create an AST node that calls \code{input\_int}, we write
  676. \begin{lstlisting}
  677. read = Call(Name('input_int'), [])
  678. \end{lstlisting}
  679. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  680. the \code{BinOp} class for binary operators.
  681. \begin{lstlisting}
  682. class BinOp:
  683. def __init__(self, left, op, right):
  684. self.op = op
  685. self.left = left
  686. self.right = right
  687. \end{lstlisting}
  688. Similar to \code{UnaryOp}, the specific operation is specified by the
  689. \code{op} parameter, which for now is just an instance of the
  690. \code{Add} class. So to create the AST
  691. node that adds negative eight to some user input, we write the following.
  692. \begin{lstlisting}
  693. ast1_1 = BinOp(read, Add(), neg_eight)
  694. \end{lstlisting}
  695. \fi}
  696. To compile a program such as \eqref{eq:arith-prog}, we need to know
  697. that the operation associated with the root node is addition and we
  698. need to be able to access its two
  699. children. \racket{Racket}\python{Python} provides pattern matching to
  700. support these kinds of queries, as we see in
  701. section~\ref{sec:pattern-matching}.
  702. We often write down the concrete syntax of a program even when we
  703. actually have in mind the AST, because the concrete syntax is more
  704. concise. We recommend that you always think of programs as abstract
  705. syntax trees.
  706. \section{Grammars}
  707. \label{sec:grammar}
  708. \index{subject}{integer}
  709. %\index{subject}{constant}
  710. A programming language can be thought of as a \emph{set} of programs.
  711. The set is infinite (that is, one can always create larger programs),
  712. so one cannot simply describe a language by listing all the
  713. programs in the language. Instead we write down a set of rules, a
  714. \emph{context-free grammar}, for building programs. Grammars are often used to
  715. define the concrete syntax of a language, but they can also be used to
  716. describe the abstract syntax. We write our rules in a variant of
  717. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  718. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  719. we describe a small language, named \LangInt{}, that consists of
  720. integers and arithmetic operations.\index{subject}{grammar}
  721. \index{subject}{context-free grammar}
  722. The first grammar rule for the abstract syntax of \LangInt{} says that an
  723. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  724. \begin{equation}
  725. \Exp ::= \INT{\Int} \label{eq:arith-int}
  726. \end{equation}
  727. %
  728. Each rule has a left-hand side and a right-hand side.
  729. If you have an AST node that matches the
  730. right-hand side, then you can categorize it according to the
  731. left-hand side.
  732. %
  733. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  734. are \emph{terminal} symbols and must literally appear in the program for the
  735. rule to be applicable.\index{subject}{terminal}
  736. %
  737. Our grammars do not mention \emph{white space}, that is, delimiter
  738. characters like spaces, tabs, and new lines. White space may be
  739. inserted between symbols for disambiguation and to improve
  740. readability. \index{subject}{white space}
  741. %
  742. A name such as $\Exp$ that is defined by the grammar rules is a
  743. \emph{nonterminal}. \index{subject}{nonterminal}
  744. %
  745. The name $\Int$ is also a nonterminal, but instead of defining it with
  746. a grammar rule, we define it with the following explanation. An
  747. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  748. $-$ (for negative integers), such that the sequence of decimals
  749. %
  750. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  751. enables the representation of integers using 63 bits, which simplifies
  752. several aspects of compilation.
  753. %
  754. Thus, these integers correspond to the Racket \texttt{fixnum}
  755. datatype on a 64-bit machine.}
  756. %
  757. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  758. enables the representation of integers using 64 bits, which simplifies
  759. several aspects of compilation. In contrast, integers in Python have
  760. unlimited precision, but the techniques needed to handle unlimited
  761. precision fall outside the scope of this book.}
  762. The second grammar rule is the \READOP{} operation, which receives an
  763. input integer from the user of the program.
  764. \begin{equation}
  765. \Exp ::= \READ{} \label{eq:arith-read}
  766. \end{equation}
  767. The third rule categorizes the negation of an $\Exp$ node as an
  768. $\Exp$.
  769. \begin{equation}
  770. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  771. \end{equation}
  772. We can apply these rules to categorize the ASTs that are in the
  773. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  774. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  775. following AST is an $\Exp$.
  776. \begin{center}
  777. \begin{minipage}{0.5\textwidth}
  778. \NEG{\INT{\code{8}}}
  779. \end{minipage}
  780. \begin{minipage}{0.25\textwidth}
  781. \begin{equation}
  782. \begin{tikzpicture}
  783. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  784. \node[draw, circle] (8) at (0, -1.2) {$8$};
  785. \draw[->] (minus) to (8);
  786. \end{tikzpicture}
  787. \label{eq:arith-neg8}
  788. \end{equation}
  789. \end{minipage}
  790. \end{center}
  791. The next two grammar rules are for addition and subtraction expressions:
  792. \begin{align}
  793. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  794. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  795. \end{align}
  796. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  797. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  798. \eqref{eq:arith-read}, and we have already categorized
  799. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  800. to show that
  801. \[
  802. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  803. \]
  804. is an $\Exp$ in the \LangInt{} language.
  805. If you have an AST for which these rules do not apply, then the
  806. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  807. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  808. because there is no rule for the \key{*} operator. Whenever we
  809. define a language with a grammar, the language includes only those
  810. programs that are justified by the grammar rules.
  811. {\if\edition\pythonEd\pythonColor
  812. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  813. There is a statement for printing the value of an expression
  814. \[
  815. \Stmt{} ::= \PRINT{\Exp}
  816. \]
  817. and a statement that evaluates an expression but ignores the result.
  818. \[
  819. \Stmt{} ::= \EXPR{\Exp}
  820. \]
  821. \fi}
  822. {\if\edition\racketEd
  823. The last grammar rule for \LangInt{} states that there is a
  824. \code{Program} node to mark the top of the whole program:
  825. \[
  826. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  827. \]
  828. The \code{Program} structure is defined as follows:
  829. \begin{lstlisting}
  830. (struct Program (info body))
  831. \end{lstlisting}
  832. where \code{body} is an expression. In further chapters, the \code{info}
  833. part is used to store auxiliary information, but for now it is
  834. just the empty list.
  835. \fi}
  836. {\if\edition\pythonEd\pythonColor
  837. The last grammar rule for \LangInt{} states that there is a
  838. \code{Module} node to mark the top of the whole program:
  839. \[
  840. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  841. \]
  842. The asterisk $*$ indicates a list of the preceding grammar item, in
  843. this case a list of statements.
  844. %
  845. The \code{Module} class is defined as follows:
  846. \begin{lstlisting}
  847. class Module:
  848. def __init__(self, body):
  849. self.body = body
  850. \end{lstlisting}
  851. where \code{body} is a list of statements.
  852. \fi}
  853. It is common to have many grammar rules with the same left-hand side
  854. but different right-hand sides, such as the rules for $\Exp$ in the
  855. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  856. combine several right-hand sides into a single rule.
  857. The concrete syntax for \LangInt{} is shown in
  858. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  859. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  860. %
  861. \racket{The \code{read-program} function provided in
  862. \code{utilities.rkt} of the support code reads a program from a file
  863. (the sequence of characters in the concrete syntax of Racket) and
  864. parses it into an abstract syntax tree. Refer to the description of
  865. \code{read-program} in appendix~\ref{appendix:utilities} for more
  866. details.}
  867. %
  868. \python{The \code{parse} function in Python's \code{ast} module
  869. converts the concrete syntax (represented as a string) into an
  870. abstract syntax tree.}
  871. \newcommand{\LintGrammarRacket}{
  872. \begin{array}{rcl}
  873. \Type &::=& \key{Integer} \\
  874. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  875. \MID \CSUB{\Exp}{\Exp}
  876. \end{array}
  877. }
  878. \newcommand{\LintASTRacket}{
  879. \begin{array}{rcl}
  880. \Type &::=& \key{Integer} \\
  881. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  882. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  883. \end{array}
  884. }
  885. \newcommand{\LintGrammarPython}{
  886. \begin{array}{rcl}
  887. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  888. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  889. \end{array}
  890. }
  891. \newcommand{\LintASTPython}{
  892. \begin{array}{rcl}
  893. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  894. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  895. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  896. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  897. \end{array}
  898. }
  899. \begin{figure}[tp]
  900. \begin{tcolorbox}[colback=white]
  901. {\if\edition\racketEd
  902. \[
  903. \begin{array}{l}
  904. \LintGrammarRacket \\
  905. \begin{array}{rcl}
  906. \LangInt{} &::=& \Exp
  907. \end{array}
  908. \end{array}
  909. \]
  910. \fi}
  911. {\if\edition\pythonEd\pythonColor
  912. \[
  913. \begin{array}{l}
  914. \LintGrammarPython \\
  915. \begin{array}{rcl}
  916. \LangInt{} &::=& \Stmt^{*}
  917. \end{array}
  918. \end{array}
  919. \]
  920. \fi}
  921. \end{tcolorbox}
  922. \caption{The concrete syntax of \LangInt{}.}
  923. \label{fig:r0-concrete-syntax}
  924. \end{figure}
  925. \begin{figure}[tp]
  926. \begin{tcolorbox}[colback=white]
  927. {\if\edition\racketEd
  928. \[
  929. \begin{array}{l}
  930. \LintASTRacket{} \\
  931. \begin{array}{rcl}
  932. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  933. \end{array}
  934. \end{array}
  935. \]
  936. \fi}
  937. {\if\edition\pythonEd\pythonColor
  938. \[
  939. \begin{array}{l}
  940. \LintASTPython\\
  941. \begin{array}{rcl}
  942. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  943. \end{array}
  944. \end{array}
  945. \]
  946. \fi}
  947. \end{tcolorbox}
  948. \python{
  949. \index{subject}{Constant@\texttt{Constant}}
  950. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  951. \index{subject}{USub@\texttt{USub}}
  952. \index{subject}{inputint@\texttt{input\_int}}
  953. \index{subject}{Call@\texttt{Call}}
  954. \index{subject}{Name@\texttt{Name}}
  955. \index{subject}{BinOp@\texttt{BinOp}}
  956. \index{subject}{Add@\texttt{Add}}
  957. \index{subject}{Sub@\texttt{Sub}}
  958. \index{subject}{print@\texttt{print}}
  959. \index{subject}{Expr@\texttt{Expr}}
  960. \index{subject}{Module@\texttt{Module}}
  961. }
  962. \caption{The abstract syntax of \LangInt{}.}
  963. \label{fig:r0-syntax}
  964. \end{figure}
  965. \section{Pattern Matching}
  966. \label{sec:pattern-matching}
  967. As mentioned in section~\ref{sec:ast}, compilers often need to access
  968. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  969. provides the \texttt{match} feature to access the parts of a value.
  970. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  971. \begin{center}
  972. \begin{minipage}{1.0\textwidth}
  973. {\if\edition\racketEd
  974. \begin{lstlisting}
  975. (match ast1_1
  976. [(Prim op (list child1 child2))
  977. (print op)])
  978. \end{lstlisting}
  979. \fi}
  980. {\if\edition\pythonEd\pythonColor
  981. \begin{lstlisting}
  982. match ast1_1:
  983. case BinOp(child1, op, child2):
  984. print(op)
  985. \end{lstlisting}
  986. \fi}
  987. \end{minipage}
  988. \end{center}
  989. {\if\edition\racketEd
  990. %
  991. In this example, the \texttt{match} form checks whether the AST
  992. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  993. three pattern variables \texttt{op}, \texttt{child1}, and
  994. \texttt{child2}. In general, a match clause consists of a
  995. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  996. recursively defined to be a pattern variable, a structure name
  997. followed by a pattern for each of the structure's arguments, or an
  998. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  999. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1000. and chapter 9 of The Racket
  1001. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1002. for complete descriptions of \code{match}.)
  1003. %
  1004. The body of a match clause may contain arbitrary Racket code. The
  1005. pattern variables can be used in the scope of the body, such as
  1006. \code{op} in \code{(print op)}.
  1007. %
  1008. \fi}
  1009. %
  1010. %
  1011. {\if\edition\pythonEd\pythonColor
  1012. %
  1013. In the example above, the \texttt{match} form checks whether the AST
  1014. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1015. three pattern variables (\texttt{child1}, \texttt{op}, and
  1016. \texttt{child2}). In general, each \code{case} consists of a
  1017. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1018. recursively defined to be one of the following: a pattern variable, a
  1019. class name followed by a pattern for each of its constructor's
  1020. arguments, or other literals\index{subject}{literals} such as strings
  1021. or lists.
  1022. %
  1023. The body of each \code{case} may contain arbitrary Python code. The
  1024. pattern variables can be used in the body, such as \code{op} in
  1025. \code{print(op)}.
  1026. %
  1027. \fi}
  1028. A \code{match} form may contain several clauses, as in the following
  1029. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1030. the AST. The \code{match} proceeds through the clauses in order,
  1031. checking whether the pattern can match the input AST. The body of the
  1032. first clause that matches is executed. The output of \code{leaf} for
  1033. several ASTs is shown on the right side of the following:
  1034. \begin{center}
  1035. \begin{minipage}{0.6\textwidth}
  1036. {\if\edition\racketEd
  1037. \begin{lstlisting}
  1038. (define (leaf arith)
  1039. (match arith
  1040. [(Int n) #t]
  1041. [(Prim 'read '()) #t]
  1042. [(Prim '- (list e1)) #f]
  1043. [(Prim '+ (list e1 e2)) #f]
  1044. [(Prim '- (list e1 e2)) #f]))
  1045. (leaf (Prim 'read '()))
  1046. (leaf (Prim '- (list (Int 8))))
  1047. (leaf (Int 8))
  1048. \end{lstlisting}
  1049. \fi}
  1050. {\if\edition\pythonEd\pythonColor
  1051. \begin{lstlisting}
  1052. def leaf(arith):
  1053. match arith:
  1054. case Constant(n):
  1055. return True
  1056. case Call(Name('input_int'), []):
  1057. return True
  1058. case UnaryOp(USub(), e1):
  1059. return False
  1060. case BinOp(e1, Add(), e2):
  1061. return False
  1062. case BinOp(e1, Sub(), e2):
  1063. return False
  1064. print(leaf(Call(Name('input_int'), [])))
  1065. print(leaf(UnaryOp(USub(), eight)))
  1066. print(leaf(Constant(8)))
  1067. \end{lstlisting}
  1068. \fi}
  1069. \end{minipage}
  1070. \vrule
  1071. \begin{minipage}{0.25\textwidth}
  1072. {\if\edition\racketEd
  1073. \begin{lstlisting}
  1074. #t
  1075. #f
  1076. #t
  1077. \end{lstlisting}
  1078. \fi}
  1079. {\if\edition\pythonEd\pythonColor
  1080. \begin{lstlisting}
  1081. True
  1082. False
  1083. True
  1084. \end{lstlisting}
  1085. \fi}
  1086. \end{minipage}
  1087. \index{subject}{True@\TRUE{}}
  1088. \index{subject}{False@\FALSE{}}
  1089. \end{center}
  1090. When constructing a \code{match} expression, we refer to the grammar
  1091. definition to identify which nonterminal we are expecting to match
  1092. against, and then we make sure that (1) we have one
  1093. \racket{clause}\python{case} for each alternative of that nonterminal
  1094. and (2) the pattern in each \racket{clause}\python{case}
  1095. corresponds to the corresponding right-hand side of a grammar
  1096. rule. For the \code{match} in the \code{leaf} function, we refer to
  1097. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1098. nonterminal has five alternatives, so the \code{match} has five
  1099. \racket{clauses}\python{cases}. The pattern in each
  1100. \racket{clause}\python{case} corresponds to the right-hand side of a
  1101. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1102. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1103. translating from grammars to patterns, replace nonterminals such as
  1104. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1105. \code{e2}).
  1106. \section{Recursive Functions}
  1107. \label{sec:recursion}
  1108. \index{subject}{recursive function}
  1109. Programs are inherently recursive. For example, an expression is often
  1110. made of smaller expressions. Thus, the natural way to process an
  1111. entire program is to use a recursive function. As a first example of
  1112. such a recursive function, we define the function \code{is\_exp} as
  1113. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1114. value and determine whether or not it is an expression in \LangInt{}.
  1115. %
  1116. We say that a function is defined by \emph{structural recursion} if
  1117. it is defined using a sequence of match \racket{clauses}\python{cases}
  1118. that correspond to a grammar and the body of each
  1119. \racket{clause}\python{case} makes a recursive call on each child
  1120. node.\footnote{This principle of structuring code according to the
  1121. data definition is advocated in the book \emph{How to Design
  1122. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1123. second function, named \code{stmt}, that recognizes whether a value
  1124. is a \LangInt{} statement.} \python{Finally, }
  1125. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1126. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1127. In general, we can write one recursive function to handle each
  1128. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1129. two examples at the bottom of the figure, the first is in
  1130. \LangInt{} and the second is not.
  1131. \begin{figure}[tp]
  1132. \begin{tcolorbox}[colback=white]
  1133. {\if\edition\racketEd
  1134. \begin{lstlisting}
  1135. (define (is_exp ast)
  1136. (match ast
  1137. [(Int n) #t]
  1138. [(Prim 'read '()) #t]
  1139. [(Prim '- (list e)) (is_exp e)]
  1140. [(Prim '+ (list e1 e2))
  1141. (and (is_exp e1) (is_exp e2))]
  1142. [(Prim '- (list e1 e2))
  1143. (and (is_exp e1) (is_exp e2))]
  1144. [else #f]))
  1145. (define (is_Lint ast)
  1146. (match ast
  1147. [(Program '() e) (is_exp e)]
  1148. [else #f]))
  1149. (is_Lint (Program '() ast1_1)
  1150. (is_Lint (Program '()
  1151. (Prim '* (list (Prim 'read '())
  1152. (Prim '+ (list (Int 8)))))))
  1153. \end{lstlisting}
  1154. \fi}
  1155. {\if\edition\pythonEd\pythonColor
  1156. \begin{lstlisting}
  1157. def is_exp(e):
  1158. match e:
  1159. case Constant(n):
  1160. return True
  1161. case Call(Name('input_int'), []):
  1162. return True
  1163. case UnaryOp(USub(), e1):
  1164. return is_exp(e1)
  1165. case BinOp(e1, Add(), e2):
  1166. return is_exp(e1) and is_exp(e2)
  1167. case BinOp(e1, Sub(), e2):
  1168. return is_exp(e1) and is_exp(e2)
  1169. case _:
  1170. return False
  1171. def stmt(s):
  1172. match s:
  1173. case Expr(Call(Name('print'), [e])):
  1174. return is_exp(e)
  1175. case Expr(e):
  1176. return is_exp(e)
  1177. case _:
  1178. return False
  1179. def is_Lint(p):
  1180. match p:
  1181. case Module(body):
  1182. return all([stmt(s) for s in body])
  1183. case _:
  1184. return False
  1185. print(is_Lint(Module([Expr(ast1_1)])))
  1186. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1187. UnaryOp(Add(), Constant(8))))])))
  1188. \end{lstlisting}
  1189. \fi}
  1190. \end{tcolorbox}
  1191. \caption{Example of recursive functions for \LangInt{}. These functions
  1192. recognize whether an AST is in \LangInt{}.}
  1193. \label{fig:exp-predicate}
  1194. \end{figure}
  1195. %% You may be tempted to merge the two functions into one, like this:
  1196. %% \begin{center}
  1197. %% \begin{minipage}{0.5\textwidth}
  1198. %% \begin{lstlisting}
  1199. %% (define (Lint ast)
  1200. %% (match ast
  1201. %% [(Int n) #t]
  1202. %% [(Prim 'read '()) #t]
  1203. %% [(Prim '- (list e)) (Lint e)]
  1204. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1205. %% [(Program '() e) (Lint e)]
  1206. %% [else #f]))
  1207. %% \end{lstlisting}
  1208. %% \end{minipage}
  1209. %% \end{center}
  1210. %% %
  1211. %% Sometimes such a trick will save a few lines of code, especially when
  1212. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1213. %% \emph{not} recommended because it can get you into trouble.
  1214. %% %
  1215. %% For example, the above function is subtly wrong:
  1216. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1217. %% returns true when it should return false.
  1218. \section{Interpreters}
  1219. \label{sec:interp_Lint}
  1220. \index{subject}{interpreter}
  1221. The behavior of a program is defined by the specification of the
  1222. programming language.
  1223. %
  1224. \racket{For example, the Scheme language is defined in the report by
  1225. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1226. reference manual~\citep{plt-tr}.}
  1227. %
  1228. \python{For example, the Python language is defined in the Python
  1229. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1230. %
  1231. In this book we use interpreters to specify each language that we
  1232. consider. An interpreter that is designated as the definition of a
  1233. language is called a \emph{definitional
  1234. interpreter}~\citep{reynolds72:_def_interp}.
  1235. \index{subject}{definitional interpreter} We warm up by creating a
  1236. definitional interpreter for the \LangInt{} language. This interpreter
  1237. serves as a second example of structural recursion. The definition of the
  1238. \code{interp\_Lint} function is shown in
  1239. figure~\ref{fig:interp_Lint}.
  1240. %
  1241. \racket{The body of the function is a match on the input program
  1242. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1243. which in turn has one match clause per grammar rule for \LangInt{}
  1244. expressions.}
  1245. %
  1246. \python{The body of the function matches on the \code{Module} AST node
  1247. and then invokes \code{interp\_stmt} on each statement in the
  1248. module. The \code{interp\_stmt} function includes a case for each
  1249. grammar rule of the \Stmt{} nonterminal, and it calls
  1250. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1251. function includes a case for each grammar rule of the \Exp{}
  1252. nonterminal. We use several auxiliary functions such as \code{add64}
  1253. and \code{input\_int} that are defined in the support code for this book.}
  1254. \begin{figure}[tp]
  1255. \begin{tcolorbox}[colback=white]
  1256. {\if\edition\racketEd
  1257. \begin{lstlisting}
  1258. (define (interp_exp e)
  1259. (match e
  1260. [(Int n) n]
  1261. [(Prim 'read '())
  1262. (define r (read))
  1263. (cond [(fixnum? r) r]
  1264. [else (error 'interp_exp "read expected an integer" r)])]
  1265. [(Prim '- (list e))
  1266. (define v (interp_exp e))
  1267. (fx- 0 v)]
  1268. [(Prim '+ (list e1 e2))
  1269. (define v1 (interp_exp e1))
  1270. (define v2 (interp_exp e2))
  1271. (fx+ v1 v2)]
  1272. [(Prim '- (list e1 e2))
  1273. (define v1 (interp_exp e1))
  1274. (define v2 (interp_exp e2))
  1275. (fx- v1 v2)]))
  1276. (define (interp_Lint p)
  1277. (match p
  1278. [(Program '() e) (interp_exp e)]))
  1279. \end{lstlisting}
  1280. \fi}
  1281. {\if\edition\pythonEd\pythonColor
  1282. \begin{lstlisting}
  1283. def interp_exp(e):
  1284. match e:
  1285. case BinOp(left, Add(), right):
  1286. l = interp_exp(left); r = interp_exp(right)
  1287. return add64(l, r)
  1288. case BinOp(left, Sub(), right):
  1289. l = interp_exp(left); r = interp_exp(right)
  1290. return sub64(l, r)
  1291. case UnaryOp(USub(), v):
  1292. return neg64(interp_exp(v))
  1293. case Constant(value):
  1294. return value
  1295. case Call(Name('input_int'), []):
  1296. return input_int()
  1297. def interp_stmt(s):
  1298. match s:
  1299. case Expr(Call(Name('print'), [arg])):
  1300. print(interp_exp(arg))
  1301. case Expr(value):
  1302. interp_exp(value)
  1303. def interp_Lint(p):
  1304. match p:
  1305. case Module(body):
  1306. for s in body:
  1307. interp_stmt(s)
  1308. \end{lstlisting}
  1309. \fi}
  1310. \end{tcolorbox}
  1311. \caption{Interpreter for the \LangInt{} language.}
  1312. \label{fig:interp_Lint}
  1313. \end{figure}
  1314. Let us consider the result of interpreting a few \LangInt{} programs. The
  1315. following program adds two integers:
  1316. {\if\edition\racketEd
  1317. \begin{lstlisting}
  1318. (+ 10 32)
  1319. \end{lstlisting}
  1320. \fi}
  1321. {\if\edition\pythonEd\pythonColor
  1322. \begin{lstlisting}
  1323. print(10 + 32)
  1324. \end{lstlisting}
  1325. \fi}
  1326. %
  1327. \noindent The result is \key{42}, the answer to life, the universe,
  1328. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1329. the Galaxy} by Douglas Adams.}
  1330. %
  1331. We wrote this program in concrete syntax, whereas the parsed
  1332. abstract syntax is
  1333. {\if\edition\racketEd
  1334. \begin{lstlisting}
  1335. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1336. \end{lstlisting}
  1337. \fi}
  1338. {\if\edition\pythonEd\pythonColor
  1339. \begin{lstlisting}
  1340. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1341. \end{lstlisting}
  1342. \fi}
  1343. The following program demonstrates that expressions may be nested within
  1344. each other, in this case nesting several additions and negations.
  1345. {\if\edition\racketEd
  1346. \begin{lstlisting}
  1347. (+ 10 (- (+ 12 20)))
  1348. \end{lstlisting}
  1349. \fi}
  1350. {\if\edition\pythonEd\pythonColor
  1351. \begin{lstlisting}
  1352. print(10 + -(12 + 20))
  1353. \end{lstlisting}
  1354. \fi}
  1355. %
  1356. \noindent What is the result of this program?
  1357. {\if\edition\racketEd
  1358. As mentioned previously, the \LangInt{} language does not support
  1359. arbitrarily large integers but only $63$-bit integers, so we
  1360. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1361. in Racket.
  1362. Suppose that
  1363. \[
  1364. n = 999999999999999999
  1365. \]
  1366. which indeed fits in $63$ bits. What happens when we run the
  1367. following program in our interpreter?
  1368. \begin{lstlisting}
  1369. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1370. \end{lstlisting}
  1371. It produces the following error:
  1372. \begin{lstlisting}
  1373. fx+: result is not a fixnum
  1374. \end{lstlisting}
  1375. We establish the convention that if running the definitional
  1376. interpreter on a program produces an error, then the meaning of that
  1377. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1378. error is a \code{trapped-error}. A compiler for the language is under
  1379. no obligation regarding programs with unspecified behavior; it does
  1380. not have to produce an executable, and if it does, that executable can
  1381. do anything. On the other hand, if the error is a
  1382. \code{trapped-error}, then the compiler must produce an executable and
  1383. it is required to report that an error occurred. To signal an error,
  1384. exit with a return code of \code{255}. The interpreters in chapters
  1385. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1386. \code{trapped-error}.
  1387. \fi}
  1388. % TODO: how to deal with too-large integers in the Python interpreter?
  1389. %% This convention applies to the languages defined in this
  1390. %% book, as a way to simplify the student's task of implementing them,
  1391. %% but this convention is not applicable to all programming languages.
  1392. %%
  1393. The last feature of the \LangInt{} language, the \READOP{} operation,
  1394. prompts the user of the program for an integer. Recall that program
  1395. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1396. \code{8}. So, if we run {\if\edition\racketEd
  1397. \begin{lstlisting}
  1398. (interp_Lint (Program '() ast1_1))
  1399. \end{lstlisting}
  1400. \fi}
  1401. {\if\edition\pythonEd\pythonColor
  1402. \begin{lstlisting}
  1403. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1404. \end{lstlisting}
  1405. \fi}
  1406. \noindent and if the input is \code{50}, the result is \code{42}.
  1407. We include the \READOP{} operation in \LangInt{} so that a clever
  1408. student cannot implement a compiler for \LangInt{} that simply runs
  1409. the interpreter during compilation to obtain the output and then
  1410. generates the trivial code to produce the output.\footnote{Yes, a
  1411. clever student did this in the first instance of this course!}
  1412. The job of a compiler is to translate a program in one language into a
  1413. program in another language so that the output program behaves the
  1414. same way as the input program. This idea is depicted in the
  1415. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1416. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1417. Given a compiler that translates from language $\mathcal{L}_1$ to
  1418. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1419. compiler must translate it into some program $P_2$ such that
  1420. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1421. same input $i$ yields the same output $o$.
  1422. \begin{equation} \label{eq:compile-correct}
  1423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1424. \node (p1) at (0, 0) {$P_1$};
  1425. \node (p2) at (3, 0) {$P_2$};
  1426. \node (o) at (3, -2.5) {$o$};
  1427. \path[->] (p1) edge [above] node {compile} (p2);
  1428. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1429. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1430. \end{tikzpicture}
  1431. \end{equation}
  1432. \python{We establish the convention that if running the definitional
  1433. interpreter on a program produces an error, then the meaning of that
  1434. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1435. unless the exception raised is a \code{TrappedError}. A compiler for
  1436. the language is under no obligation regarding programs with
  1437. unspecified behavior; it does not have to produce an executable, and
  1438. if it does, that executable can do anything. On the other hand, if
  1439. the error is a \code{TrappedError}, then the compiler must produce
  1440. an executable and it is required to report that an error
  1441. occurred. To signal an error, exit with a return code of \code{255}.
  1442. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1443. section \ref{sec:arrays} use \code{TrappedError}.}
  1444. In the next section we see our first example of a compiler.
  1445. \section{Example Compiler: A Partial Evaluator}
  1446. \label{sec:partial-evaluation}
  1447. In this section we consider a compiler that translates \LangInt{}
  1448. programs into \LangInt{} programs that may be more efficient. The
  1449. compiler eagerly computes the parts of the program that do not depend
  1450. on any inputs, a process known as \emph{partial
  1451. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1452. For example, given the following program
  1453. {\if\edition\racketEd
  1454. \begin{lstlisting}
  1455. (+ (read) (- (+ 5 3)))
  1456. \end{lstlisting}
  1457. \fi}
  1458. {\if\edition\pythonEd\pythonColor
  1459. \begin{lstlisting}
  1460. print(input_int() + -(5 + 3) )
  1461. \end{lstlisting}
  1462. \fi}
  1463. \noindent our compiler translates it into the program
  1464. {\if\edition\racketEd
  1465. \begin{lstlisting}
  1466. (+ (read) -8)
  1467. \end{lstlisting}
  1468. \fi}
  1469. {\if\edition\pythonEd\pythonColor
  1470. \begin{lstlisting}
  1471. print(input_int() + -8)
  1472. \end{lstlisting}
  1473. \fi}
  1474. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1475. evaluator for the \LangInt{} language. The output of the partial evaluator
  1476. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1477. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1478. whereas the code for partially evaluating the negation and addition
  1479. operations is factored into three auxiliary functions:
  1480. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1481. functions is the output of partially evaluating the children.
  1482. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1483. arguments are integers and if they are, perform the appropriate
  1484. arithmetic. Otherwise, they create an AST node for the arithmetic
  1485. operation.
  1486. \begin{figure}[tp]
  1487. \begin{tcolorbox}[colback=white]
  1488. {\if\edition\racketEd
  1489. \begin{lstlisting}
  1490. (define (pe_neg r)
  1491. (match r
  1492. [(Int n) (Int (fx- 0 n))]
  1493. [else (Prim '- (list r))]))
  1494. (define (pe_add r1 r2)
  1495. (match* (r1 r2)
  1496. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1497. [(_ _) (Prim '+ (list r1 r2))]))
  1498. (define (pe_sub r1 r2)
  1499. (match* (r1 r2)
  1500. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1501. [(_ _) (Prim '- (list r1 r2))]))
  1502. (define (pe_exp e)
  1503. (match e
  1504. [(Int n) (Int n)]
  1505. [(Prim 'read '()) (Prim 'read '())]
  1506. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1507. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1508. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1509. (define (pe_Lint p)
  1510. (match p
  1511. [(Program '() e) (Program '() (pe_exp e))]))
  1512. \end{lstlisting}
  1513. \fi}
  1514. {\if\edition\pythonEd\pythonColor
  1515. \begin{lstlisting}
  1516. def pe_neg(r):
  1517. match r:
  1518. case Constant(n):
  1519. return Constant(neg64(n))
  1520. case _:
  1521. return UnaryOp(USub(), r)
  1522. def pe_add(r1, r2):
  1523. match (r1, r2):
  1524. case (Constant(n1), Constant(n2)):
  1525. return Constant(add64(n1, n2))
  1526. case _:
  1527. return BinOp(r1, Add(), r2)
  1528. def pe_sub(r1, r2):
  1529. match (r1, r2):
  1530. case (Constant(n1), Constant(n2)):
  1531. return Constant(sub64(n1, n2))
  1532. case _:
  1533. return BinOp(r1, Sub(), r2)
  1534. def pe_exp(e):
  1535. match e:
  1536. case BinOp(left, Add(), right):
  1537. return pe_add(pe_exp(left), pe_exp(right))
  1538. case BinOp(left, Sub(), right):
  1539. return pe_sub(pe_exp(left), pe_exp(right))
  1540. case UnaryOp(USub(), v):
  1541. return pe_neg(pe_exp(v))
  1542. case Constant(value):
  1543. return e
  1544. case Call(Name('input_int'), []):
  1545. return e
  1546. def pe_stmt(s):
  1547. match s:
  1548. case Expr(Call(Name('print'), [arg])):
  1549. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1550. case Expr(value):
  1551. return Expr(pe_exp(value))
  1552. def pe_P_int(p):
  1553. match p:
  1554. case Module(body):
  1555. new_body = [pe_stmt(s) for s in body]
  1556. return Module(new_body)
  1557. \end{lstlisting}
  1558. \fi}
  1559. \end{tcolorbox}
  1560. \caption{A partial evaluator for \LangInt{}.}
  1561. \label{fig:pe-arith}
  1562. \end{figure}
  1563. To gain some confidence that the partial evaluator is correct, we can
  1564. test whether it produces programs that produce the same result as the
  1565. input programs. That is, we can test whether it satisfies the diagram
  1566. of \eqref{eq:compile-correct}.
  1567. %
  1568. {\if\edition\racketEd
  1569. The following code runs the partial evaluator on several examples and
  1570. tests the output program. The \texttt{parse-program} and
  1571. \texttt{assert} functions are defined in
  1572. appendix~\ref{appendix:utilities}.\\
  1573. \begin{minipage}{1.0\textwidth}
  1574. \begin{lstlisting}
  1575. (define (test_pe p)
  1576. (assert "testing pe_Lint"
  1577. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1578. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1579. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1580. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1581. \end{lstlisting}
  1582. \end{minipage}
  1583. \fi}
  1584. % TODO: python version of testing the PE
  1585. \begin{exercise}\normalfont\normalsize
  1586. Create three programs in the \LangInt{} language and test whether
  1587. partially evaluating them with \code{pe\_Lint} and then
  1588. interpreting them with \code{interp\_Lint} gives the same result
  1589. as directly interpreting them with \code{interp\_Lint}.
  1590. \end{exercise}
  1591. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1592. \chapter{Integers and Variables}
  1593. \label{ch:Lvar}
  1594. \setcounter{footnote}{0}
  1595. This chapter covers compiling a subset of
  1596. \racket{Racket}\python{Python} to x86-64 assembly
  1597. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1598. integer arithmetic and local variables. We often refer to x86-64
  1599. simply as x86. The chapter first describes the \LangVar{} language
  1600. (section~\ref{sec:s0}) and then introduces x86 assembly
  1601. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1602. discuss only the instructions needed for compiling \LangVar{}. We
  1603. introduce more x86 instructions in subsequent chapters. After
  1604. introducing \LangVar{} and x86, we reflect on their differences and
  1605. create a plan to break down the translation from \LangVar{} to x86
  1606. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1607. the chapter gives detailed hints regarding each step. We aim to give
  1608. enough hints that the well-prepared reader, together with a few
  1609. friends, can implement a compiler from \LangVar{} to x86 in a short
  1610. time. To suggest the scale of this first compiler, we note that the
  1611. instructor solution for the \LangVar{} compiler is approximately
  1612. \racket{500}\python{300} lines of code.
  1613. \section{The \LangVar{} Language}
  1614. \label{sec:s0}
  1615. \index{subject}{variable}
  1616. The \LangVar{} language extends the \LangInt{} language with
  1617. variables. The concrete syntax of the \LangVar{} language is defined
  1618. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1619. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1620. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1621. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1622. \key{-} is a unary operator, and \key{+} is a binary operator.
  1623. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1624. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1625. the top of the program.
  1626. %% The $\itm{info}$
  1627. %% field of the \key{Program} structure contains an \emph{association
  1628. %% list} (a list of key-value pairs) that is used to communicate
  1629. %% auxiliary data from one compiler pass the next.
  1630. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1631. exhibit several compilation techniques.
  1632. \newcommand{\LvarGrammarRacket}{
  1633. \begin{array}{rcl}
  1634. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1635. \end{array}
  1636. }
  1637. \newcommand{\LvarASTRacket}{
  1638. \begin{array}{rcl}
  1639. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1640. \end{array}
  1641. }
  1642. \newcommand{\LvarGrammarPython}{
  1643. \begin{array}{rcl}
  1644. \Exp &::=& \Var{} \\
  1645. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1646. \end{array}
  1647. }
  1648. \newcommand{\LvarASTPython}{
  1649. \begin{array}{rcl}
  1650. \Exp{} &::=& \VAR{\Var{}} \\
  1651. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1652. \end{array}
  1653. }
  1654. \begin{figure}[tp]
  1655. \centering
  1656. \begin{tcolorbox}[colback=white]
  1657. {\if\edition\racketEd
  1658. \[
  1659. \begin{array}{l}
  1660. \gray{\LintGrammarRacket{}} \\ \hline
  1661. \LvarGrammarRacket{} \\
  1662. \begin{array}{rcl}
  1663. \LangVarM{} &::=& \Exp
  1664. \end{array}
  1665. \end{array}
  1666. \]
  1667. \fi}
  1668. {\if\edition\pythonEd\pythonColor
  1669. \[
  1670. \begin{array}{l}
  1671. \gray{\LintGrammarPython} \\ \hline
  1672. \LvarGrammarPython \\
  1673. \begin{array}{rcl}
  1674. \LangVarM{} &::=& \Stmt^{*}
  1675. \end{array}
  1676. \end{array}
  1677. \]
  1678. \fi}
  1679. \end{tcolorbox}
  1680. \caption{The concrete syntax of \LangVar{}.}
  1681. \label{fig:Lvar-concrete-syntax}
  1682. \end{figure}
  1683. \begin{figure}[tp]
  1684. \centering
  1685. \begin{tcolorbox}[colback=white]
  1686. {\if\edition\racketEd
  1687. \[
  1688. \begin{array}{l}
  1689. \gray{\LintASTRacket{}} \\ \hline
  1690. \LvarASTRacket \\
  1691. \begin{array}{rcl}
  1692. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1693. \end{array}
  1694. \end{array}
  1695. \]
  1696. \fi}
  1697. {\if\edition\pythonEd\pythonColor
  1698. \[
  1699. \begin{array}{l}
  1700. \gray{\LintASTPython}\\ \hline
  1701. \LvarASTPython \\
  1702. \begin{array}{rcl}
  1703. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1704. \end{array}
  1705. \end{array}
  1706. \]
  1707. \fi}
  1708. \end{tcolorbox}
  1709. \caption{The abstract syntax of \LangVar{}.}
  1710. \label{fig:Lvar-syntax}
  1711. \end{figure}
  1712. {\if\edition\racketEd
  1713. Let us dive further into the syntax and semantics of the \LangVar{}
  1714. language. The \key{let} feature defines a variable for use within its
  1715. body and initializes the variable with the value of an expression.
  1716. The abstract syntax for \key{let} is shown in
  1717. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1718. \begin{lstlisting}
  1719. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1720. \end{lstlisting}
  1721. For example, the following program initializes \code{x} to $32$ and then
  1722. evaluates the body \code{(+ 10 x)}, producing $42$.
  1723. \begin{lstlisting}
  1724. (let ([x (+ 12 20)]) (+ 10 x))
  1725. \end{lstlisting}
  1726. \fi}
  1727. %
  1728. {\if\edition\pythonEd\pythonColor
  1729. %
  1730. The \LangVar{} language includes an assignment statement, which defines a
  1731. variable for use in later statements and initializes the variable with
  1732. the value of an expression. The abstract syntax for assignment is
  1733. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1734. assignment is \index{subject}{Assign@\texttt{Assign}}
  1735. \begin{lstlisting}
  1736. |$\itm{var}$| = |$\itm{exp}$|
  1737. \end{lstlisting}
  1738. For example, the following program initializes the variable \code{x}
  1739. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1740. \begin{lstlisting}
  1741. x = 12 + 20
  1742. print(10 + x)
  1743. \end{lstlisting}
  1744. \fi}
  1745. {\if\edition\racketEd
  1746. %
  1747. When there are multiple \key{let}s for the same variable, the closest
  1748. enclosing \key{let} is used. That is, variable definitions overshadow
  1749. prior definitions. Consider the following program with two \key{let}s
  1750. that define two variables named \code{x}. Can you figure out the
  1751. result?
  1752. \begin{lstlisting}
  1753. (let ([x 32]) (+ (let ([x 10]) x) x))
  1754. \end{lstlisting}
  1755. For the purposes of depicting which variable occurrences correspond to
  1756. which definitions, the following shows the \code{x}'s annotated with
  1757. subscripts to distinguish them. Double-check that your answer for the
  1758. previous program is the same as your answer for this annotated version
  1759. of the program.
  1760. \begin{lstlisting}
  1761. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1762. \end{lstlisting}
  1763. The initializing expression is always evaluated before the body of the
  1764. \key{let}, so in the following, the \key{read} for \code{x} is
  1765. performed before the \key{read} for \code{y}. Given the input
  1766. $52$ then $10$, the following produces $42$ (not $-42$).
  1767. \begin{lstlisting}
  1768. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1769. \end{lstlisting}
  1770. \fi}
  1771. \subsection{Extensible Interpreters via Method Overriding}
  1772. \label{sec:extensible-interp}
  1773. \index{subject}{method overriding}
  1774. To prepare for discussing the interpreter of \LangVar{}, we explain
  1775. why we implement it in an object-oriented style. Throughout this book
  1776. we define many interpreters, one for each language that we
  1777. study. Because each language builds on the prior one, there is a lot
  1778. of commonality between these interpreters. We want to write down the
  1779. common parts just once instead of many times. A naive interpreter for
  1780. \LangVar{} would handle the \racket{cases for variables and
  1781. \code{let}} \python{case for variables} but dispatch to an
  1782. interpreter for \LangInt{} in the rest of the cases. The following
  1783. code sketches this idea. (We explain the \code{env} parameter in
  1784. section~\ref{sec:interp-Lvar}.)
  1785. \begin{center}
  1786. {\if\edition\racketEd
  1787. \begin{minipage}{0.45\textwidth}
  1788. \begin{lstlisting}
  1789. (define ((interp_Lint env) e)
  1790. (match e
  1791. [(Prim '- (list e1))
  1792. (fx- 0 ((interp_Lint env) e1))]
  1793. ...))
  1794. \end{lstlisting}
  1795. \end{minipage}
  1796. \begin{minipage}{0.45\textwidth}
  1797. \begin{lstlisting}
  1798. (define ((interp_Lvar env) e)
  1799. (match e
  1800. [(Var x)
  1801. (dict-ref env x)]
  1802. [(Let x e body)
  1803. (define v ((interp_Lvar env) e))
  1804. (define env^ (dict-set env x v))
  1805. ((interp_Lvar env^) body)]
  1806. [else ((interp_Lint env) e)]))
  1807. \end{lstlisting}
  1808. \end{minipage}
  1809. \fi}
  1810. {\if\edition\pythonEd\pythonColor
  1811. \begin{minipage}{0.45\textwidth}
  1812. \begin{lstlisting}
  1813. def interp_Lint(e, env):
  1814. match e:
  1815. case UnaryOp(USub(), e1):
  1816. return - interp_Lint(e1, env)
  1817. ...
  1818. \end{lstlisting}
  1819. \end{minipage}
  1820. \begin{minipage}{0.45\textwidth}
  1821. \begin{lstlisting}
  1822. def interp_Lvar(e, env):
  1823. match e:
  1824. case Name(id):
  1825. return env[id]
  1826. case _:
  1827. return interp_Lint(e, env)
  1828. \end{lstlisting}
  1829. \end{minipage}
  1830. \fi}
  1831. \end{center}
  1832. The problem with this naive approach is that it does not handle
  1833. situations in which an \LangVar{} feature, such as a variable, is
  1834. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1835. in the following program.
  1836. {\if\edition\racketEd
  1837. \begin{lstlisting}
  1838. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1839. \end{lstlisting}
  1840. \fi}
  1841. {\if\edition\pythonEd\pythonColor
  1842. \begin{minipage}{1.0\textwidth}
  1843. \begin{lstlisting}
  1844. y = 10
  1845. print(-y)
  1846. \end{lstlisting}
  1847. \end{minipage}
  1848. \fi}
  1849. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1850. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1851. then it recursively calls \code{interp\_Lint} again on its argument.
  1852. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1853. an error!
  1854. To make our interpreters extensible we need something called
  1855. \emph{open recursion}\index{subject}{open recursion}, in which the
  1856. tying of the recursive knot is delayed until the functions are
  1857. composed. Object-oriented languages provide open recursion via method
  1858. overriding. The following code uses
  1859. method overriding to interpret \LangInt{} and \LangVar{} using
  1860. %
  1861. \racket{the
  1862. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1863. \index{subject}{class} feature of Racket.}%
  1864. %
  1865. \python{a Python \code{class} definition.}
  1866. %
  1867. We define one class for each language and define a method for
  1868. interpreting expressions inside each class. The class for \LangVar{}
  1869. inherits from the class for \LangInt{}, and the method
  1870. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1871. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1872. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1873. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1874. \code{interp\_exp} in \LangInt{}.
  1875. \begin{center}
  1876. \hspace{-20pt}
  1877. {\if\edition\racketEd
  1878. \begin{minipage}{0.45\textwidth}
  1879. \begin{lstlisting}
  1880. (define interp-Lint-class
  1881. (class object%
  1882. (define/public ((interp_exp env) e)
  1883. (match e
  1884. [(Prim '- (list e))
  1885. (fx- 0 ((interp_exp env) e))]
  1886. ...))
  1887. ...))
  1888. \end{lstlisting}
  1889. \end{minipage}
  1890. \begin{minipage}{0.45\textwidth}
  1891. \begin{lstlisting}
  1892. (define interp-Lvar-class
  1893. (class interp-Lint-class
  1894. (define/override ((interp_exp env) e)
  1895. (match e
  1896. [(Var x)
  1897. (dict-ref env x)]
  1898. [(Let x e body)
  1899. (define v ((interp_exp env) e))
  1900. (define env^ (dict-set env x v))
  1901. ((interp_exp env^) body)]
  1902. [else
  1903. (super (interp_exp env) e)]))
  1904. ...
  1905. ))
  1906. \end{lstlisting}
  1907. \end{minipage}
  1908. \fi}
  1909. {\if\edition\pythonEd\pythonColor
  1910. \begin{minipage}{0.45\textwidth}
  1911. \begin{lstlisting}
  1912. class InterpLint:
  1913. def interp_exp(e):
  1914. match e:
  1915. case UnaryOp(USub(), e1):
  1916. return neg64(self.interp_exp(e1))
  1917. ...
  1918. ...
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \begin{minipage}{0.45\textwidth}
  1922. \begin{lstlisting}
  1923. def InterpLvar(InterpLint):
  1924. def interp_exp(e):
  1925. match e:
  1926. case Name(id):
  1927. return env[id]
  1928. case _:
  1929. return super().interp_exp(e)
  1930. ...
  1931. \end{lstlisting}
  1932. \end{minipage}
  1933. \fi}
  1934. \end{center}
  1935. We return to the troublesome example, repeated here:
  1936. {\if\edition\racketEd
  1937. \begin{lstlisting}
  1938. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1939. \end{lstlisting}
  1940. \fi}
  1941. {\if\edition\pythonEd\pythonColor
  1942. \begin{lstlisting}
  1943. y = 10
  1944. print(-y)
  1945. \end{lstlisting}
  1946. \fi}
  1947. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1948. \racket{on this expression,}
  1949. \python{on the \code{-y} expression,}
  1950. %
  1951. which we call \code{e0}, by creating an object of the \LangVar{} class
  1952. and calling the \code{interp\_exp} method
  1953. {\if\edition\racketEd
  1954. \begin{lstlisting}
  1955. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1956. \end{lstlisting}
  1957. \fi}
  1958. {\if\edition\pythonEd\pythonColor
  1959. \begin{lstlisting}
  1960. InterpLvar().interp_exp(e0)
  1961. \end{lstlisting}
  1962. \fi}
  1963. \noindent To process the \code{-} operator, the default case of
  1964. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1965. method in \LangInt{}. But then for the recursive method call, it
  1966. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1967. \code{Var} node is handled correctly. Thus, method overriding gives us
  1968. the open recursion that we need to implement our interpreters in an
  1969. extensible way.
  1970. \subsection{Definitional Interpreter for \LangVar{}}
  1971. \label{sec:interp-Lvar}
  1972. Having justified the use of classes and methods to implement
  1973. interpreters, we revisit the definitional interpreter for \LangInt{}
  1974. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1975. create an interpreter for \LangVar{}, shown in
  1976. figure~\ref{fig:interp-Lvar}.
  1977. %
  1978. \python{We change the \code{interp\_stmt} method in the interpreter
  1979. for \LangInt{} to take two extra parameters named \code{env}, which
  1980. we discuss in the next paragraph, and \code{cont} for
  1981. \emph{continuation}, which is the technical name for what comes
  1982. after a particular point in a program. The \code{cont} parameter is
  1983. the list of statements that that follow the current statement. Note
  1984. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  1985. statement and passes the rest of the statements as the argument for
  1986. \code{cont}. This organization enables each statement to decide what
  1987. if anything should be evaluated after it, for example, allowing a
  1988. \code{return} statement to exit early from a function (see
  1989. Chapter~\ref{ch:Lfun}).}
  1990. The interpreter for \LangVar{} adds two new cases for
  1991. variables and \racket{\key{let}}\python{assignment}. For
  1992. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1993. value bound to a variable to all the uses of the variable. To
  1994. accomplish this, we maintain a mapping from variables to values called
  1995. an \emph{environment}\index{subject}{environment}.
  1996. %
  1997. We use
  1998. %
  1999. \racket{an association list (alist) }%
  2000. %
  2001. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2002. %
  2003. to represent the environment.
  2004. %
  2005. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2006. and the \code{racket/dict} package.}
  2007. %
  2008. The \code{interp\_exp} function takes the current environment,
  2009. \code{env}, as an extra parameter. When the interpreter encounters a
  2010. variable, it looks up the corresponding value in the environment. If
  2011. the variable is not in the environment (because the variable was not
  2012. defined) then the lookup will fail and the interpreter will
  2013. halt with an error. Recall that the compiler is not obligated to
  2014. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2015. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2016. prohibit access to undefined variables.}
  2017. %
  2018. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2019. initializing expression, extends the environment with the result
  2020. value bound to the variable, using \code{dict-set}, then evaluates
  2021. the body of the \key{Let}.}
  2022. %
  2023. \python{When the interpreter encounters an assignment, it evaluates
  2024. the initializing expression and then associates the resulting value
  2025. with the variable in the environment.}
  2026. \begin{figure}[tp]
  2027. \begin{tcolorbox}[colback=white]
  2028. {\if\edition\racketEd
  2029. \begin{lstlisting}
  2030. (define interp-Lint-class
  2031. (class object%
  2032. (super-new)
  2033. (define/public ((interp_exp env) e)
  2034. (match e
  2035. [(Int n) n]
  2036. [(Prim 'read '())
  2037. (define r (read))
  2038. (cond [(fixnum? r) r]
  2039. [else (error 'interp_exp "expected an integer" r)])]
  2040. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2041. [(Prim '+ (list e1 e2))
  2042. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2043. [(Prim '- (list e1 e2))
  2044. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2045. (define/public (interp_program p)
  2046. (match p
  2047. [(Program '() e) ((interp_exp '()) e)]))
  2048. ))
  2049. \end{lstlisting}
  2050. \fi}
  2051. {\if\edition\pythonEd\pythonColor
  2052. \begin{lstlisting}
  2053. class InterpLint:
  2054. def interp_exp(self, e, env):
  2055. match e:
  2056. case BinOp(left, Add(), right):
  2057. l = self.interp_exp(left, env)
  2058. r = self.interp_exp(right, env)
  2059. return add64(l, r)
  2060. case BinOp(left, Sub(), right):
  2061. l = self.interp_exp(left, env)
  2062. r = self.interp_exp(right, env)
  2063. return sub64(l, r)
  2064. case UnaryOp(USub(), v):
  2065. return neg64(self.interp_exp(v, env))
  2066. case Constant(value):
  2067. return value
  2068. case Call(Name('input_int'), []):
  2069. return int(input())
  2070. def interp_stmt(self, s, env, cont):
  2071. match s:
  2072. case Expr(Call(Name('print'), [arg])):
  2073. val = self.interp_exp(arg, env)
  2074. print(val, end='')
  2075. return self.interp_stmts(cont, env)
  2076. case Expr(value):
  2077. self.interp_exp(value, env)
  2078. return self.interp_stmts(cont, env)
  2079. case _:
  2080. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2081. def interp_stmts(self, ss, env):
  2082. match ss:
  2083. case []:
  2084. return 0
  2085. case [s, *ss]:
  2086. return self.interp_stmt(s, env, ss)
  2087. def interp(self, p):
  2088. match p:
  2089. case Module(body):
  2090. self.interp_stmts(body, {})
  2091. def interp_Lint(p):
  2092. return InterpLint().interp(p)
  2093. \end{lstlisting}
  2094. \fi}
  2095. \end{tcolorbox}
  2096. \caption{Interpreter for \LangInt{} as a class.}
  2097. \label{fig:interp-Lint-class}
  2098. \end{figure}
  2099. \begin{figure}[tp]
  2100. \begin{tcolorbox}[colback=white]
  2101. {\if\edition\racketEd
  2102. \begin{lstlisting}
  2103. (define interp-Lvar-class
  2104. (class interp-Lint-class
  2105. (super-new)
  2106. (define/override ((interp_exp env) e)
  2107. (match e
  2108. [(Var x) (dict-ref env x)]
  2109. [(Let x e body)
  2110. (define new-env (dict-set env x ((interp_exp env) e)))
  2111. ((interp_exp new-env) body)]
  2112. [else ((super interp_exp env) e)]))
  2113. ))
  2114. (define (interp_Lvar p)
  2115. (send (new interp-Lvar-class) interp_program p))
  2116. \end{lstlisting}
  2117. \fi}
  2118. {\if\edition\pythonEd\pythonColor
  2119. \begin{lstlisting}
  2120. class InterpLvar(InterpLint):
  2121. def interp_exp(self, e, env):
  2122. match e:
  2123. case Name(id):
  2124. return env[id]
  2125. case _:
  2126. return super().interp_exp(e, env)
  2127. def interp_stmt(self, s, env, cont):
  2128. match s:
  2129. case Assign([lhs], value):
  2130. env[lhs.id] = self.interp_exp(value, env)
  2131. return self.interp_stmts(cont, env)
  2132. case _:
  2133. return super().interp_stmt(s, env, cont)
  2134. def interp_Lvar(p):
  2135. return InterpLvar().interp(p)
  2136. \end{lstlisting}
  2137. \fi}
  2138. \end{tcolorbox}
  2139. \caption{Interpreter for the \LangVar{} language.}
  2140. \label{fig:interp-Lvar}
  2141. \end{figure}
  2142. {\if\edition\racketEd
  2143. \begin{figure}[tp]
  2144. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2145. \small
  2146. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2147. An \emph{association list} (called an alist) is a list of key-value pairs.
  2148. For example, we can map people to their ages with an alist
  2149. \index{subject}{alist}\index{subject}{association list}
  2150. \begin{lstlisting}[basicstyle=\ttfamily]
  2151. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2152. \end{lstlisting}
  2153. The \emph{dictionary} interface is for mapping keys to values.
  2154. Every alist implements this interface. \index{subject}{dictionary}
  2155. The package
  2156. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2157. provides many functions for working with dictionaries, such as
  2158. \begin{description}
  2159. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2160. returns the value associated with the given $\itm{key}$.
  2161. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2162. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2163. and otherwise is the same as $\itm{dict}$.
  2164. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2165. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2166. of keys and values in $\itm{dict}$. For example, the following
  2167. creates a new alist in which the ages are incremented:
  2168. \end{description}
  2169. \vspace{-10pt}
  2170. \begin{lstlisting}[basicstyle=\ttfamily]
  2171. (for/list ([(k v) (in-dict ages)])
  2172. (cons k (add1 v)))
  2173. \end{lstlisting}
  2174. \end{tcolorbox}
  2175. %\end{wrapfigure}
  2176. \caption{Association lists implement the dictionary interface.}
  2177. \label{fig:alist}
  2178. \end{figure}
  2179. \fi}
  2180. The goal for this chapter is to implement a compiler that translates
  2181. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2182. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2183. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2184. That is, they output the same integer $n$. We depict this correctness
  2185. criteria in the following diagram:
  2186. \[
  2187. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2188. \node (p1) at (0, 0) {$P_1$};
  2189. \node (p2) at (4, 0) {$P_2$};
  2190. \node (o) at (4, -2) {$n$};
  2191. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2192. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2193. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2194. \end{tikzpicture}
  2195. \]
  2196. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2197. compiling \LangVar{}.
  2198. \section{The \LangXInt{} Assembly Language}
  2199. \label{sec:x86}
  2200. \index{subject}{x86}
  2201. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2202. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2203. assembler.
  2204. %
  2205. A program begins with a \code{main} label followed by a sequence of
  2206. instructions. The \key{globl} directive makes the \key{main} procedure
  2207. externally visible so that the operating system can call it.
  2208. %
  2209. An x86 program is stored in the computer's memory. For our purposes,
  2210. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2211. values. The computer has a \emph{program counter}
  2212. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2213. \code{rip} register that points to the address of the next instruction
  2214. to be executed. For most instructions, the program counter is
  2215. incremented after the instruction is executed so that it points to the
  2216. next instruction in memory. Most x86 instructions take two operands,
  2217. each of which is an integer constant (called an \emph{immediate
  2218. value}\index{subject}{immediate value}), a
  2219. \emph{register}\index{subject}{register}, or a memory location.
  2220. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2221. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2222. && \key{r8} \MID \key{r9} \MID \key{r10}
  2223. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2224. \MID \key{r14} \MID \key{r15}}
  2225. \newcommand{\GrammarXInt}{
  2226. \begin{array}{rcl}
  2227. \Reg &::=& \allregisters{} \\
  2228. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2229. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2230. \key{subq} \; \Arg\key{,} \Arg \MID
  2231. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2232. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2233. \key{callq} \; \mathit{label} \MID
  2234. \key{retq} \MID
  2235. \key{jmp}\,\itm{label} \MID \\
  2236. && \itm{label}\key{:}\; \Instr
  2237. \end{array}
  2238. }
  2239. \begin{figure}[tp]
  2240. \begin{tcolorbox}[colback=white]
  2241. {\if\edition\racketEd
  2242. \[
  2243. \begin{array}{l}
  2244. \GrammarXInt \\
  2245. \begin{array}{lcl}
  2246. \LangXIntM{} &::= & \key{.globl main}\\
  2247. & & \key{main:} \; \Instr\ldots
  2248. \end{array}
  2249. \end{array}
  2250. \]
  2251. \fi}
  2252. {\if\edition\pythonEd\pythonColor
  2253. \[
  2254. \begin{array}{lcl}
  2255. \Reg &::=& \allregisters{} \\
  2256. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2257. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2258. \key{subq} \; \Arg\key{,} \Arg \MID
  2259. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2260. && \key{callq} \; \mathit{label} \MID
  2261. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2262. \LangXIntM{} &::= & \key{.globl main}\\
  2263. & & \key{main:} \; \Instr^{*}
  2264. \end{array}
  2265. \]
  2266. \fi}
  2267. \end{tcolorbox}
  2268. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2269. \label{fig:x86-int-concrete}
  2270. \end{figure}
  2271. A register is a special kind of variable that holds a 64-bit
  2272. value. There are 16 general-purpose registers in the computer; their
  2273. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2274. written with a percent sign, \key{\%}, followed by the register name,
  2275. for example \key{\%rax}.
  2276. An immediate value is written using the notation \key{\$}$n$ where $n$
  2277. is an integer.
  2278. %
  2279. %
  2280. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2281. which obtains the address stored in register $r$ and then adds $n$
  2282. bytes to the address. The resulting address is used to load or to store
  2283. to memory depending on whether it occurs as a source or destination
  2284. argument of an instruction.
  2285. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2286. the source $s$ and destination $d$, applies the arithmetic operation,
  2287. and then writes the result to the destination $d$. \index{subject}{instruction}
  2288. %
  2289. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2290. stores the result in $d$.
  2291. %
  2292. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2293. specified by the label, and $\key{retq}$ returns from a procedure to
  2294. its caller.
  2295. %
  2296. We discuss procedure calls in more detail further in this chapter and
  2297. in chapter~\ref{ch:Lfun}.
  2298. %
  2299. The last letter \key{q} indicates that these instructions operate on
  2300. quadwords, which are 64-bit values.
  2301. %
  2302. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2303. counter to the address of the instruction immediately after the
  2304. specified label.}
  2305. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2306. all the x86 instructions used in this book.
  2307. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2308. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2309. \lstinline{movq $10, %rax}
  2310. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2311. adds $32$ to the $10$ in \key{rax} and
  2312. puts the result, $42$, into \key{rax}.
  2313. %
  2314. The last instruction \key{retq} finishes the \key{main} function by
  2315. returning the integer in \key{rax} to the operating system. The
  2316. operating system interprets this integer as the program's exit
  2317. code. By convention, an exit code of 0 indicates that a program has
  2318. completed successfully, and all other exit codes indicate various
  2319. errors.
  2320. %
  2321. \racket{However, in this book we return the result of the program
  2322. as the exit code.}
  2323. \begin{figure}[tbp]
  2324. \begin{minipage}{0.45\textwidth}
  2325. \begin{tcolorbox}[colback=white]
  2326. \begin{lstlisting}
  2327. .globl main
  2328. main:
  2329. movq $10, %rax
  2330. addq $32, %rax
  2331. retq
  2332. \end{lstlisting}
  2333. \end{tcolorbox}
  2334. \end{minipage}
  2335. \caption{An x86 program that computes
  2336. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2337. \label{fig:p0-x86}
  2338. \end{figure}
  2339. We exhibit the use of memory for storing intermediate results in the
  2340. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2341. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2342. uses a region of memory called the \emph{procedure call stack}
  2343. (\emph{stack} for
  2344. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2345. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2346. for each procedure call. The memory layout for an individual frame is
  2347. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2348. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2349. address of the item at the top of the stack. In general, we use the
  2350. term \emph{pointer}\index{subject}{pointer} for something that
  2351. contains an address. The stack grows downward in memory, so we
  2352. increase the size of the stack by subtracting from the stack pointer.
  2353. In the context of a procedure call, the \emph{return
  2354. address}\index{subject}{return address} is the location of the
  2355. instruction that immediately follows the call instruction on the
  2356. caller side. The function call instruction, \code{callq}, pushes the
  2357. return address onto the stack prior to jumping to the procedure. The
  2358. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2359. pointer} and is used to access variables that are stored in the
  2360. frame of the current procedure call. The base pointer of the caller
  2361. is stored immediately after the return address.
  2362. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2363. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2364. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2365. $-16\key{(\%rbp)}$, and so on.
  2366. \begin{figure}[tbp]
  2367. \begin{minipage}{0.66\textwidth}
  2368. \begin{tcolorbox}[colback=white]
  2369. {\if\edition\racketEd
  2370. \begin{lstlisting}
  2371. start:
  2372. movq $10, -8(%rbp)
  2373. negq -8(%rbp)
  2374. movq -8(%rbp), %rax
  2375. addq $52, %rax
  2376. jmp conclusion
  2377. .globl main
  2378. main:
  2379. pushq %rbp
  2380. movq %rsp, %rbp
  2381. subq $16, %rsp
  2382. jmp start
  2383. conclusion:
  2384. addq $16, %rsp
  2385. popq %rbp
  2386. retq
  2387. \end{lstlisting}
  2388. \fi}
  2389. {\if\edition\pythonEd\pythonColor
  2390. \begin{lstlisting}
  2391. .globl main
  2392. main:
  2393. pushq %rbp
  2394. movq %rsp, %rbp
  2395. subq $16, %rsp
  2396. movq $10, -8(%rbp)
  2397. negq -8(%rbp)
  2398. movq -8(%rbp), %rax
  2399. addq $52, %rax
  2400. addq $16, %rsp
  2401. popq %rbp
  2402. retq
  2403. \end{lstlisting}
  2404. \fi}
  2405. \end{tcolorbox}
  2406. \end{minipage}
  2407. \caption{An x86 program that computes
  2408. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2409. \label{fig:p1-x86}
  2410. \end{figure}
  2411. \begin{figure}[tbp]
  2412. \begin{minipage}{0.66\textwidth}
  2413. \begin{tcolorbox}[colback=white]
  2414. \centering
  2415. \begin{tabular}{|r|l|} \hline
  2416. Position & Contents \\ \hline
  2417. $8$(\key{\%rbp}) & return address \\
  2418. $0$(\key{\%rbp}) & old \key{rbp} \\
  2419. $-8$(\key{\%rbp}) & variable $1$ \\
  2420. $-16$(\key{\%rbp}) & variable $2$ \\
  2421. \ldots & \ldots \\
  2422. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2423. \end{tabular}
  2424. \end{tcolorbox}
  2425. \end{minipage}
  2426. \caption{Memory layout of a frame.}
  2427. \label{fig:frame}
  2428. \end{figure}
  2429. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2430. is transferred from the operating system to the \code{main} function.
  2431. The operating system issues a \code{callq main} instruction that
  2432. pushes its return address on the stack and then jumps to
  2433. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2434. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2435. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2436. out of alignment (because the \code{callq} pushed the return address).
  2437. The first three instructions are the typical
  2438. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2439. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2440. pointer \code{rsp} and then saves the base pointer of the caller at
  2441. address \code{rsp} on the stack. The next instruction \code{movq
  2442. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2443. which is pointing to the location of the old base pointer. The
  2444. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2445. make enough room for storing variables. This program needs one
  2446. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2447. 16-byte-aligned, and then we are ready to make calls to other functions.
  2448. \racket{The last instruction of the prelude is \code{jmp start}, which
  2449. transfers control to the instructions that were generated from the
  2450. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2451. \racket{The first instruction under the \code{start} label is}
  2452. %
  2453. \python{The first instruction after the prelude is}
  2454. %
  2455. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2456. %
  2457. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2458. $1$ to $-10$.
  2459. %
  2460. The next instruction moves the $-10$ from variable $1$ into the
  2461. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2462. the value in \code{rax}, updating its contents to $42$.
  2463. \racket{The three instructions under the label \code{conclusion} are the
  2464. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2465. %
  2466. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2467. \code{main} function consists of the last three instructions.}
  2468. %
  2469. The first two restore the \code{rsp} and \code{rbp} registers to their
  2470. states at the beginning of the procedure. In particular,
  2471. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2472. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2473. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2474. \key{retq}, jumps back to the procedure that called this one and adds
  2475. $8$ to the stack pointer.
  2476. Our compiler needs a convenient representation for manipulating x86
  2477. programs, so we define an abstract syntax for x86, shown in
  2478. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2479. \LangXInt{}.
  2480. %
  2481. {\if\edition\pythonEd\pythonColor%
  2482. The main difference between this and the concrete syntax of \LangXInt{}
  2483. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2484. names, and register names are explicitly represented by strings.
  2485. \fi} %
  2486. {\if\edition\racketEd
  2487. The main difference between this and the concrete syntax of \LangXInt{}
  2488. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2489. front of every instruction. Instead instructions are grouped into
  2490. \emph{basic blocks}\index{subject}{basic block} with a
  2491. label associated with every basic block; this is why the \key{X86Program}
  2492. struct includes an alist mapping labels to basic blocks. The reason for this
  2493. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2494. introduce conditional branching. The \code{Block} structure includes
  2495. an $\itm{info}$ field that is not needed in this chapter but becomes
  2496. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2497. $\itm{info}$ field should contain an empty list.
  2498. \fi}
  2499. %
  2500. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2501. node includes an integer for representing the arity of the function,
  2502. that is, the number of arguments, which is helpful to know during
  2503. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2504. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2505. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2506. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2507. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2508. \MID \skey{r14} \MID \skey{r15}}
  2509. \newcommand{\ASTXIntRacket}{
  2510. \begin{array}{lcl}
  2511. \Reg &::=& \allregisters{} \\
  2512. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2513. \MID \DEREF{\Reg}{\Int} \\
  2514. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2515. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2516. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2517. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2518. &\MID& \PUSHQ{\Arg}
  2519. \MID \POPQ{\Arg} \\
  2520. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2521. \MID \RETQ{}
  2522. \MID \JMP{\itm{label}} \\
  2523. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2524. \end{array}
  2525. }
  2526. \newcommand{\ASTXIntPython}{
  2527. \begin{array}{lcl}
  2528. \Reg &::=& \allregisters{} \\
  2529. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2530. \MID \DEREF{\Reg}{\Int} \\
  2531. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2532. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2533. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2534. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2535. &\MID& \PUSHQ{\Arg}
  2536. \MID \POPQ{\Arg} \\
  2537. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2538. \MID \RETQ{}
  2539. \MID \JMP{\itm{label}} \\
  2540. \Block &::= & \Instr^{+}
  2541. \end{array}
  2542. }
  2543. \begin{figure}[tp]
  2544. \begin{tcolorbox}[colback=white]
  2545. \small
  2546. {\if\edition\racketEd
  2547. \[\arraycolsep=3pt
  2548. \begin{array}{l}
  2549. \ASTXIntRacket \\
  2550. \begin{array}{lcl}
  2551. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2552. \end{array}
  2553. \end{array}
  2554. \]
  2555. \fi}
  2556. {\if\edition\pythonEd\pythonColor
  2557. \[
  2558. \begin{array}{lcl}
  2559. \Reg &::=& \allastregisters{} \\
  2560. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2561. \MID \DEREF{\Reg}{\Int} \\
  2562. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2563. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2564. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2565. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2566. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2567. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2568. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2569. \end{array}
  2570. \]
  2571. \fi}
  2572. \end{tcolorbox}
  2573. \caption{The abstract syntax of \LangXInt{} assembly.}
  2574. \label{fig:x86-int-ast}
  2575. \end{figure}
  2576. \section{Planning the Trip to x86}
  2577. \label{sec:plan-s0-x86}
  2578. To compile one language to another, it helps to focus on the
  2579. differences between the two languages because the compiler will need
  2580. to bridge those differences. What are the differences between \LangVar{}
  2581. and x86 assembly? Here are some of the most important ones:
  2582. \begin{enumerate}
  2583. \item x86 arithmetic instructions typically have two arguments and
  2584. update the second argument in place. In contrast, \LangVar{}
  2585. arithmetic operations take two arguments and produce a new value.
  2586. An x86 instruction may have at most one memory-accessing argument.
  2587. Furthermore, some x86 instructions place special restrictions on
  2588. their arguments.
  2589. \item An argument of an \LangVar{} operator can be a deeply nested
  2590. expression, whereas x86 instructions restrict their arguments to be
  2591. integer constants, registers, and memory locations.
  2592. {\if\edition\racketEd
  2593. \item The order of execution in x86 is explicit in the syntax, which
  2594. is a sequence of instructions and jumps to labeled positions,
  2595. whereas in \LangVar{} the order of evaluation is a left-to-right
  2596. depth-first traversal of the abstract syntax tree. \fi}
  2597. \item A program in \LangVar{} can have any number of variables,
  2598. whereas x86 has 16 registers and the procedure call stack.
  2599. {\if\edition\racketEd
  2600. \item Variables in \LangVar{} can shadow other variables with the
  2601. same name. In x86, registers have unique names, and memory locations
  2602. have unique addresses.
  2603. \fi}
  2604. \end{enumerate}
  2605. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2606. down the problem into several steps, which deal with these differences
  2607. one at a time. Each of these steps is called a \emph{pass} of the
  2608. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2609. %
  2610. This term indicates that each step passes over, or traverses, the AST
  2611. of the program.
  2612. %
  2613. Furthermore, we follow the nanopass approach, which means that we
  2614. strive for each pass to accomplish one clear objective rather than two
  2615. or three at the same time.
  2616. %
  2617. We begin by sketching how we might implement each pass and give each
  2618. pass a name. We then figure out an ordering of the passes and the
  2619. input/output language for each pass. The very first pass has
  2620. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2621. its output language. In between these two passes, we can choose
  2622. whichever language is most convenient for expressing the output of
  2623. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2624. \emph{intermediate language} of our own design. Finally, to
  2625. implement each pass we write one recursive function per nonterminal in
  2626. the grammar of the input language of the pass.
  2627. \index{subject}{intermediate language}
  2628. Our compiler for \LangVar{} consists of the following passes:
  2629. %
  2630. \begin{description}
  2631. {\if\edition\racketEd
  2632. \item[\key{uniquify}] deals with the shadowing of variables by
  2633. renaming every variable to a unique name.
  2634. \fi}
  2635. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2636. of a primitive operation or function call is a variable or integer,
  2637. that is, an \emph{atomic} expression. We refer to nonatomic
  2638. expressions as \emph{complex}. This pass introduces temporary
  2639. variables to hold the results of complex
  2640. subexpressions.\index{subject}{atomic
  2641. expression}\index{subject}{complex expression}%
  2642. {\if\edition\racketEd
  2643. \item[\key{explicate\_control}] makes the execution order of the
  2644. program explicit. It converts the abstract syntax tree
  2645. representation into a graph in which each node is a labeled sequence
  2646. of statements and the edges are \code{goto} statements.
  2647. \fi}
  2648. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2649. handles the difference between
  2650. \LangVar{} operations and x86 instructions. This pass converts each
  2651. \LangVar{} operation to a short sequence of instructions that
  2652. accomplishes the same task.
  2653. \item[\key{assign\_homes}] replaces variables with registers or stack
  2654. locations.
  2655. \end{description}
  2656. %
  2657. {\if\edition\racketEd
  2658. %
  2659. Our treatment of \code{remove\_complex\_operands} and
  2660. \code{explicate\_control} as separate passes is an example of the
  2661. nanopass approach.\footnote{For analogous decompositions of the
  2662. translation into continuation passing style, see the work of
  2663. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2664. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2665. %
  2666. \fi}
  2667. The next question is, in what order should we apply these passes? This
  2668. question can be challenging because it is difficult to know ahead of
  2669. time which orderings will be better (that is, will be easier to
  2670. implement, produce more efficient code, and so on), and therefore
  2671. ordering often involves trial and error. Nevertheless, we can plan
  2672. ahead and make educated choices regarding the ordering.
  2673. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2674. \key{uniquify}? The \key{uniquify} pass should come first because
  2675. \key{explicate\_control} changes all the \key{let}-bound variables to
  2676. become local variables whose scope is the entire program, which would
  2677. confuse variables with the same name.}
  2678. %
  2679. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2680. because the later removes the \key{let} form, but it is convenient to
  2681. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2682. %
  2683. \racket{The ordering of \key{uniquify} with respect to
  2684. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2685. \key{uniquify} to come first.}
  2686. The \key{select\_instructions} and \key{assign\_homes} passes are
  2687. intertwined.
  2688. %
  2689. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2690. passing arguments to functions and that it is preferable to assign
  2691. parameters to their corresponding registers. This suggests that it
  2692. would be better to start with the \key{select\_instructions} pass,
  2693. which generates the instructions for argument passing, before
  2694. performing register allocation.
  2695. %
  2696. On the other hand, by selecting instructions first we may run into a
  2697. dead end in \key{assign\_homes}. Recall that only one argument of an
  2698. x86 instruction may be a memory access, but \key{assign\_homes} might
  2699. be forced to assign both arguments to memory locations.
  2700. %
  2701. A sophisticated approach is to repeat the two passes until a solution
  2702. is found. However, to reduce implementation complexity we recommend
  2703. placing \key{select\_instructions} first, followed by the
  2704. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2705. that uses a reserved register to fix outstanding problems.
  2706. \begin{figure}[tbp]
  2707. \begin{tcolorbox}[colback=white]
  2708. {\if\edition\racketEd
  2709. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2710. \node (Lvar) at (0,2) {\large \LangVar{}};
  2711. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2712. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2713. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2714. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2715. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2716. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2717. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2718. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2719. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2720. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2721. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2722. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2723. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2724. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2725. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2726. \end{tikzpicture}
  2727. \fi}
  2728. {\if\edition\pythonEd\pythonColor
  2729. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2730. \node (Lvar) at (0,2) {\large \LangVar{}};
  2731. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2732. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2733. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2734. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2735. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2736. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2737. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2738. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2739. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2740. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2741. \end{tikzpicture}
  2742. \fi}
  2743. \end{tcolorbox}
  2744. \caption{Diagram of the passes for compiling \LangVar{}. }
  2745. \label{fig:Lvar-passes}
  2746. \end{figure}
  2747. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2748. passes and identifies the input and output language of each pass.
  2749. %
  2750. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2751. language, which extends \LangXInt{} with an unbounded number of
  2752. program-scope variables and removes the restrictions regarding
  2753. instruction arguments.
  2754. %
  2755. The last pass, \key{prelude\_and\_conclusion}, places the program
  2756. instructions inside a \code{main} function with instructions for the
  2757. prelude and conclusion.
  2758. %
  2759. \racket{In the next section we discuss the \LangCVar{} intermediate
  2760. language that serves as the output of \code{explicate\_control}.}
  2761. %
  2762. The remainder of this chapter provides guidance on the implementation
  2763. of each of the compiler passes represented in
  2764. figure~\ref{fig:Lvar-passes}.
  2765. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2766. %% are programs that are still in the \LangVar{} language, though the
  2767. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2768. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2769. %% %
  2770. %% The output of \code{explicate\_control} is in an intermediate language
  2771. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2772. %% syntax, which we introduce in the next section. The
  2773. %% \key{select-instruction} pass translates from \LangCVar{} to
  2774. %% \LangXVar{}. The \key{assign-homes} and
  2775. %% \key{patch-instructions}
  2776. %% passes input and output variants of x86 assembly.
  2777. \newcommand{\CvarGrammarRacket}{
  2778. \begin{array}{lcl}
  2779. \Atm &::=& \Int \MID \Var \\
  2780. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2781. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2782. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2783. \end{array}
  2784. }
  2785. \newcommand{\CvarASTRacket}{
  2786. \begin{array}{lcl}
  2787. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2788. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2789. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2790. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2791. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2792. \end{array}
  2793. }
  2794. {\if\edition\racketEd
  2795. \subsection{The \LangCVar{} Intermediate Language}
  2796. The output of \code{explicate\_control} is similar to the C
  2797. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2798. categories for expressions and statements, so we name it \LangCVar{}.
  2799. This style of intermediate language is also known as
  2800. \emph{three-address code}, to emphasize that the typical form of a
  2801. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2802. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2803. The concrete syntax for \LangCVar{} is shown in
  2804. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2805. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2806. %
  2807. The \LangCVar{} language supports the same operators as \LangVar{} but
  2808. the arguments of operators are restricted to atomic
  2809. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2810. assignment statements that can be executed in sequence using the
  2811. \key{Seq} form. A sequence of statements always ends with
  2812. \key{Return}, a guarantee that is baked into the grammar rules for
  2813. \itm{tail}. The naming of this nonterminal comes from the term
  2814. \emph{tail position}\index{subject}{tail position}, which refers to an
  2815. expression that is the last one to execute within a function or
  2816. program.
  2817. A \LangCVar{} program consists of an alist mapping labels to
  2818. tails. This is more general than necessary for the present chapter, as
  2819. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2820. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2821. there is just one label, \key{start}, and the whole program is
  2822. its tail.
  2823. %
  2824. The $\itm{info}$ field of the \key{CProgram} form, after the
  2825. \code{explicate\_control} pass, contains an alist that associates the
  2826. symbol \key{locals} with a list of all the variables used in the
  2827. program. At the start of the program, these variables are
  2828. uninitialized; they become initialized on their first assignment.
  2829. \begin{figure}[tbp]
  2830. \begin{tcolorbox}[colback=white]
  2831. \[
  2832. \begin{array}{l}
  2833. \CvarGrammarRacket \\
  2834. \begin{array}{lcl}
  2835. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2836. \end{array}
  2837. \end{array}
  2838. \]
  2839. \end{tcolorbox}
  2840. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2841. \label{fig:c0-concrete-syntax}
  2842. \end{figure}
  2843. \begin{figure}[tbp]
  2844. \begin{tcolorbox}[colback=white]
  2845. \[
  2846. \begin{array}{l}
  2847. \CvarASTRacket \\
  2848. \begin{array}{lcl}
  2849. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2850. \end{array}
  2851. \end{array}
  2852. \]
  2853. \end{tcolorbox}
  2854. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2855. \label{fig:c0-syntax}
  2856. \end{figure}
  2857. The definitional interpreter for \LangCVar{} is in the support code,
  2858. in the file \code{interp-Cvar.rkt}.
  2859. \fi}
  2860. {\if\edition\racketEd
  2861. \section{Uniquify Variables}
  2862. \label{sec:uniquify-Lvar}
  2863. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2864. with a unique name. Both the input and output of the \code{uniquify}
  2865. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2866. should translate the program on the left into the program on the
  2867. right.
  2868. \begin{transformation}
  2869. \begin{lstlisting}
  2870. (let ([x 32])
  2871. (+ (let ([x 10]) x) x))
  2872. \end{lstlisting}
  2873. \compilesto
  2874. \begin{lstlisting}
  2875. (let ([x.1 32])
  2876. (+ (let ([x.2 10]) x.2) x.1))
  2877. \end{lstlisting}
  2878. \end{transformation}
  2879. The following is another example translation, this time of a program
  2880. with a \key{let} nested inside the initializing expression of another
  2881. \key{let}.
  2882. \begin{transformation}
  2883. \begin{lstlisting}
  2884. (let ([x (let ([x 4])
  2885. (+ x 1))])
  2886. (+ x 2))
  2887. \end{lstlisting}
  2888. \compilesto
  2889. \begin{lstlisting}
  2890. (let ([x.2 (let ([x.1 4])
  2891. (+ x.1 1))])
  2892. (+ x.2 2))
  2893. \end{lstlisting}
  2894. \end{transformation}
  2895. We recommend implementing \code{uniquify} by creating a structurally
  2896. recursive function named \code{uniquify\_exp} that does little other
  2897. than copy an expression. However, when encountering a \key{let}, it
  2898. should generate a unique name for the variable and associate the old
  2899. name with the new name in an alist.\footnote{The Racket function
  2900. \code{gensym} is handy for generating unique variable names.} The
  2901. \code{uniquify\_exp} function needs to access this alist when it gets
  2902. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2903. for the alist.
  2904. The skeleton of the \code{uniquify\_exp} function is shown in
  2905. figure~\ref{fig:uniquify-Lvar}.
  2906. %% The function is curried so that it is
  2907. %% convenient to partially apply it to an alist and then apply it to
  2908. %% different expressions, as in the last case for primitive operations in
  2909. %% figure~\ref{fig:uniquify-Lvar}.
  2910. The
  2911. %
  2912. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2913. %
  2914. form of Racket is useful for transforming the element of a list to
  2915. produce a new list.\index{subject}{for/list}
  2916. \begin{figure}[tbp]
  2917. \begin{tcolorbox}[colback=white]
  2918. \begin{lstlisting}
  2919. (define (uniquify_exp env)
  2920. (lambda (e)
  2921. (match e
  2922. [(Var x) ___]
  2923. [(Int n) (Int n)]
  2924. [(Let x e body) ___]
  2925. [(Prim op es)
  2926. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2927. (define (uniquify p)
  2928. (match p
  2929. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2930. \end{lstlisting}
  2931. \end{tcolorbox}
  2932. \caption{Skeleton for the \key{uniquify} pass.}
  2933. \label{fig:uniquify-Lvar}
  2934. \end{figure}
  2935. \begin{exercise}
  2936. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2937. Complete the \code{uniquify} pass by filling in the blanks in
  2938. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2939. variables and for the \key{let} form in the file \code{compiler.rkt}
  2940. in the support code.
  2941. \end{exercise}
  2942. \begin{exercise}
  2943. \normalfont\normalsize
  2944. \label{ex:Lvar}
  2945. Create five \LangVar{} programs that exercise the most interesting
  2946. parts of the \key{uniquify} pass; that is, the programs should include
  2947. \key{let} forms, variables, and variables that shadow each other.
  2948. The five programs should be placed in the subdirectory named
  2949. \key{tests}, and the file names should start with \code{var\_test\_}
  2950. followed by a unique integer and end with the file extension
  2951. \key{.rkt}.
  2952. %
  2953. The \key{run-tests.rkt} script in the support code checks whether the
  2954. output programs produce the same result as the input programs. The
  2955. script uses the \key{interp-tests} function
  2956. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2957. your \key{uniquify} pass on the example programs. The \code{passes}
  2958. parameter of \key{interp-tests} is a list that should have one entry
  2959. for each pass in your compiler. For now, define \code{passes} to
  2960. contain just one entry for \code{uniquify} as follows:
  2961. \begin{lstlisting}
  2962. (define passes
  2963. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2964. \end{lstlisting}
  2965. Run the \key{run-tests.rkt} script in the support code to check
  2966. whether the output programs produce the same result as the input
  2967. programs.
  2968. \end{exercise}
  2969. \fi}
  2970. \section{Remove Complex Operands}
  2971. \label{sec:remove-complex-opera-Lvar}
  2972. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2973. into a restricted form in which the arguments of operations are atomic
  2974. expressions. Put another way, this pass removes complex
  2975. operands\index{subject}{complex operand}, such as the expression
  2976. \racket{\code{(- 10)}}\python{\code{-10}}
  2977. in the following program. This is accomplished by introducing a new
  2978. temporary variable, assigning the complex operand to the new
  2979. variable, and then using the new variable in place of the complex
  2980. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2981. right.
  2982. {\if\edition\racketEd
  2983. \begin{transformation}
  2984. % var_test_19.rkt
  2985. \begin{lstlisting}
  2986. (let ([x (+ 42 (- 10))])
  2987. (+ x 10))
  2988. \end{lstlisting}
  2989. \compilesto
  2990. \begin{lstlisting}
  2991. (let ([x (let ([tmp.1 (- 10)])
  2992. (+ 42 tmp.1))])
  2993. (+ x 10))
  2994. \end{lstlisting}
  2995. \end{transformation}
  2996. \fi}
  2997. {\if\edition\pythonEd\pythonColor
  2998. \begin{transformation}
  2999. \begin{lstlisting}
  3000. x = 42 + -10
  3001. print(x + 10)
  3002. \end{lstlisting}
  3003. \compilesto
  3004. \begin{lstlisting}
  3005. tmp_0 = -10
  3006. x = 42 + tmp_0
  3007. tmp_1 = x + 10
  3008. print(tmp_1)
  3009. \end{lstlisting}
  3010. \end{transformation}
  3011. \fi}
  3012. \newcommand{\LvarMonadASTRacket}{
  3013. \begin{array}{rcl}
  3014. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3015. \Exp &::=& \Atm \MID \READ{} \\
  3016. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3017. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3018. \end{array}
  3019. }
  3020. \newcommand{\LvarMonadASTPython}{
  3021. \begin{array}{rcl}
  3022. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3023. \Exp{} &::=& \Atm \MID \READ{} \\
  3024. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3025. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3026. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3027. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3028. \end{array}
  3029. }
  3030. \begin{figure}[tp]
  3031. \centering
  3032. \begin{tcolorbox}[colback=white]
  3033. {\if\edition\racketEd
  3034. \[
  3035. \begin{array}{l}
  3036. \LvarMonadASTRacket \\
  3037. \begin{array}{rcl}
  3038. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3039. \end{array}
  3040. \end{array}
  3041. \]
  3042. \fi}
  3043. {\if\edition\pythonEd\pythonColor
  3044. \[
  3045. \begin{array}{l}
  3046. \LvarMonadASTPython \\
  3047. \begin{array}{rcl}
  3048. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3049. \end{array}
  3050. \end{array}
  3051. \]
  3052. \fi}
  3053. \end{tcolorbox}
  3054. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3055. atomic expressions.}
  3056. \label{fig:Lvar-anf-syntax}
  3057. \end{figure}
  3058. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3059. of this pass, the language \LangVarANF{}. The only difference is that
  3060. operator arguments are restricted to be atomic expressions that are
  3061. defined by the \Atm{} nonterminal. In particular, integer constants
  3062. and variables are atomic.
  3063. The atomic expressions are pure (they do not cause or depend on side
  3064. effects) whereas complex expressions may have side effects, such as
  3065. \READ{}. A language with this separation between pure expressions
  3066. versus expressions with side effects is said to be in monadic normal
  3067. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3068. in the name \LangVarANF{}. An important invariant of the
  3069. \code{remove\_complex\_operands} pass is that the relative ordering
  3070. among complex expressions is not changed, but the relative ordering
  3071. between atomic expressions and complex expressions can change and
  3072. often does. The reason that these changes are behavior preserving is
  3073. that the atomic expressions are pure.
  3074. {\if\edition\racketEd
  3075. Another well-known form for intermediate languages is the
  3076. \emph{administrative normal form}
  3077. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3078. \index{subject}{administrative normal form} \index{subject}{ANF}
  3079. %
  3080. The \LangVarANF{} language is not quite in ANF because it allows the
  3081. right-hand side of a \code{let} to be a complex expression, such as
  3082. another \code{let}. The flattening of nested \code{let} expressions is
  3083. instead one of the responsibilities of the \code{explicate\_control}
  3084. pass.
  3085. \fi}
  3086. {\if\edition\racketEd
  3087. We recommend implementing this pass with two mutually recursive
  3088. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3089. \code{rco\_atom} to subexpressions that need to become atomic and to
  3090. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3091. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3092. returns an expression. The \code{rco\_atom} function returns two
  3093. things: an atomic expression and an alist mapping temporary variables to
  3094. complex subexpressions. You can return multiple things from a function
  3095. using Racket's \key{values} form, and you can receive multiple things
  3096. from a function call using the \key{define-values} form.
  3097. \fi}
  3098. %
  3099. {\if\edition\pythonEd\pythonColor
  3100. %
  3101. We recommend implementing this pass with an auxiliary method named
  3102. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3103. Boolean that specifies whether the expression needs to become atomic
  3104. or not. The \code{rco\_exp} method should return a pair consisting of
  3105. the new expression and a list of pairs, associating new temporary
  3106. variables with their initializing expressions.
  3107. %
  3108. \fi}
  3109. {\if\edition\racketEd
  3110. %
  3111. In the example program with the expression \code{(+ 42 (-
  3112. 10))}, the subexpression \code{(- 10)} should be processed using the
  3113. \code{rco\_atom} function because it is an argument of the \code{+}
  3114. operator and therefore needs to become atomic. The output of
  3115. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3116. \begin{transformation}
  3117. \begin{lstlisting}
  3118. (- 10)
  3119. \end{lstlisting}
  3120. \compilesto
  3121. \begin{lstlisting}
  3122. tmp.1
  3123. ((tmp.1 . (- 10)))
  3124. \end{lstlisting}
  3125. \end{transformation}
  3126. \fi}
  3127. %
  3128. {\if\edition\pythonEd\pythonColor
  3129. %
  3130. Returning to the example program with the expression \code{42 + -10},
  3131. the subexpression \code{-10} should be processed using the
  3132. \code{rco\_exp} function with \code{True} as the second argument,
  3133. because \code{-10} is an argument of the \code{+} operator and
  3134. therefore needs to become atomic. The output of \code{rco\_exp}
  3135. applied to \code{-10} is as follows.
  3136. \begin{transformation}
  3137. \begin{lstlisting}
  3138. -10
  3139. \end{lstlisting}
  3140. \compilesto
  3141. \begin{lstlisting}
  3142. tmp_1
  3143. [(tmp_1, -10)]
  3144. \end{lstlisting}
  3145. \end{transformation}
  3146. %
  3147. \fi}
  3148. Take special care of programs, such as the following, that
  3149. %
  3150. \racket{bind a variable to an atomic expression.}
  3151. %
  3152. \python{assign an atomic expression to a variable.}
  3153. %
  3154. You should leave such \racket{variable bindings}\python{assignments}
  3155. unchanged, as shown in the program on the right:\\
  3156. %
  3157. {\if\edition\racketEd
  3158. \begin{transformation}
  3159. % var_test_20.rkt
  3160. \begin{lstlisting}
  3161. (let ([a 42])
  3162. (let ([b a])
  3163. b))
  3164. \end{lstlisting}
  3165. \compilesto
  3166. \begin{lstlisting}
  3167. (let ([a 42])
  3168. (let ([b a])
  3169. b))
  3170. \end{lstlisting}
  3171. \end{transformation}
  3172. \fi}
  3173. {\if\edition\pythonEd\pythonColor
  3174. \begin{transformation}
  3175. \begin{lstlisting}
  3176. a = 42
  3177. b = a
  3178. print(b)
  3179. \end{lstlisting}
  3180. \compilesto
  3181. \begin{lstlisting}
  3182. a = 42
  3183. b = a
  3184. print(b)
  3185. \end{lstlisting}
  3186. \end{transformation}
  3187. \fi}
  3188. %
  3189. \noindent A careless implementation might produce the following output with
  3190. unnecessary temporary variables.
  3191. \begin{center}
  3192. \begin{minipage}{0.4\textwidth}
  3193. {\if\edition\racketEd
  3194. \begin{lstlisting}
  3195. (let ([tmp.1 42])
  3196. (let ([a tmp.1])
  3197. (let ([tmp.2 a])
  3198. (let ([b tmp.2])
  3199. b))))
  3200. \end{lstlisting}
  3201. \fi}
  3202. {\if\edition\pythonEd\pythonColor
  3203. \begin{lstlisting}
  3204. tmp_1 = 42
  3205. a = tmp_1
  3206. tmp_2 = a
  3207. b = tmp_2
  3208. print(b)
  3209. \end{lstlisting}
  3210. \fi}
  3211. \end{minipage}
  3212. \end{center}
  3213. \begin{exercise}
  3214. \normalfont\normalsize
  3215. {\if\edition\racketEd
  3216. Implement the \code{remove\_complex\_operands} function in
  3217. \code{compiler.rkt}.
  3218. %
  3219. Create three new \LangVar{} programs that exercise the interesting
  3220. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3221. regarding file names described in exercise~\ref{ex:Lvar}.
  3222. %
  3223. In the \code{run-tests.rkt} script, add the following entry to the
  3224. list of \code{passes}, and then run the script to test your compiler.
  3225. \begin{lstlisting}
  3226. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3227. \end{lstlisting}
  3228. In debugging your compiler, it is often useful to see the intermediate
  3229. programs that are output from each pass. To print the intermediate
  3230. programs, place \lstinline{(debug-level 1)} before the call to
  3231. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3232. %
  3233. {\if\edition\pythonEd\pythonColor
  3234. Implement the \code{remove\_complex\_operands} pass in
  3235. \code{compiler.py}, creating auxiliary functions for each
  3236. nonterminal in the grammar, that is, \code{rco\_exp}
  3237. and \code{rco\_stmt}. We recommend that you use the function
  3238. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3239. \fi}
  3240. \end{exercise}
  3241. {\if\edition\pythonEd\pythonColor
  3242. \begin{exercise}
  3243. \normalfont\normalsize
  3244. \label{ex:Lvar}
  3245. Create five \LangVar{} programs that exercise the most interesting
  3246. parts of the \code{remove\_complex\_operands} pass. The five programs
  3247. should be placed in the subdirectory named \key{tests}, and the file
  3248. names should start with \code{var\_test\_} followed by a unique
  3249. integer and end with the file extension \key{.py}.
  3250. %% The \key{run-tests.rkt} script in the support code checks whether the
  3251. %% output programs produce the same result as the input programs. The
  3252. %% script uses the \key{interp-tests} function
  3253. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3254. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3255. %% parameter of \key{interp-tests} is a list that should have one entry
  3256. %% for each pass in your compiler. For now, define \code{passes} to
  3257. %% contain just one entry for \code{uniquify} as shown below.
  3258. %% \begin{lstlisting}
  3259. %% (define passes
  3260. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3261. %% \end{lstlisting}
  3262. Run the \key{run-tests.py} script in the support code to check
  3263. whether the output programs produce the same result as the input
  3264. programs.
  3265. \end{exercise}
  3266. \fi}
  3267. {\if\edition\racketEd
  3268. \section{Explicate Control}
  3269. \label{sec:explicate-control-Lvar}
  3270. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3271. programs that make the order of execution explicit in their
  3272. syntax. For now this amounts to flattening \key{let} constructs into a
  3273. sequence of assignment statements. For example, consider the following
  3274. \LangVar{} program:\\
  3275. % var_test_11.rkt
  3276. \begin{minipage}{0.96\textwidth}
  3277. \begin{lstlisting}
  3278. (let ([y (let ([x 20])
  3279. (+ x (let ([x 22]) x)))])
  3280. y)
  3281. \end{lstlisting}
  3282. \end{minipage}\\
  3283. %
  3284. The output of the previous pass is shown next, on the left, and the
  3285. output of \code{explicate\_control} is on the right. Recall that the
  3286. right-hand side of a \key{let} executes before its body, so that the order
  3287. of evaluation for this program is to assign \code{20} to \code{x.1},
  3288. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3289. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3290. this ordering explicit.
  3291. \begin{transformation}
  3292. \begin{lstlisting}
  3293. (let ([y (let ([x.1 20])
  3294. (let ([x.2 22])
  3295. (+ x.1 x.2)))])
  3296. y)
  3297. \end{lstlisting}
  3298. \compilesto
  3299. \begin{lstlisting}[language=C]
  3300. start:
  3301. x.1 = 20;
  3302. x.2 = 22;
  3303. y = (+ x.1 x.2);
  3304. return y;
  3305. \end{lstlisting}
  3306. \end{transformation}
  3307. \begin{figure}[tbp]
  3308. \begin{tcolorbox}[colback=white]
  3309. \begin{lstlisting}
  3310. (define (explicate_tail e)
  3311. (match e
  3312. [(Var x) ___]
  3313. [(Int n) (Return (Int n))]
  3314. [(Let x rhs body) ___]
  3315. [(Prim op es) ___]
  3316. [else (error "explicate_tail unhandled case" e)]))
  3317. (define (explicate_assign e x cont)
  3318. (match e
  3319. [(Var x) ___]
  3320. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3321. [(Let y rhs body) ___]
  3322. [(Prim op es) ___]
  3323. [else (error "explicate_assign unhandled case" e)]))
  3324. (define (explicate_control p)
  3325. (match p
  3326. [(Program info body) ___]))
  3327. \end{lstlisting}
  3328. \end{tcolorbox}
  3329. \caption{Skeleton for the \code{explicate\_control} pass.}
  3330. \label{fig:explicate-control-Lvar}
  3331. \end{figure}
  3332. The organization of this pass depends on the notion of tail position
  3333. to which we have alluded. Here is the definition.
  3334. \begin{definition}\normalfont
  3335. The following rules define when an expression is in \emph{tail
  3336. position}\index{subject}{tail position} for the language \LangVar{}.
  3337. \begin{enumerate}
  3338. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3339. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3340. \end{enumerate}
  3341. \end{definition}
  3342. We recommend implementing \code{explicate\_control} using two
  3343. recursive functions, \code{explicate\_tail} and
  3344. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3345. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3346. function should be applied to expressions in tail position, whereas the
  3347. \code{explicate\_assign} should be applied to expressions that occur on
  3348. the right-hand side of a \key{let}.
  3349. %
  3350. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3351. input and produces a \Tail{} in \LangCVar{} (see
  3352. figure~\ref{fig:c0-syntax}).
  3353. %
  3354. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3355. the variable to which it is to be assigned, and a \Tail{} in
  3356. \LangCVar{} for the code that comes after the assignment. The
  3357. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3358. The \code{explicate\_assign} function is in accumulator-passing style:
  3359. the \code{cont} parameter is used for accumulating the output. This
  3360. accumulator-passing style plays an important role in the way that we
  3361. generate high-quality code for conditional expressions in
  3362. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3363. continuation because it contains the generated code that should come
  3364. after the current assignment. This code organization is also related
  3365. to continuation-passing style, except that \code{cont} is not what
  3366. happens next during compilation but is what happens next in the
  3367. generated code.
  3368. \begin{exercise}\normalfont\normalsize
  3369. %
  3370. Implement the \code{explicate\_control} function in
  3371. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3372. exercise the code in \code{explicate\_control}.
  3373. %
  3374. In the \code{run-tests.rkt} script, add the following entry to the
  3375. list of \code{passes} and then run the script to test your compiler.
  3376. \begin{lstlisting}
  3377. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3378. \end{lstlisting}
  3379. \end{exercise}
  3380. \fi}
  3381. \section{Select Instructions}
  3382. \label{sec:select-Lvar}
  3383. \index{subject}{select instructions}
  3384. In the \code{select\_instructions} pass we begin the work of
  3385. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3386. language of this pass is a variant of x86 that still uses variables,
  3387. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3388. nonterminal of the \LangXInt{} abstract syntax
  3389. (figure~\ref{fig:x86-int-ast}).
  3390. \racket{We recommend implementing the
  3391. \code{select\_instructions} with three auxiliary functions, one for
  3392. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3393. $\Tail$.}
  3394. \python{We recommend implementing an auxiliary function
  3395. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3396. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3397. same and integer constants change to immediates; that is, $\INT{n}$
  3398. changes to $\IMM{n}$.}
  3399. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3400. arithmetic operations. For example, consider the following addition
  3401. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3402. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3403. \key{addq} instruction in x86, but it performs an in-place update.
  3404. %
  3405. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3406. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into the
  3407. left-hand \itm{var}.
  3408. \begin{transformation}
  3409. {\if\edition\racketEd
  3410. \begin{lstlisting}
  3411. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3412. \end{lstlisting}
  3413. \fi}
  3414. {\if\edition\pythonEd\pythonColor
  3415. \begin{lstlisting}
  3416. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3417. \end{lstlisting}
  3418. \fi}
  3419. \compilesto
  3420. \begin{lstlisting}
  3421. movq |$\Arg_1$|, %rax
  3422. addq |$\Arg_2$|, %rax
  3423. movq %rax, |$\itm{var}$|
  3424. \end{lstlisting}
  3425. \end{transformation}
  3426. %
  3427. However, with some care we can generate shorter sequences of
  3428. instructions. Suppose that one or more of the arguments of the
  3429. addition is the same variable as the left-hand side of the assignment.
  3430. Then the assignment statement can be translated into a single
  3431. \key{addq} instruction, as follows.
  3432. \begin{transformation}
  3433. {\if\edition\racketEd
  3434. \begin{lstlisting}
  3435. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3436. \end{lstlisting}
  3437. \fi}
  3438. {\if\edition\pythonEd\pythonColor
  3439. \begin{lstlisting}
  3440. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3441. \end{lstlisting}
  3442. \fi}
  3443. \compilesto
  3444. \begin{lstlisting}
  3445. addq |$\Arg_1$|, |$\itm{var}$|
  3446. \end{lstlisting}
  3447. \end{transformation}
  3448. %
  3449. On the other hand, if $\Atm_1$ is not the same variable as the
  3450. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3451. and then add $\Arg_2$ to \itm{var}.
  3452. %
  3453. \begin{transformation}
  3454. {\if\edition\racketEd
  3455. \begin{lstlisting}
  3456. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3457. \end{lstlisting}
  3458. \fi}
  3459. {\if\edition\pythonEd\pythonColor
  3460. \begin{lstlisting}
  3461. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3462. \end{lstlisting}
  3463. \fi}
  3464. \compilesto
  3465. \begin{lstlisting}
  3466. movq |$\Arg_1$|, |$\itm{var}$|
  3467. addq |$\Arg_2$|, |$\itm{var}$|
  3468. \end{lstlisting}
  3469. \end{transformation}
  3470. The \READOP{} operation does not have a direct counterpart in x86
  3471. assembly, so we provide this functionality with the function
  3472. \code{read\_int} in the file \code{runtime.c}, written in
  3473. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3474. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3475. system}, or simply the \emph{runtime} for short. When compiling your
  3476. generated x86 assembly code, you need to compile \code{runtime.c} to
  3477. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3478. \code{-c}) and link it into the executable. For our purposes of code
  3479. generation, all you need to do is translate an assignment of
  3480. \READOP{} into a call to the \code{read\_int} function followed by a
  3481. move from \code{rax} to the left-hand side variable. (Recall that the
  3482. return value of a function goes into \code{rax}.)
  3483. \begin{transformation}
  3484. {\if\edition\racketEd
  3485. \begin{lstlisting}
  3486. |$\itm{var}$| = (read);
  3487. \end{lstlisting}
  3488. \fi}
  3489. {\if\edition\pythonEd\pythonColor
  3490. \begin{lstlisting}
  3491. |$\itm{var}$| = input_int();
  3492. \end{lstlisting}
  3493. \fi}
  3494. \compilesto
  3495. \begin{lstlisting}
  3496. callq read_int
  3497. movq %rax, |$\itm{var}$|
  3498. \end{lstlisting}
  3499. \end{transformation}
  3500. {\if\edition\pythonEd\pythonColor
  3501. %
  3502. Similarly, we translate the \code{print} operation, shown below, into
  3503. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3504. In x86, the first six arguments to functions are passed in registers,
  3505. with the first argument passed in register \code{rdi}. So we move the
  3506. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3507. \code{callq} instruction.
  3508. \begin{transformation}
  3509. \begin{lstlisting}
  3510. print(|$\Atm$|)
  3511. \end{lstlisting}
  3512. \compilesto
  3513. \begin{lstlisting}
  3514. movq |$\Arg$|, %rdi
  3515. callq print_int
  3516. \end{lstlisting}
  3517. \end{transformation}
  3518. %
  3519. \fi}
  3520. {\if\edition\racketEd
  3521. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3522. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3523. assignment to the \key{rax} register followed by a jump to the
  3524. conclusion of the program (so the conclusion needs to be labeled).
  3525. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3526. recursively and then append the resulting instructions.
  3527. \fi}
  3528. {\if\edition\pythonEd\pythonColor
  3529. We recommend that you use the function \code{utils.label\_name()} to
  3530. transform strings into labels, for example, in
  3531. the target of the \code{callq} instruction. This practice makes your
  3532. compiler portable across Linux and Mac OS X, which requires an underscore
  3533. prefixed to all labels.
  3534. \fi}
  3535. \begin{exercise}
  3536. \normalfont\normalsize
  3537. {\if\edition\racketEd
  3538. Implement the \code{select\_instructions} pass in
  3539. \code{compiler.rkt}. Create three new example programs that are
  3540. designed to exercise all the interesting cases in this pass.
  3541. %
  3542. In the \code{run-tests.rkt} script, add the following entry to the
  3543. list of \code{passes} and then run the script to test your compiler.
  3544. \begin{lstlisting}
  3545. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3546. \end{lstlisting}
  3547. \fi}
  3548. {\if\edition\pythonEd\pythonColor
  3549. Implement the \key{select\_instructions} pass in
  3550. \code{compiler.py}. Create three new example programs that are
  3551. designed to exercise all the interesting cases in this pass.
  3552. Run the \code{run-tests.py} script to check
  3553. whether the output programs produce the same result as the input
  3554. programs.
  3555. \fi}
  3556. \end{exercise}
  3557. \section{Assign Homes}
  3558. \label{sec:assign-Lvar}
  3559. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3560. \LangXVar{} programs that no longer use program variables. Thus, the
  3561. \code{assign\_homes} pass is responsible for placing all the program
  3562. variables in registers or on the stack. For runtime efficiency, it is
  3563. better to place variables in registers, but because there are only
  3564. sixteen registers, some programs must necessarily resort to placing
  3565. some variables on the stack. In this chapter we focus on the mechanics
  3566. of placing variables on the stack. We study an algorithm for placing
  3567. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3568. Consider again the following \LangVar{} program from
  3569. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3570. % var_test_20.rkt
  3571. \begin{minipage}{0.96\textwidth}
  3572. {\if\edition\racketEd
  3573. \begin{lstlisting}
  3574. (let ([a 42])
  3575. (let ([b a])
  3576. b))
  3577. \end{lstlisting}
  3578. \fi}
  3579. {\if\edition\pythonEd\pythonColor
  3580. \begin{lstlisting}
  3581. a = 42
  3582. b = a
  3583. print(b)
  3584. \end{lstlisting}
  3585. \fi}
  3586. \end{minipage}\\
  3587. %
  3588. The output of \code{select\_instructions} is shown next, on the left,
  3589. and the output of \code{assign\_homes} is on the right. In this
  3590. example, we assign variable \code{a} to stack location
  3591. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3592. \begin{transformation}
  3593. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3594. movq $42, a
  3595. movq a, b
  3596. movq b, %rax
  3597. \end{lstlisting}
  3598. \compilesto
  3599. %stack-space: 16
  3600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3601. movq $42, -8(%rbp)
  3602. movq -8(%rbp), -16(%rbp)
  3603. movq -16(%rbp), %rax
  3604. \end{lstlisting}
  3605. \end{transformation}
  3606. \racket{
  3607. The \code{assign\_homes} pass should replace all variables
  3608. with stack locations.
  3609. The list of variables can be obtained from
  3610. the \code{locals-types} entry in the $\itm{info}$ of the
  3611. \code{X86Program} node. The \code{locals-types} entry is an alist
  3612. mapping all the variables in the program to their types
  3613. (for now, just \code{Integer}).
  3614. As an aside, the \code{locals-types} entry is
  3615. computed by \code{type-check-Cvar} in the support code, which
  3616. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3617. which you should propagate to the \code{X86Program} node.}
  3618. %
  3619. \python{The \code{assign\_homes} pass should replace all uses of
  3620. variables with stack locations.}
  3621. %
  3622. In the process of assigning variables to stack locations, it is
  3623. convenient for you to compute and store the size of the frame (in
  3624. bytes) in
  3625. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3626. %
  3627. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3628. %
  3629. which is needed later to generate the conclusion of the \code{main}
  3630. procedure. The x86-64 standard requires the frame size to be a
  3631. multiple of 16 bytes.\index{subject}{frame}
  3632. % TODO: store the number of variables instead? -Jeremy
  3633. \begin{exercise}\normalfont\normalsize
  3634. Implement the \code{assign\_homes} pass in
  3635. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3636. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3637. grammar. We recommend that the auxiliary functions take an extra
  3638. parameter that maps variable names to homes (stack locations for now).
  3639. %
  3640. {\if\edition\racketEd
  3641. In the \code{run-tests.rkt} script, add the following entry to the
  3642. list of \code{passes} and then run the script to test your compiler.
  3643. \begin{lstlisting}
  3644. (list "assign homes" assign-homes interp_x86-0)
  3645. \end{lstlisting}
  3646. \fi}
  3647. {\if\edition\pythonEd\pythonColor
  3648. Run the \code{run-tests.py} script to check
  3649. whether the output programs produce the same result as the input
  3650. programs.
  3651. \fi}
  3652. \end{exercise}
  3653. \section{Patch Instructions}
  3654. \label{sec:patch-s0}
  3655. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3656. \LangXInt{} by making sure that each instruction adheres to the
  3657. restriction that at most one argument of an instruction may be a
  3658. memory reference.
  3659. We return to the following example.\\
  3660. \begin{minipage}{0.5\textwidth}
  3661. % var_test_20.rkt
  3662. {\if\edition\racketEd
  3663. \begin{lstlisting}
  3664. (let ([a 42])
  3665. (let ([b a])
  3666. b))
  3667. \end{lstlisting}
  3668. \fi}
  3669. {\if\edition\pythonEd\pythonColor
  3670. \begin{lstlisting}
  3671. a = 42
  3672. b = a
  3673. print(b)
  3674. \end{lstlisting}
  3675. \fi}
  3676. \end{minipage}\\
  3677. The \code{assign\_homes} pass produces the following translation. \\
  3678. \begin{minipage}{0.5\textwidth}
  3679. {\if\edition\racketEd
  3680. \begin{lstlisting}
  3681. movq $42, -8(%rbp)
  3682. movq -8(%rbp), -16(%rbp)
  3683. movq -16(%rbp), %rax
  3684. \end{lstlisting}
  3685. \fi}
  3686. {\if\edition\pythonEd\pythonColor
  3687. \begin{lstlisting}
  3688. movq $42, -8(%rbp)
  3689. movq -8(%rbp), -16(%rbp)
  3690. movq -16(%rbp), %rdi
  3691. callq print_int
  3692. \end{lstlisting}
  3693. \fi}
  3694. \end{minipage}\\
  3695. The second \key{movq} instruction is problematic because both
  3696. arguments are stack locations. We suggest fixing this problem by
  3697. moving from the source location to the register \key{rax} and then
  3698. from \key{rax} to the destination location, as follows.
  3699. \begin{lstlisting}
  3700. movq -8(%rbp), %rax
  3701. movq %rax, -16(%rbp)
  3702. \end{lstlisting}
  3703. There is a similar corner case that also needs to be dealt with. If
  3704. one argument is an immediate integer larger than $2^{16}$ and the
  3705. other is a memory reference, then the instruction is invalid. One can
  3706. fix this, for example, by first moving the immediate integer into
  3707. \key{rax} and then using \key{rax} in place of the integer.
  3708. \begin{exercise}
  3709. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3710. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3711. Create three new example programs that are
  3712. designed to exercise all the interesting cases in this pass.
  3713. %
  3714. {\if\edition\racketEd
  3715. In the \code{run-tests.rkt} script, add the following entry to the
  3716. list of \code{passes} and then run the script to test your compiler.
  3717. \begin{lstlisting}
  3718. (list "patch instructions" patch_instructions interp_x86-0)
  3719. \end{lstlisting}
  3720. \fi}
  3721. {\if\edition\pythonEd\pythonColor
  3722. Run the \code{run-tests.py} script to check
  3723. whether the output programs produce the same result as the input
  3724. programs.
  3725. \fi}
  3726. \end{exercise}
  3727. \section{Generate Prelude and Conclusion}
  3728. \label{sec:print-x86}
  3729. \index{subject}{prelude}\index{subject}{conclusion}
  3730. The last step of the compiler from \LangVar{} to x86 is to generate
  3731. the \code{main} function with a prelude and conclusion wrapped around
  3732. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3733. discussed in section~\ref{sec:x86}.
  3734. When running on Mac OS X, your compiler should prefix an underscore to
  3735. all labels (for example, changing \key{main} to \key{\_main}).
  3736. %
  3737. \racket{The Racket call \code{(system-type 'os)} is useful for
  3738. determining which operating system the compiler is running on. It
  3739. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3740. %
  3741. \python{The Python \code{platform} library includes a \code{system()}
  3742. function that returns \code{\textquotesingle Linux\textquotesingle},
  3743. \code{\textquotesingle Windows\textquotesingle}, or
  3744. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3745. \begin{exercise}\normalfont\normalsize
  3746. %
  3747. Implement the \key{prelude\_and\_conclusion} pass in
  3748. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3749. %
  3750. {\if\edition\racketEd
  3751. In the \code{run-tests.rkt} script, add the following entry to the
  3752. list of \code{passes} and then run the script to test your compiler.
  3753. \begin{lstlisting}
  3754. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3755. \end{lstlisting}
  3756. %
  3757. Uncomment the call to the \key{compiler-tests} function
  3758. (appendix~\ref{appendix:utilities}), which tests your complete
  3759. compiler by executing the generated x86 code. It translates the x86
  3760. AST that you produce into a string by invoking the \code{print-x86}
  3761. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3762. the provided \key{runtime.c} file to \key{runtime.o} using
  3763. \key{gcc}. Run the script to test your compiler.
  3764. %
  3765. \fi}
  3766. {\if\edition\pythonEd\pythonColor
  3767. %
  3768. Run the \code{run-tests.py} script to check whether the output
  3769. programs produce the same result as the input programs. That script
  3770. translates the x86 AST that you produce into a string by invoking the
  3771. \code{repr} method that is implemented by the x86 AST classes in
  3772. \code{x86\_ast.py}.
  3773. %
  3774. \fi}
  3775. \end{exercise}
  3776. \section{Challenge: Partial Evaluator for \LangVar{}}
  3777. \label{sec:pe-Lvar}
  3778. \index{subject}{partialevaluation@partial evaluation}
  3779. This section describes two optional challenge exercises that involve
  3780. adapting and improving the partial evaluator for \LangInt{} that was
  3781. introduced in section~\ref{sec:partial-evaluation}.
  3782. \begin{exercise}\label{ex:pe-Lvar}
  3783. \normalfont\normalsize
  3784. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3785. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3786. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3787. %
  3788. \racket{\key{let} binding}\python{assignment}
  3789. %
  3790. to the \LangInt{} language, so you will need to add cases for them in
  3791. the \code{pe\_exp}
  3792. %
  3793. \racket{function.}
  3794. %
  3795. \python{and \code{pe\_stmt} functions.}
  3796. %
  3797. Once complete, add the partial evaluation pass to the front of your
  3798. compiler, and make sure that your compiler still passes all the
  3799. tests.
  3800. \end{exercise}
  3801. \begin{exercise}
  3802. \normalfont\normalsize
  3803. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3804. \code{pe\_add} auxiliary functions with functions that know more about
  3805. arithmetic. For example, your partial evaluator should translate
  3806. {\if\edition\racketEd
  3807. \[
  3808. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3809. \code{(+ 2 (read))}
  3810. \]
  3811. \fi}
  3812. {\if\edition\pythonEd\pythonColor
  3813. \[
  3814. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3815. \code{2 + input\_int()}
  3816. \]
  3817. \fi}
  3818. %
  3819. To accomplish this, the \code{pe\_exp} function should produce output
  3820. in the form of the $\itm{residual}$ nonterminal of the following
  3821. grammar. The idea is that when processing an addition expression, we
  3822. can always produce one of the following: (1) an integer constant, (2)
  3823. an addition expression with an integer constant on the left-hand side
  3824. but not the right-hand side, or (3) an addition expression in which
  3825. neither subexpression is a constant.
  3826. %
  3827. {\if\edition\racketEd
  3828. \[
  3829. \begin{array}{lcl}
  3830. \itm{inert} &::=& \Var
  3831. \MID \LP\key{read}\RP
  3832. \MID \LP\key{-} ~\Var\RP
  3833. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3834. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3835. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3836. \itm{residual} &::=& \Int
  3837. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3838. \MID \itm{inert}
  3839. \end{array}
  3840. \]
  3841. \fi}
  3842. {\if\edition\pythonEd\pythonColor
  3843. \[
  3844. \begin{array}{lcl}
  3845. \itm{inert} &::=& \Var
  3846. \MID \key{input\_int}\LP\RP
  3847. \MID \key{-} \Var
  3848. \MID \key{-} \key{input\_int}\LP\RP
  3849. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3850. \itm{residual} &::=& \Int
  3851. \MID \Int ~ \key{+} ~ \itm{inert}
  3852. \MID \itm{inert}
  3853. \end{array}
  3854. \]
  3855. \fi}
  3856. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3857. inputs are $\itm{residual}$ expressions and they should return
  3858. $\itm{residual}$ expressions. Once the improvements are complete,
  3859. make sure that your compiler still passes all the tests. After
  3860. all, fast code is useless if it produces incorrect results!
  3861. \end{exercise}
  3862. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3863. {\if\edition\pythonEd\pythonColor
  3864. \chapter{Parsing}
  3865. \label{ch:parsing}
  3866. \setcounter{footnote}{0}
  3867. \index{subject}{parsing}
  3868. In this chapter we learn how to use the Lark parser
  3869. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3870. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3871. You will then be asked to use Lark to create a parser for \LangVar{}.
  3872. We also describe the parsing algorithms used inside Lark, studying the
  3873. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3874. A parser framework such as Lark takes in a specification of the
  3875. concrete syntax and an input program and produces a parse tree. Even
  3876. though a parser framework does most of the work for us, using one
  3877. properly requires some knowledge. In particular, we must learn about
  3878. its specification languages and we must learn how to deal with
  3879. ambiguity in our language specifications. Also, some algorithms, such
  3880. as LALR(1), place restrictions on the grammars they can handle, in
  3881. which case knowing the algorithm help with trying to decipher the
  3882. error messages.
  3883. The process of parsing is traditionally subdivided into two phases:
  3884. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3885. analysis} (also called parsing). The lexical analysis phase
  3886. translates the sequence of characters into a sequence of
  3887. \emph{tokens}, that is, words consisting of several characters. The
  3888. parsing phase organizes the tokens into a \emph{parse tree} that
  3889. captures how the tokens were matched by rules in the grammar of the
  3890. language. The reason for the subdivision into two phases is to enable
  3891. the use of a faster but less powerful algorithm for lexical analysis
  3892. and the use of a slower but more powerful algorithm for parsing.
  3893. %
  3894. %% Likewise, parser generators typical come in pairs, with separate
  3895. %% generators for the lexical analyzer (or lexer for short) and for the
  3896. %% parser. A particularly influential pair of generators were
  3897. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3898. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3899. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3900. %% Compiler Compiler.
  3901. %
  3902. The Lark parser framework that we use in this chapter includes both
  3903. lexical analyzers and parsers. The next section discusses lexical
  3904. analysis, and the remainder of the chapter discusses parsing.
  3905. \section{Lexical Analysis and Regular Expressions}
  3906. \label{sec:lex}
  3907. The lexical analyzers produced by Lark turn a sequence of characters
  3908. (a string) into a sequence of token objects. For example, a Lark
  3909. generated lexer for \LangInt{} converts the string
  3910. \begin{lstlisting}
  3911. 'print(1 + 3)'
  3912. \end{lstlisting}
  3913. \noindent into the following sequence of token objects:
  3914. \begin{center}
  3915. \begin{minipage}{0.95\textwidth}
  3916. \begin{lstlisting}
  3917. Token('PRINT', 'print')
  3918. Token('LPAR', '(')
  3919. Token('INT', '1')
  3920. Token('PLUS', '+')
  3921. Token('INT', '3')
  3922. Token('RPAR', ')')
  3923. Token('NEWLINE', '\n')
  3924. \end{lstlisting}
  3925. \end{minipage}
  3926. \end{center}
  3927. Each token includes a field for its \code{type}, such as \skey{INT},
  3928. and a field for its \code{value}, such as \skey{1}.
  3929. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3930. specification language for Lark's lexer is one regular expression for
  3931. each type of token. The term \emph{regular} comes from the term
  3932. \emph{regular languages}, which are the languages that can be
  3933. recognized by a finite state machine. A \emph{regular expression} is a
  3934. pattern formed of the following core elements:\index{subject}{regular
  3935. expression}\footnote{Regular expressions traditionally include the
  3936. empty regular expression that matches any zero-length part of a
  3937. string, but Lark does not support the empty regular expression.}
  3938. \begin{itemize}
  3939. \item A single character $c$ is a regular expression, and it matches
  3940. only itself. For example, the regular expression \code{a} matches
  3941. only the string \skey{a}.
  3942. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3943. R_2$ form a regular expression that matches any string that matches
  3944. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3945. matches the string \skey{a} and the string \skey{c}.
  3946. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3947. expression that matches any string that can be formed by
  3948. concatenating two strings, where the first string matches $R_1$ and
  3949. the second string matches $R_2$. For example, the regular expression
  3950. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3951. (Parentheses can be used to control the grouping of operators within
  3952. a regular expression.)
  3953. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3954. Kleene closure) is a regular expression that matches any string that
  3955. can be formed by concatenating zero or more strings that each match
  3956. the regular expression $R$. For example, the regular expression
  3957. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3958. \skey{abc}.
  3959. \end{itemize}
  3960. For our convenience, Lark also accepts the following extended set of
  3961. regular expressions that are automatically translated into the core
  3962. regular expressions.
  3963. \begin{itemize}
  3964. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3965. c_n]$ is a regular expression that matches any one of the
  3966. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3967. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3968. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3969. a regular expression that matches any character between $c_1$ and
  3970. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3971. letter in the alphabet.
  3972. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3973. is a regular expression that matches any string that can
  3974. be formed by concatenating one or more strings that each match $R$.
  3975. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3976. matches \skey{b} and \skey{bzca}.
  3977. \item A regular expression followed by a question mark $R\ttm{?}$
  3978. is a regular expression that matches any string that either
  3979. matches $R$ or is the empty string.
  3980. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3981. \end{itemize}
  3982. In a Lark grammar file, each kind of token is specified by a
  3983. \emph{terminal}\index{subject}{terminal} which is defined by a rule
  3984. that consists of the name of the terminal followed by a colon followed
  3985. by a sequence of literals. The literals include strings such as
  3986. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  3987. terminal names, and literals composed using the regular expression
  3988. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  3989. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  3990. \begin{center}
  3991. \begin{minipage}{0.95\textwidth}
  3992. \begin{lstlisting}
  3993. DIGIT: /[0-9]/
  3994. INT: "-"? DIGIT+
  3995. NEWLINE: (/\r/? /\n/)+
  3996. \end{lstlisting}
  3997. \end{minipage}
  3998. \end{center}
  3999. \section{Grammars and Parse Trees}
  4000. \label{sec:CFG}
  4001. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4002. specify the abstract syntax of a language. We now take a closer look
  4003. at using grammar rules to specify the concrete syntax. Recall that
  4004. each rule has a left-hand side and a right-hand side where the
  4005. left-hand side is a nonterminal and the right-hand side is a pattern
  4006. that defines what can be parsed as that nonterminal. For concrete
  4007. syntax, each right-hand side expresses a pattern for a string, instead
  4008. of a pattern for an abstract syntax tree. In particular, each
  4009. right-hand side is a sequence of
  4010. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4011. terminal or a nonterminal. The nonterminals play the same role as in
  4012. the abstract syntax, defining categories of syntax. The nonterminals
  4013. of a grammar include the tokens defined in the lexer and all the
  4014. nonterminals defined by the grammar rules.
  4015. As an example, let us take a closer look at the concrete syntax of the
  4016. \LangInt{} language, repeated here.
  4017. \[
  4018. \begin{array}{l}
  4019. \LintGrammarPython \\
  4020. \begin{array}{rcl}
  4021. \LangInt{} &::=& \Stmt^{*}
  4022. \end{array}
  4023. \end{array}
  4024. \]
  4025. The Lark syntax for grammar rules differs slightly from the variant of
  4026. BNF that we use in this book. In particular, the notation $::=$ is
  4027. replaced by a single colon, and the use of typewriter font for string
  4028. literals is replaced by quotation marks. The following grammar serves
  4029. as a first draft of a Lark grammar for \LangInt{}.
  4030. \begin{center}
  4031. \begin{minipage}{0.95\textwidth}
  4032. \begin{lstlisting}[escapechar=$]
  4033. exp: INT
  4034. | "input_int" "(" ")"
  4035. | "-" exp
  4036. | exp "+" exp
  4037. | exp "-" exp
  4038. | "(" exp ")"
  4039. stmt_list:
  4040. | stmt NEWLINE stmt_list
  4041. lang_int: stmt_list
  4042. \end{lstlisting}
  4043. \end{minipage}
  4044. \end{center}
  4045. Let us begin by discussing the rule \code{exp: INT}, which says that
  4046. if the lexer matches a string to \code{INT}, then the parser also
  4047. categorizes the string as an \code{exp}. Recall that in
  4048. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4049. nonterminal with a sentence in English. Here we specify \code{INT}
  4050. more formally using a type of token \code{INT} and its regular
  4051. expression \code{"-"? DIGIT+}.
  4052. The rule \code{exp: exp "+" exp} says that any string that matches
  4053. \code{exp}, followed by the \code{+} character, followed by another
  4054. string that matches \code{exp}, is itself an \code{exp}. For example,
  4055. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4056. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4057. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4058. \code{exp}. We can visualize the application of grammar rules to parse
  4059. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4060. internal node in the tree is an application of a grammar rule and is
  4061. labeled with its left-hand side nonterminal. Each leaf node is a
  4062. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4063. shown in figure~\ref{fig:simple-parse-tree}.
  4064. \begin{figure}[tbp]
  4065. \begin{tcolorbox}[colback=white]
  4066. \centering
  4067. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4068. \end{tcolorbox}
  4069. \caption{The parse tree for \lstinline{'1+3'}.}
  4070. \label{fig:simple-parse-tree}
  4071. \end{figure}
  4072. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4073. following parse tree as represented by \code{Tree} and \code{Token}
  4074. objects.
  4075. \begin{lstlisting}
  4076. Tree('lang_int',
  4077. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4078. Tree('exp', [Token('INT', '3')])])]),
  4079. Token('NEWLINE', '\n')])
  4080. \end{lstlisting}
  4081. The nodes that come from the lexer are \code{Token} objects, whereas
  4082. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4083. object has a \code{data} field containing the name of the nonterminal
  4084. for the grammar rule that was applied. Each \code{Tree} object also
  4085. has a \code{children} field that is a list containing trees and/or
  4086. tokens. Note that Lark does not produce nodes for string literals in
  4087. the grammar. For example, the \code{Tree} node for the addition
  4088. expression has only two children for the two integers but is missing
  4089. its middle child for the \code{"+"} terminal. This would be
  4090. problematic except that Lark provides a mechanism for customizing the
  4091. \code{data} field of each \code{Tree} node on the basis of which rule was
  4092. applied. Next to each alternative in a grammar rule, write \code{->}
  4093. followed by a string that you want to appear in the \code{data}
  4094. field. The following is a second draft of a Lark grammar for
  4095. \LangInt{}, this time with more specific labels on the \code{Tree}
  4096. nodes.
  4097. \begin{center}
  4098. \begin{minipage}{0.95\textwidth}
  4099. \begin{lstlisting}[escapechar=$]
  4100. exp: INT -> int
  4101. | "input_int" "(" ")" -> input_int
  4102. | "-" exp -> usub
  4103. | exp "+" exp -> add
  4104. | exp "-" exp -> sub
  4105. | "(" exp ")" -> paren
  4106. stmt: "print" "(" exp ")" -> print
  4107. | exp -> expr
  4108. stmt_list: -> empty_stmt
  4109. | stmt NEWLINE stmt_list -> add_stmt
  4110. lang_int: stmt_list -> module
  4111. \end{lstlisting}
  4112. \end{minipage}
  4113. \end{center}
  4114. Here is the resulting parse tree.
  4115. \begin{lstlisting}
  4116. Tree('module',
  4117. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4118. Tree('int', [Token('INT', '3')])])]),
  4119. Token('NEWLINE', '\n')])
  4120. \end{lstlisting}
  4121. \section{Ambiguous Grammars}
  4122. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4123. can be parsed in more than one way. For example, consider the string
  4124. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4125. our draft grammar, resulting in the two parse trees shown in
  4126. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4127. interpreting the second parse tree would yield \code{-4} even through
  4128. the correct answer is \code{2}.
  4129. \begin{figure}[tbp]
  4130. \begin{tcolorbox}[colback=white]
  4131. \centering
  4132. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4133. \end{tcolorbox}
  4134. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4135. \label{fig:ambig-parse-tree}
  4136. \end{figure}
  4137. To deal with this problem we can change the grammar by categorizing
  4138. the syntax in a more fine-grained fashion. In this case we want to
  4139. disallow the application of the rule \code{exp: exp "-" exp} when the
  4140. child on the right is an addition. To do this we can replace the
  4141. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4142. the expressions except for addition, as in the following.
  4143. \begin{center}
  4144. \begin{minipage}{0.95\textwidth}
  4145. \begin{lstlisting}[escapechar=$]
  4146. exp: exp "-" exp_no_add -> sub
  4147. | exp "+" exp -> add
  4148. | exp_no_add
  4149. exp_no_add: INT -> int
  4150. | "input_int" "(" ")" -> input_int
  4151. | "-" exp -> usub
  4152. | exp "-" exp_no_add -> sub
  4153. | "(" exp ")" -> paren
  4154. \end{lstlisting}
  4155. \end{minipage}
  4156. \end{center}
  4157. However, there remains some ambiguity in the grammar. For example, the
  4158. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4159. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4160. (incorrect). That is, subtraction is left associative. Likewise,
  4161. addition in Python is left associative. We also need to consider the
  4162. interaction of unary subtraction with both addition and
  4163. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4164. has higher \emph{precedence}\index{subject}{precedence} than addition
  4165. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4166. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4167. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4168. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4169. all the other expressions, and it uses \code{exp\_hi} for the second
  4170. child in the rules for addition and subtraction. Furthermore, unary
  4171. subtraction uses \code{exp\_hi} for its child.
  4172. For languages with more operators and more precedence levels, one must
  4173. refine the \code{exp} nonterminal into several nonterminals, one for
  4174. each precedence level.
  4175. \begin{figure}[tbp]
  4176. \begin{tcolorbox}[colback=white]
  4177. \centering
  4178. \begin{lstlisting}[escapechar=$]
  4179. exp: exp "+" exp_hi -> add
  4180. | exp "-" exp_hi -> sub
  4181. | exp_hi
  4182. exp_hi: INT -> int
  4183. | "input_int" "(" ")" -> input_int
  4184. | "-" exp_hi -> usub
  4185. | "(" exp ")" -> paren
  4186. stmt: "print" "(" exp ")" -> print
  4187. | exp -> expr
  4188. stmt_list: -> empty_stmt
  4189. | stmt NEWLINE stmt_list -> add_stmt
  4190. lang_int: stmt_list -> module
  4191. \end{lstlisting}
  4192. \end{tcolorbox}
  4193. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4194. \label{fig:Lint-lark-grammar}
  4195. \end{figure}
  4196. \section{From Parse Trees to Abstract Syntax Trees}
  4197. As we have seen, the output of a Lark parser is a parse tree, that is,
  4198. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4199. step is to convert the parse tree to an abstract syntax tree. This can
  4200. be accomplished with a recursive function that inspects the
  4201. \code{data} field of each node and then constructs the corresponding
  4202. AST node, using recursion to handle its children. The following is an
  4203. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4204. \begin{center}
  4205. \begin{minipage}{0.95\textwidth}
  4206. \begin{lstlisting}
  4207. def parse_tree_to_ast(e):
  4208. if e.data == 'int':
  4209. return Constant(int(e.children[0].value))
  4210. elif e.data == 'input_int':
  4211. return Call(Name('input_int'), [])
  4212. elif e.data == 'add':
  4213. e1, e2 = e.children
  4214. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4215. ...
  4216. else:
  4217. raise Exception('unhandled parse tree', e)
  4218. \end{lstlisting}
  4219. \end{minipage}
  4220. \end{center}
  4221. \begin{exercise}
  4222. \normalfont\normalsize
  4223. %
  4224. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4225. default parsing algorithm (Earley) with the \code{ambiguity} option
  4226. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4227. output will include multiple parse trees that will indicate to you
  4228. that there is a problem with your grammar. Your parser should ignore
  4229. white space, so we recommend using Lark's \code{\%ignore} directive
  4230. as follows.
  4231. \begin{lstlisting}
  4232. WS: /[ \t\f\r\n]/+
  4233. %ignore WS
  4234. \end{lstlisting}
  4235. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4236. Lark parser instead of using the \code{parse} function from
  4237. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4238. programs that you have created, and create four additional programs
  4239. that test for ambiguities in your grammar.
  4240. \end{exercise}
  4241. \section{Earley's Algorithm}
  4242. \label{sec:earley}
  4243. In this section we discuss the parsing algorithm of
  4244. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4245. algorithm is powerful in that it can handle any context-free grammar,
  4246. which makes it easy to use. However, it is not a particularly
  4247. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4248. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4249. the number of tokens in the input
  4250. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4251. learn about the LALR(1) algorithm, which is more efficient but cannot
  4252. handle all context-free grammars.
  4253. Earley's algorithm can be viewed as an interpreter; it treats the
  4254. grammar as the program being interpreted and it treats the concrete
  4255. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4256. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4257. keep track of its progress and to store its results. The chart is an
  4258. array with one slot for each position in the input string, where
  4259. position $0$ is before the first character and position $n$ is
  4260. immediately after the last character. So, the array has length $n+1$
  4261. for an input string of length $n$. Each slot in the chart contains a
  4262. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4263. with a period indicating how much of its right-hand side has already
  4264. been parsed. For example, the dotted rule
  4265. \begin{lstlisting}
  4266. exp: exp "+" . exp_hi
  4267. \end{lstlisting}
  4268. represents a partial parse that has matched an \code{exp} followed by
  4269. \code{+}, but has not yet parsed an \code{exp} to the right of
  4270. \code{+}.
  4271. %
  4272. Earley's algorithm starts with an initialization phase, and then
  4273. repeats three actions---prediction, scanning, and completion---for as
  4274. long as opportunities arise. We demonstrate Earley's algorithm on a
  4275. running example, parsing the following program:
  4276. \begin{lstlisting}
  4277. print(1 + 3)
  4278. \end{lstlisting}
  4279. The algorithm's initialization phase creates dotted rules for all the
  4280. grammar rules whose left-hand side is the start symbol and places them
  4281. in slot $0$ of the chart. We also record the starting position of the
  4282. dotted rule in parentheses on the right. For example, given the
  4283. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4284. \begin{lstlisting}
  4285. lang_int: . stmt_list (0)
  4286. \end{lstlisting}
  4287. in slot $0$ of the chart. The algorithm then proceeds with
  4288. \emph{prediction} actions in which it adds more dotted rules to the
  4289. chart based on the nonterminals that come immediately after a period. In
  4290. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4291. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4292. period at the beginning of their right-hand sides, as follows:
  4293. \begin{lstlisting}
  4294. stmt_list: . (0)
  4295. stmt_list: . stmt NEWLINE stmt_list (0)
  4296. \end{lstlisting}
  4297. We continue to perform prediction actions as more opportunities
  4298. arise. For example, the \code{stmt} nonterminal now appears after a
  4299. period, so we add all the rules for \code{stmt}.
  4300. \begin{lstlisting}
  4301. stmt: . "print" "(" exp ")" (0)
  4302. stmt: . exp (0)
  4303. \end{lstlisting}
  4304. This reveals yet more opportunities for prediction, so we add the grammar
  4305. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4306. \begin{lstlisting}[escapechar=$]
  4307. exp: . exp "+" exp_hi (0)
  4308. exp: . exp "-" exp_hi (0)
  4309. exp: . exp_hi (0)
  4310. exp_hi: . INT (0)
  4311. exp_hi: . "input_int" "(" ")" (0)
  4312. exp_hi: . "-" exp_hi (0)
  4313. exp_hi: . "(" exp ")" (0)
  4314. \end{lstlisting}
  4315. We have exhausted the opportunities for prediction, so the algorithm
  4316. proceeds to \emph{scanning}, in which we inspect the next input token
  4317. and look for a dotted rule at the current position that has a matching
  4318. terminal immediately following the period. In our running example, the
  4319. first input token is \code{"print"}, so we identify the rule in slot
  4320. $0$ of the chart where \code{"print"} follows the period:
  4321. \begin{lstlisting}
  4322. stmt: . "print" "(" exp ")" (0)
  4323. \end{lstlisting}
  4324. We advance the period past \code{"print"} and add the resulting rule
  4325. to slot $1$ of the chart:
  4326. \begin{lstlisting}
  4327. stmt: "print" . "(" exp ")" (0)
  4328. \end{lstlisting}
  4329. If the new dotted rule had a nonterminal after the period, we would
  4330. need to carry out a prediction action, adding more dotted rules to
  4331. slot $1$. That is not the case, so we continue scanning. The next
  4332. input token is \code{"("}, so we add the following to slot $2$ of the
  4333. chart.
  4334. \begin{lstlisting}
  4335. stmt: "print" "(" . exp ")" (0)
  4336. \end{lstlisting}
  4337. Now we have a nonterminal after the period, so we carry out several
  4338. prediction actions, adding dotted rules for \code{exp} and
  4339. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4340. starting position $2$.
  4341. \begin{lstlisting}[escapechar=$]
  4342. exp: . exp "+" exp_hi (2)
  4343. exp: . exp "-" exp_hi (2)
  4344. exp: . exp_hi (2)
  4345. exp_hi: . INT (2)
  4346. exp_hi: . "input_int" "(" ")" (2)
  4347. exp_hi: . "-" exp_hi (2)
  4348. exp_hi: . "(" exp ")" (2)
  4349. \end{lstlisting}
  4350. With this prediction complete, we return to scanning, noting that the
  4351. next input token is \code{"1"}, which the lexer parses as an
  4352. \code{INT}. There is a matching rule in slot $2$:
  4353. \begin{lstlisting}
  4354. exp_hi: . INT (2)
  4355. \end{lstlisting}
  4356. so we advance the period and put the following rule into slot $3$.
  4357. \begin{lstlisting}
  4358. exp_hi: INT . (2)
  4359. \end{lstlisting}
  4360. This brings us to \emph{completion} actions. When the period reaches
  4361. the end of a dotted rule, we recognize that the substring
  4362. has matched the nonterminal on the left-hand side of the rule, in this case
  4363. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4364. rules into slot $2$ (the starting position for the finished rule) if
  4365. the period is immediately followed by \code{exp\_hi}. So we identify
  4366. \begin{lstlisting}
  4367. exp: . exp_hi (2)
  4368. \end{lstlisting}
  4369. and add the following dotted rule to slot $3$
  4370. \begin{lstlisting}
  4371. exp: exp_hi . (2)
  4372. \end{lstlisting}
  4373. This triggers another completion step for the nonterminal \code{exp},
  4374. adding two more dotted rules to slot $3$.
  4375. \begin{lstlisting}[escapechar=$]
  4376. exp: exp . "+" exp_hi (2)
  4377. exp: exp . "-" exp_hi (2)
  4378. \end{lstlisting}
  4379. Returning to scanning, the next input token is \code{"+"}, so
  4380. we add the following to slot $4$.
  4381. \begin{lstlisting}[escapechar=$]
  4382. exp: exp "+" . exp_hi (2)
  4383. \end{lstlisting}
  4384. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4385. the following dotted rules to slot $4$ of the chart.
  4386. \begin{lstlisting}[escapechar=$]
  4387. exp_hi: . INT (4)
  4388. exp_hi: . "input_int" "(" ")" (4)
  4389. exp_hi: . "-" exp_hi (4)
  4390. exp_hi: . "(" exp ")" (4)
  4391. \end{lstlisting}
  4392. The next input token is \code{"3"} which the lexer categorized as an
  4393. \code{INT}, so we advance the period past \code{INT} for the rules in
  4394. slot $4$, of which there is just one, and put the following into slot $5$.
  4395. \begin{lstlisting}[escapechar=$]
  4396. exp_hi: INT . (4)
  4397. \end{lstlisting}
  4398. The period at the end of the rule triggers a completion action for the
  4399. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4400. So we advance the period and put the following into slot $5$.
  4401. \begin{lstlisting}[escapechar=$]
  4402. exp: exp "+" exp_hi . (2)
  4403. \end{lstlisting}
  4404. This triggers another completion action for the rules in slot $2$ that
  4405. have a period before \code{exp}.
  4406. \begin{lstlisting}[escapechar=$]
  4407. stmt: "print" "(" exp . ")" (0)
  4408. exp: exp . "+" exp_hi (2)
  4409. exp: exp . "-" exp_hi (2)
  4410. \end{lstlisting}
  4411. We scan the next input token \code{")"}, placing the following dotted
  4412. rule into slot $6$.
  4413. \begin{lstlisting}[escapechar=$]
  4414. stmt: "print" "(" exp ")" . (0)
  4415. \end{lstlisting}
  4416. This triggers the completion of \code{stmt} in slot $0$
  4417. \begin{lstlisting}
  4418. stmt_list: stmt . NEWLINE stmt_list (0)
  4419. \end{lstlisting}
  4420. The last input token is a \code{NEWLINE}, so we advance the period
  4421. and place the new dotted rule into slot $7$.
  4422. \begin{lstlisting}
  4423. stmt_list: stmt NEWLINE . stmt_list (0)
  4424. \end{lstlisting}
  4425. We are close to the end of parsing the input!
  4426. The period is before the \code{stmt\_list} nonterminal, so we
  4427. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4428. \begin{lstlisting}
  4429. stmt_list: . (7)
  4430. stmt_list: . stmt NEWLINE stmt_list (7)
  4431. stmt: . "print" "(" exp ")" (7)
  4432. stmt: . exp (7)
  4433. \end{lstlisting}
  4434. There is immediately an opportunity for completion of \code{stmt\_list},
  4435. so we add the following to slot $7$.
  4436. \begin{lstlisting}
  4437. stmt_list: stmt NEWLINE stmt_list . (0)
  4438. \end{lstlisting}
  4439. This triggers another completion action for \code{stmt\_list} in slot $0$
  4440. \begin{lstlisting}
  4441. lang_int: stmt_list . (0)
  4442. \end{lstlisting}
  4443. which in turn completes \code{lang\_int}, the start symbol of the
  4444. grammar, so the parsing of the input is complete.
  4445. For reference, we now give a general description of Earley's
  4446. algorithm.
  4447. \begin{enumerate}
  4448. \item The algorithm begins by initializing slot $0$ of the chart with the
  4449. grammar rule for the start symbol, placing a period at the beginning
  4450. of the right-hand side, and recording its starting position as $0$.
  4451. \item The algorithm repeatedly applies the following three kinds of
  4452. actions for as long as there are opportunities to do so.
  4453. \begin{itemize}
  4454. \item Prediction: If there is a rule in slot $k$ whose period comes
  4455. before a nonterminal, add the rules for that nonterminal into slot
  4456. $k$, placing a period at the beginning of their right-hand sides
  4457. and recording their starting position as $k$.
  4458. \item Scanning: If the token at position $k$ of the input string
  4459. matches the symbol after the period in a dotted rule in slot $k$
  4460. of the chart, advance the period in the dotted rule, adding
  4461. the result to slot $k+1$.
  4462. \item Completion: If a dotted rule in slot $k$ has a period at the
  4463. end, inspect the rules in the slot corresponding to the starting
  4464. position of the completed rule. If any of those rules have a
  4465. nonterminal following their period that matches the left-hand side
  4466. of the completed rule, then advance their period, placing the new
  4467. dotted rule in slot $k$.
  4468. \end{itemize}
  4469. While repeating these three actions, take care never to add
  4470. duplicate dotted rules to the chart.
  4471. \end{enumerate}
  4472. We have described how Earley's algorithm recognizes that an input
  4473. string matches a grammar, but we have not described how it builds a
  4474. parse tree. The basic idea is simple, but building parse trees in an
  4475. efficient way is more complex, requiring a data structure called a
  4476. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4477. to attach a partial parse tree to every dotted rule in the chart.
  4478. Initially, the tree node associated with a dotted rule has no
  4479. children. As the period moves to the right, the nodes from the
  4480. subparses are added as children to the tree node.
  4481. As mentioned at the beginning of this section, Earley's algorithm is
  4482. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4483. files that contain thousands of tokens in a reasonable amount of time,
  4484. but not millions.
  4485. %
  4486. In the next section we discuss the LALR(1) parsing algorithm, which is
  4487. efficient enough to use with even the largest of input files.
  4488. \section{The LALR(1) Algorithm}
  4489. \label{sec:lalr}
  4490. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4491. two-phase approach in which it first compiles the grammar into a state
  4492. machine and then runs the state machine to parse an input string. The
  4493. second phase has time complexity $O(n)$ where $n$ is the number of
  4494. tokens in the input, so LALR(1) is the best one could hope for with
  4495. respect to efficiency.
  4496. %
  4497. A particularly influential implementation of LALR(1) is the
  4498. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4499. \texttt{yacc} stands for ``yet another compiler compiler''.
  4500. %
  4501. The LALR(1) state machine uses a stack to record its progress in
  4502. parsing the input string. Each element of the stack is a pair: a
  4503. state number and a grammar symbol (a terminal or a nonterminal). The
  4504. symbol characterizes the input that has been parsed so far, and the
  4505. state number is used to remember how to proceed once the next
  4506. symbol's worth of input has been parsed. Each state in the machine
  4507. represents where the parser stands in the parsing process with respect
  4508. to certain grammar rules. In particular, each state is associated with
  4509. a set of dotted rules.
  4510. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4511. (also called parse table) for the following simple but ambiguous
  4512. grammar:
  4513. \begin{lstlisting}[escapechar=$]
  4514. exp: INT
  4515. | exp "+" exp
  4516. stmt: "print" exp
  4517. start: stmt
  4518. \end{lstlisting}
  4519. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4520. read in a \lstinline{"print"} token, so the top of the stack is
  4521. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4522. the input according to grammar rule 1, which is signified by showing
  4523. rule 1 with a period after the \code{"print"} token and before the
  4524. \code{exp} nonterminal. There are two rules that could apply next,
  4525. rules 2 and 3, so state 1 also shows those rules with a period at
  4526. the beginning of their right-hand sides. The edges between states
  4527. indicate which transitions the machine should make depending on the
  4528. next input token. So, for example, if the next input token is
  4529. \code{INT} then the parser will push \code{INT} and the target state 4
  4530. on the stack and transition to state 4. Suppose that we are now at the end
  4531. of the input. State 4 says that we should reduce by rule 3, so we pop
  4532. from the stack the same number of items as the number of symbols in
  4533. the right-hand side of the rule, in this case just one. We then
  4534. momentarily jump to the state at the top of the stack (state 1) and
  4535. then follow the goto edge that corresponds to the left-hand side of
  4536. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4537. state 3. (A slightly longer example parse is shown in
  4538. figure~\ref{fig:shift-reduce}.)
  4539. \begin{figure}[htbp]
  4540. \centering
  4541. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4542. \caption{An LALR(1) parse table and a trace of an example run.}
  4543. \label{fig:shift-reduce}
  4544. \end{figure}
  4545. In general, the algorithm works as follows. First, set the current state to
  4546. state $0$. Then repeat the following, looking at the next input token.
  4547. \begin{itemize}
  4548. \item If there there is a shift edge for the input token in the
  4549. current state, push the edge's target state and the input token onto
  4550. the stack and proceed to the edge's target state.
  4551. \item If there is a reduce action for the input token in the current
  4552. state, pop $k$ elements from the stack, where $k$ is the number of
  4553. symbols in the right-hand side of the rule being reduced. Jump to
  4554. the state at the top of the stack and then follow the goto edge for
  4555. the nonterminal that matches the left-hand side of the rule that we
  4556. are reducing by. Push the edge's target state and the nonterminal on the
  4557. stack.
  4558. \end{itemize}
  4559. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4560. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4561. algorithm does not know which action to take in this case. When a
  4562. state has both a shift and a reduce action for the same token, we say
  4563. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4564. will arise, for example, in trying to parse the input
  4565. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4566. the parser will be in state 6 and will not know whether to
  4567. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4568. to proceed by shifting the next \lstinline{+} from the input.
  4569. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4570. arises when there are two reduce actions in a state for the same
  4571. token. To understand which grammars give rise to shift/reduce and
  4572. reduce/reduce conflicts, it helps to know how the parse table is
  4573. generated from the grammar, which we discuss next.
  4574. The parse table is generated one state at a time. State 0 represents
  4575. the start of the parser. We add the grammar rule for the start symbol
  4576. to this state with a period at the beginning of the right-hand side,
  4577. similarly to the initialization phase of the Earley parser. If the
  4578. period appears immediately before another nonterminal, we add all the
  4579. rules with that nonterminal on the left-hand side. Again, we place a
  4580. period at the beginning of the right-hand side of each new
  4581. rule. This process, called \emph{state closure}, is continued
  4582. until there are no more rules to add (similarly to the prediction
  4583. actions of an Earley parser). We then examine each dotted rule in the
  4584. current state $I$. Suppose that a dotted rule has the form $A ::=
  4585. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4586. are sequences of symbols. We create a new state and call it $J$. If $X$
  4587. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4588. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4589. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4590. state $J$. We start by adding all dotted rules from state $I$ that
  4591. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4592. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4593. the period moved past the $X$. (This is analogous to completion in
  4594. Earley's algorithm.) We then perform state closure on $J$. This
  4595. process repeats until there are no more states or edges to add.
  4596. We then mark states as accepting states if they have a dotted rule
  4597. that is the start rule with a period at the end. Also, to add
  4598. the reduce actions, we look for any state containing a dotted rule
  4599. with a period at the end. Let $n$ be the rule number for this dotted
  4600. rule. We then put a reduce $n$ action into that state for every token
  4601. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4602. dotted rule with a period at the end. We therefore put a reduce by
  4603. rule 3 action into state 4 for every
  4604. token.
  4605. When inserting reduce actions, take care to spot any shift/reduce or
  4606. reduce/reduce conflicts. If there are any, abort the construction of
  4607. the parse table.
  4608. \begin{exercise}
  4609. \normalfont\normalsize
  4610. %
  4611. Working on paper, walk through the parse table generation process for
  4612. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4613. your results against the parse table shown in
  4614. figure~\ref{fig:shift-reduce}.
  4615. \end{exercise}
  4616. \begin{exercise}
  4617. \normalfont\normalsize
  4618. %
  4619. Change the parser in your compiler for \LangVar{} to set the
  4620. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4621. all the \LangVar{} programs that you have created. In doing so, Lark
  4622. may signal an error due to shift/reduce or reduce/reduce conflicts
  4623. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4624. remove those conflicts.
  4625. \end{exercise}
  4626. \section{Further Reading}
  4627. In this chapter we have just scratched the surface of the field of
  4628. parsing, with the study of a very general but less efficient algorithm
  4629. (Earley) and with a more limited but highly efficient algorithm
  4630. (LALR). There are many more algorithms and classes of grammars that
  4631. fall between these two ends of the spectrum. We recommend to the reader
  4632. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4633. Regarding lexical analysis, we have described the specification
  4634. language, which are the regular expressions, but not the algorithms
  4635. for recognizing them. In short, regular expressions can be translated
  4636. to nondeterministic finite automata, which in turn are translated to
  4637. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4638. all the details on lexical analysis.
  4639. \fi}
  4640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4641. \chapter{Register Allocation}
  4642. \label{ch:register-allocation-Lvar}
  4643. \setcounter{footnote}{0}
  4644. \index{subject}{register allocation}
  4645. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4646. storing variables on the procedure call stack. The CPU may require tens
  4647. to hundreds of cycles to access a location on the stack, whereas
  4648. accessing a register takes only a single cycle. In this chapter we
  4649. improve the efficiency of our generated code by storing some variables
  4650. in registers. The goal of register allocation is to fit as many
  4651. variables into registers as possible. Some programs have more
  4652. variables than registers, so we cannot always map each variable to a
  4653. different register. Fortunately, it is common for different variables
  4654. to be in use during different periods of time during program
  4655. execution, and in those cases we can map multiple variables to the
  4656. same register.
  4657. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4658. example. The source program is on the left and the output of
  4659. instruction selection\index{subject}{instruction selection}
  4660. is on the right. The program is almost
  4661. completely in the x86 assembly language, but it still uses variables.
  4662. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4663. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4664. the other hand, is used only after this point, so \code{x} and
  4665. \code{z} could share the same register.
  4666. \begin{figure}
  4667. \begin{tcolorbox}[colback=white]
  4668. \begin{minipage}{0.45\textwidth}
  4669. Example \LangVar{} program:
  4670. % var_test_28.rkt
  4671. {\if\edition\racketEd
  4672. \begin{lstlisting}
  4673. (let ([v 1])
  4674. (let ([w 42])
  4675. (let ([x (+ v 7)])
  4676. (let ([y x])
  4677. (let ([z (+ x w)])
  4678. (+ z (- y)))))))
  4679. \end{lstlisting}
  4680. \fi}
  4681. {\if\edition\pythonEd\pythonColor
  4682. \begin{lstlisting}
  4683. v = 1
  4684. w = 42
  4685. x = v + 7
  4686. y = x
  4687. z = x + w
  4688. print(z + (- y))
  4689. \end{lstlisting}
  4690. \fi}
  4691. \end{minipage}
  4692. \begin{minipage}{0.45\textwidth}
  4693. After instruction selection:
  4694. {\if\edition\racketEd
  4695. \begin{lstlisting}
  4696. locals-types:
  4697. x : Integer, y : Integer,
  4698. z : Integer, t : Integer,
  4699. v : Integer, w : Integer
  4700. start:
  4701. movq $1, v
  4702. movq $42, w
  4703. movq v, x
  4704. addq $7, x
  4705. movq x, y
  4706. movq x, z
  4707. addq w, z
  4708. movq y, t
  4709. negq t
  4710. movq z, %rax
  4711. addq t, %rax
  4712. jmp conclusion
  4713. \end{lstlisting}
  4714. \fi}
  4715. {\if\edition\pythonEd\pythonColor
  4716. \begin{lstlisting}
  4717. movq $1, v
  4718. movq $42, w
  4719. movq v, x
  4720. addq $7, x
  4721. movq x, y
  4722. movq x, z
  4723. addq w, z
  4724. movq y, tmp_0
  4725. negq tmp_0
  4726. movq z, tmp_1
  4727. addq tmp_0, tmp_1
  4728. movq tmp_1, %rdi
  4729. callq print_int
  4730. \end{lstlisting}
  4731. \fi}
  4732. \end{minipage}
  4733. \end{tcolorbox}
  4734. \caption{A running example for register allocation.}
  4735. \label{fig:reg-eg}
  4736. \end{figure}
  4737. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4738. compute where a variable is in use. Once we have that information, we
  4739. compute which variables are in use at the same time, that is, which ones
  4740. \emph{interfere}\index{subject}{interfere} with each other, and
  4741. represent this relation as an undirected graph whose vertices are
  4742. variables and edges indicate when two variables interfere
  4743. (section~\ref{sec:build-interference}). We then model register
  4744. allocation as a graph coloring problem
  4745. (section~\ref{sec:graph-coloring}).
  4746. If we run out of registers despite these efforts, we place the
  4747. remaining variables on the stack, similarly to how we handled
  4748. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4749. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4750. location. The decision to spill a variable is handled as part of the
  4751. graph coloring process.
  4752. We make the simplifying assumption that each variable is assigned to
  4753. one location (a register or stack address). A more sophisticated
  4754. approach is to assign a variable to one or more locations in different
  4755. regions of the program. For example, if a variable is used many times
  4756. in short sequence and then used again only after many other
  4757. instructions, it could be more efficient to assign the variable to a
  4758. register during the initial sequence and then move it to the stack for
  4759. the rest of its lifetime. We refer the interested reader to
  4760. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4761. approach.
  4762. % discuss prioritizing variables based on how much they are used.
  4763. \section{Registers and Calling Conventions}
  4764. \label{sec:calling-conventions}
  4765. \index{subject}{calling conventions}
  4766. As we perform register allocation, we must be aware of the
  4767. \emph{calling conventions} \index{subject}{calling conventions} that
  4768. govern how function calls are performed in x86.
  4769. %
  4770. Even though \LangVar{} does not include programmer-defined functions,
  4771. our generated code includes a \code{main} function that is called by
  4772. the operating system and our generated code contains calls to the
  4773. \code{read\_int} function.
  4774. Function calls require coordination between two pieces of code that
  4775. may be written by different programmers or generated by different
  4776. compilers. Here we follow the System V calling conventions that are
  4777. used by the GNU C compiler on Linux and
  4778. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4779. %
  4780. The calling conventions include rules about how functions share the
  4781. use of registers. In particular, the caller is responsible for freeing
  4782. some registers prior to the function call for use by the callee.
  4783. These are called the \emph{caller-saved registers}
  4784. \index{subject}{caller-saved registers}
  4785. and they are
  4786. \begin{lstlisting}
  4787. rax rcx rdx rsi rdi r8 r9 r10 r11
  4788. \end{lstlisting}
  4789. On the other hand, the callee is responsible for preserving the values
  4790. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4791. which are
  4792. \begin{lstlisting}
  4793. rsp rbp rbx r12 r13 r14 r15
  4794. \end{lstlisting}
  4795. We can think about this caller/callee convention from two points of
  4796. view, the caller view and the callee view, as follows:
  4797. \begin{itemize}
  4798. \item The caller should assume that all the caller-saved registers get
  4799. overwritten with arbitrary values by the callee. On the other hand,
  4800. the caller can safely assume that all the callee-saved registers
  4801. retain their original values.
  4802. \item The callee can freely use any of the caller-saved registers.
  4803. However, if the callee wants to use a callee-saved register, the
  4804. callee must arrange to put the original value back in the register
  4805. prior to returning to the caller. This can be accomplished by saving
  4806. the value to the stack in the prelude of the function and restoring
  4807. the value in the conclusion of the function.
  4808. \end{itemize}
  4809. In x86, registers are also used for passing arguments to a function
  4810. and for the return value. In particular, the first six arguments of a
  4811. function are passed in the following six registers, in this order.
  4812. \begin{lstlisting}
  4813. rdi rsi rdx rcx r8 r9
  4814. \end{lstlisting}
  4815. We refer to these six registers are the argument-passing registers
  4816. \index{subject}{argument-passing registers}.
  4817. If there are more than six arguments, the convention is to use space
  4818. on the frame of the caller for the rest of the arguments. In
  4819. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4820. argument and the rest of the arguments, which simplifies the treatment
  4821. of efficient tail calls.
  4822. %
  4823. \racket{For now, the only function we care about is \code{read\_int},
  4824. which takes zero arguments.}
  4825. %
  4826. \python{For now, the only functions we care about are \code{read\_int}
  4827. and \code{print\_int}, which take zero and one argument, respectively.}
  4828. %
  4829. The register \code{rax} is used for the return value of a function.
  4830. The next question is how these calling conventions impact register
  4831. allocation. Consider the \LangVar{} program presented in
  4832. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4833. example from the caller point of view and then from the callee point
  4834. of view. We refer to a variable that is in use during a function call
  4835. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4836. The program makes two calls to \READOP{}. The variable \code{x} is
  4837. call-live because it is in use during the second call to \READOP{}; we
  4838. must ensure that the value in \code{x} does not get overwritten during
  4839. the call to \READOP{}. One obvious approach is to save all the values
  4840. that reside in caller-saved registers to the stack prior to each
  4841. function call and to restore them after each call. That way, if the
  4842. register allocator chooses to assign \code{x} to a caller-saved
  4843. register, its value will be preserved across the call to \READOP{}.
  4844. However, saving and restoring to the stack is relatively slow. If
  4845. \code{x} is not used many times, it may be better to assign \code{x}
  4846. to a stack location in the first place. Or better yet, if we can
  4847. arrange for \code{x} to be placed in a callee-saved register, then it
  4848. won't need to be saved and restored during function calls.
  4849. We recommend an approach that captures these issues in the
  4850. interference graph, without complicating the graph coloring algorithm.
  4851. During liveness analysis we know which variables are call-live because
  4852. we compute which variables are in use at every instruction
  4853. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4854. interference graph (section~\ref{sec:build-interference}), we can
  4855. place an edge in the interference graph between each call-live
  4856. variable and the caller-saved registers. This will prevent the graph
  4857. coloring algorithm from assigning call-live variables to caller-saved
  4858. registers.
  4859. On the other hand, for variables that are not call-live, we prefer
  4860. placing them in caller-saved registers to leave more room for
  4861. call-live variables in the callee-saved registers. This can also be
  4862. implemented without complicating the graph coloring algorithm. We
  4863. recommend that the graph coloring algorithm assign variables to
  4864. natural numbers, choosing the lowest number for which there is no
  4865. interference. After the coloring is complete, we map the numbers to
  4866. registers and stack locations: mapping the lowest numbers to
  4867. caller-saved registers, the next lowest to callee-saved registers, and
  4868. the largest numbers to stack locations. This ordering gives preference
  4869. to registers over stack locations and to caller-saved registers over
  4870. callee-saved registers.
  4871. Returning to the example in
  4872. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4873. generated x86 code on the right-hand side. Variable \code{x} is
  4874. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4875. in a safe place during the second call to \code{read\_int}. Next,
  4876. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4877. because \code{y} is not a call-live variable.
  4878. We have completed the analysis from the caller point of view, so now
  4879. we switch to the callee point of view, focusing on the prelude and
  4880. conclusion of the \code{main} function. As usual, the prelude begins
  4881. with saving the \code{rbp} register to the stack and setting the
  4882. \code{rbp} to the current stack pointer. We now know why it is
  4883. necessary to save the \code{rbp}: it is a callee-saved register. The
  4884. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4885. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4886. (\code{x}). The other callee-saved registers are not saved in the
  4887. prelude because they are not used. The prelude subtracts 8 bytes from
  4888. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4889. conclusion, we see that \code{rbx} is restored from the stack with a
  4890. \code{popq} instruction.
  4891. \index{subject}{prelude}\index{subject}{conclusion}
  4892. \begin{figure}[tp]
  4893. \begin{tcolorbox}[colback=white]
  4894. \begin{minipage}{0.45\textwidth}
  4895. Example \LangVar{} program:
  4896. %var_test_14.rkt
  4897. {\if\edition\racketEd
  4898. \begin{lstlisting}
  4899. (let ([x (read)])
  4900. (let ([y (read)])
  4901. (+ (+ x y) 42)))
  4902. \end{lstlisting}
  4903. \fi}
  4904. {\if\edition\pythonEd\pythonColor
  4905. \begin{lstlisting}
  4906. x = input_int()
  4907. y = input_int()
  4908. print((x + y) + 42)
  4909. \end{lstlisting}
  4910. \fi}
  4911. \end{minipage}
  4912. \begin{minipage}{0.45\textwidth}
  4913. Generated x86 assembly:
  4914. {\if\edition\racketEd
  4915. \begin{lstlisting}
  4916. start:
  4917. callq read_int
  4918. movq %rax, %rbx
  4919. callq read_int
  4920. movq %rax, %rcx
  4921. addq %rcx, %rbx
  4922. movq %rbx, %rax
  4923. addq $42, %rax
  4924. jmp _conclusion
  4925. .globl main
  4926. main:
  4927. pushq %rbp
  4928. movq %rsp, %rbp
  4929. pushq %rbx
  4930. subq $8, %rsp
  4931. jmp start
  4932. conclusion:
  4933. addq $8, %rsp
  4934. popq %rbx
  4935. popq %rbp
  4936. retq
  4937. \end{lstlisting}
  4938. \fi}
  4939. {\if\edition\pythonEd\pythonColor
  4940. \begin{lstlisting}
  4941. .globl main
  4942. main:
  4943. pushq %rbp
  4944. movq %rsp, %rbp
  4945. pushq %rbx
  4946. subq $8, %rsp
  4947. callq read_int
  4948. movq %rax, %rbx
  4949. callq read_int
  4950. movq %rax, %rcx
  4951. movq %rbx, %rdx
  4952. addq %rcx, %rdx
  4953. movq %rdx, %rcx
  4954. addq $42, %rcx
  4955. movq %rcx, %rdi
  4956. callq print_int
  4957. addq $8, %rsp
  4958. popq %rbx
  4959. popq %rbp
  4960. retq
  4961. \end{lstlisting}
  4962. \fi}
  4963. \end{minipage}
  4964. \end{tcolorbox}
  4965. \caption{An example with function calls.}
  4966. \label{fig:example-calling-conventions}
  4967. \end{figure}
  4968. %\clearpage
  4969. \section{Liveness Analysis}
  4970. \label{sec:liveness-analysis-Lvar}
  4971. \index{subject}{liveness analysis}
  4972. The \code{uncover\_live} \racket{pass}\python{function} performs
  4973. \emph{liveness analysis}; that is, it discovers which variables are
  4974. in use in different regions of a program.
  4975. %
  4976. A variable or register is \emph{live} at a program point if its
  4977. current value is used at some later point in the program. We refer to
  4978. variables, stack locations, and registers collectively as
  4979. \emph{locations}.
  4980. %
  4981. Consider the following code fragment in which there are two writes to
  4982. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4983. time?
  4984. \begin{center}
  4985. \begin{minipage}{0.85\textwidth}
  4986. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4987. movq $5, a
  4988. movq $30, b
  4989. movq a, c
  4990. movq $10, b
  4991. addq b, c
  4992. \end{lstlisting}
  4993. \end{minipage}
  4994. \end{center}
  4995. The answer is no, because \code{a} is live from line 1 to 3 and
  4996. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4997. line 2 is never used because it is overwritten (line 4) before the
  4998. next read (line 5).
  4999. The live locations for each instruction can be computed by traversing
  5000. the instruction sequence back to front (i.e., backward in execution
  5001. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5002. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5003. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5004. locations before instruction $I_k$. \racket{We recommend representing
  5005. these sets with the Racket \code{set} data structure described in
  5006. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5007. with the Python
  5008. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5009. data structure.}
  5010. {\if\edition\racketEd
  5011. \begin{figure}[tp]
  5012. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5013. \small
  5014. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5015. A \emph{set} is an unordered collection of elements without duplicates.
  5016. Here are some of the operations defined on sets.
  5017. \index{subject}{set}
  5018. \begin{description}
  5019. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5020. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5021. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5022. difference of the two sets.
  5023. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5024. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5025. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5026. \end{description}
  5027. \end{tcolorbox}
  5028. %\end{wrapfigure}
  5029. \caption{The \code{set} data structure.}
  5030. \label{fig:set}
  5031. \end{figure}
  5032. \fi}
  5033. The locations that are live after an instruction are its
  5034. \emph{live-after}\index{subject}{live-after} set, and the locations
  5035. that are live before an instruction are its
  5036. \emph{live-before}\index{subject}{live-before} set. The live-after
  5037. set of an instruction is always the same as the live-before set of the
  5038. next instruction.
  5039. \begin{equation} \label{eq:live-after-before-next}
  5040. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5041. \end{equation}
  5042. To start things off, there are no live locations after the last
  5043. instruction, so
  5044. \begin{equation}\label{eq:live-last-empty}
  5045. L_{\mathsf{after}}(n) = \emptyset
  5046. \end{equation}
  5047. We then apply the following rule repeatedly, traversing the
  5048. instruction sequence back to front.
  5049. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5050. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5051. \end{equation}
  5052. where $W(k)$ are the locations written to by instruction $I_k$, and
  5053. $R(k)$ are the locations read by instruction $I_k$.
  5054. {\if\edition\racketEd
  5055. %
  5056. There is a special case for \code{jmp} instructions. The locations
  5057. that are live before a \code{jmp} should be the locations in
  5058. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5059. maintaining an alist named \code{label->live} that maps each label to
  5060. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5061. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5062. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5063. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5064. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5065. %
  5066. \fi}
  5067. Let us walk through the previous example, applying these formulas
  5068. starting with the instruction on line 5 of the code fragment. We
  5069. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5070. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5071. $\emptyset$ because it is the last instruction
  5072. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5073. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5074. variables \code{b} and \code{c}
  5075. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5076. \[
  5077. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5078. \]
  5079. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5080. the live-before set from line 5 to be the live-after set for this
  5081. instruction (formula~\eqref{eq:live-after-before-next}).
  5082. \[
  5083. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5084. \]
  5085. This move instruction writes to \code{b} and does not read from any
  5086. variables, so we have the following live-before set
  5087. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5088. \[
  5089. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5090. \]
  5091. The live-before for instruction \code{movq a, c}
  5092. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5093. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5094. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5095. variable that is not live and does not read from a variable.
  5096. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5097. because it writes to variable \code{a}.
  5098. \begin{figure}[tbp]
  5099. \centering
  5100. \begin{tcolorbox}[colback=white]
  5101. \hspace{10pt}
  5102. \begin{minipage}{0.4\textwidth}
  5103. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5104. movq $5, a
  5105. movq $30, b
  5106. movq a, c
  5107. movq $10, b
  5108. addq b, c
  5109. \end{lstlisting}
  5110. \end{minipage}
  5111. \vrule\hspace{10pt}
  5112. \begin{minipage}{0.45\textwidth}
  5113. \begin{align*}
  5114. L_{\mathsf{before}}(1)= \emptyset,
  5115. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5116. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5117. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5118. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5119. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5120. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5121. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5122. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5123. L_{\mathsf{after}}(5)= \emptyset
  5124. \end{align*}
  5125. \end{minipage}
  5126. \end{tcolorbox}
  5127. \caption{Example output of liveness analysis on a short example.}
  5128. \label{fig:liveness-example-0}
  5129. \end{figure}
  5130. \begin{exercise}\normalfont\normalsize
  5131. Perform liveness analysis by hand on the running example in
  5132. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5133. sets for each instruction. Compare your answers to the solution
  5134. shown in figure~\ref{fig:live-eg}.
  5135. \end{exercise}
  5136. \begin{figure}[tp]
  5137. \hspace{20pt}
  5138. \begin{minipage}{0.55\textwidth}
  5139. \begin{tcolorbox}[colback=white]
  5140. {\if\edition\racketEd
  5141. \begin{lstlisting}
  5142. |$\{\ttm{rsp}\}$|
  5143. movq $1, v
  5144. |$\{\ttm{v},\ttm{rsp}\}$|
  5145. movq $42, w
  5146. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5147. movq v, x
  5148. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5149. addq $7, x
  5150. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5151. movq x, y
  5152. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5153. movq x, z
  5154. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5155. addq w, z
  5156. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5157. movq y, t
  5158. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5159. negq t
  5160. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5161. movq z, %rax
  5162. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5163. addq t, %rax
  5164. |$\{\ttm{rax},\ttm{rsp}\}$|
  5165. jmp conclusion
  5166. \end{lstlisting}
  5167. \fi}
  5168. {\if\edition\pythonEd\pythonColor
  5169. \begin{lstlisting}
  5170. movq $1, v
  5171. |$\{\ttm{v}\}$|
  5172. movq $42, w
  5173. |$\{\ttm{w}, \ttm{v}\}$|
  5174. movq v, x
  5175. |$\{\ttm{w}, \ttm{x}\}$|
  5176. addq $7, x
  5177. |$\{\ttm{w}, \ttm{x}\}$|
  5178. movq x, y
  5179. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5180. movq x, z
  5181. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5182. addq w, z
  5183. |$\{\ttm{y}, \ttm{z}\}$|
  5184. movq y, tmp_0
  5185. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5186. negq tmp_0
  5187. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5188. movq z, tmp_1
  5189. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5190. addq tmp_0, tmp_1
  5191. |$\{\ttm{tmp\_1}\}$|
  5192. movq tmp_1, %rdi
  5193. |$\{\ttm{rdi}\}$|
  5194. callq print_int
  5195. |$\{\}$|
  5196. \end{lstlisting}
  5197. \fi}
  5198. \end{tcolorbox}
  5199. \end{minipage}
  5200. \caption{The running example annotated with live-after sets.}
  5201. \label{fig:live-eg}
  5202. \end{figure}
  5203. \begin{exercise}\normalfont\normalsize
  5204. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5205. %
  5206. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5207. field of the \code{Block} structure.}
  5208. %
  5209. \python{Return a dictionary that maps each instruction to its
  5210. live-after set.}
  5211. %
  5212. \racket{We recommend creating an auxiliary function that takes a list
  5213. of instructions and an initial live-after set (typically empty) and
  5214. returns the list of live-after sets.}
  5215. %
  5216. We recommend creating auxiliary functions to (1) compute the set
  5217. of locations that appear in an \Arg{}, (2) compute the locations read
  5218. by an instruction (the $R$ function), and (3) the locations written by
  5219. an instruction (the $W$ function). The \code{callq} instruction should
  5220. include all the caller-saved registers in its write set $W$ because
  5221. the calling convention says that those registers may be written to
  5222. during the function call. Likewise, the \code{callq} instruction
  5223. should include the appropriate argument-passing registers in its
  5224. read set $R$, depending on the arity of the function being
  5225. called. (This is why the abstract syntax for \code{callq} includes the
  5226. arity.)
  5227. \end{exercise}
  5228. %\clearpage
  5229. \section{Build the Interference Graph}
  5230. \label{sec:build-interference}
  5231. {\if\edition\racketEd
  5232. \begin{figure}[tp]
  5233. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5234. \small
  5235. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5236. A \emph{graph} is a collection of vertices and edges where each
  5237. edge connects two vertices. A graph is \emph{directed} if each
  5238. edge points from a source to a target. Otherwise the graph is
  5239. \emph{undirected}.
  5240. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5241. \begin{description}
  5242. %% We currently don't use directed graphs. We instead use
  5243. %% directed multi-graphs. -Jeremy
  5244. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5245. directed graph from a list of edges. Each edge is a list
  5246. containing the source and target vertex.
  5247. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5248. undirected graph from a list of edges. Each edge is represented by
  5249. a list containing two vertices.
  5250. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5251. inserts a vertex into the graph.
  5252. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5253. inserts an edge between the two vertices.
  5254. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5255. returns a sequence of vertices adjacent to the vertex.
  5256. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5257. returns a sequence of all vertices in the graph.
  5258. \end{description}
  5259. \end{tcolorbox}
  5260. %\end{wrapfigure}
  5261. \caption{The Racket \code{graph} package.}
  5262. \label{fig:graph}
  5263. \end{figure}
  5264. \fi}
  5265. On the basis of the liveness analysis, we know where each location is
  5266. live. However, during register allocation, we need to answer
  5267. questions of the specific form: are locations $u$ and $v$ live at the
  5268. same time? (If so, they cannot be assigned to the same register.) To
  5269. make this question more efficient to answer, we create an explicit
  5270. data structure, an \emph{interference
  5271. graph}\index{subject}{interference graph}. An interference graph is
  5272. an undirected graph that has a node for every variable and register
  5273. and has an edge between two nodes if they are
  5274. live at the same time, that is, if they interfere with each other.
  5275. %
  5276. \racket{We recommend using the Racket \code{graph} package
  5277. (figure~\ref{fig:graph}) to represent the interference graph.}
  5278. %
  5279. \python{We provide implementations of directed and undirected graph
  5280. data structures in the file \code{graph.py} of the support code.}
  5281. A straightforward way to compute the interference graph is to look at
  5282. the set of live locations between each instruction and add an edge to
  5283. the graph for every pair of variables in the same set. This approach
  5284. is less than ideal for two reasons. First, it can be expensive because
  5285. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5286. locations. Second, in the special case in which two locations hold the
  5287. same value (because one was assigned to the other), they can be live
  5288. at the same time without interfering with each other.
  5289. A better way to compute the interference graph is to focus on
  5290. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5291. must not overwrite something in a live location. So for each
  5292. instruction, we create an edge between the locations being written to
  5293. and the live locations. (However, a location never interferes with
  5294. itself.) For the \key{callq} instruction, we consider all the
  5295. caller-saved registers to have been written to, so an edge is added
  5296. between every live variable and every caller-saved register. Also, for
  5297. \key{movq} there is the special case of two variables holding the same
  5298. value. If a live variable $v$ is the same as the source of the
  5299. \key{movq}, then there is no need to add an edge between $v$ and the
  5300. destination, because they both hold the same value.
  5301. %
  5302. Hence we have the following two rules:
  5303. \begin{enumerate}
  5304. \item If instruction $I_k$ is a move instruction of the form
  5305. \key{movq} $s$\key{,} $d$, then for every $v \in
  5306. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5307. $(d,v)$.
  5308. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5309. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5310. $(d,v)$.
  5311. \end{enumerate}
  5312. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5313. these rules to each instruction. We highlight a few of the
  5314. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5315. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5316. so \code{v} interferes with \code{rsp}.}
  5317. %
  5318. \python{The first instruction is \lstinline{movq $1, v}, and the
  5319. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5320. no interference because $\ttm{v}$ is the destination of the move.}
  5321. %
  5322. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5323. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5324. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5325. %
  5326. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5327. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5328. $\ttm{x}$ interferes with \ttm{w}.}
  5329. %
  5330. \racket{The next instruction is \lstinline{movq x, y}, and the
  5331. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5332. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5333. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5334. \ttm{x} and \ttm{y} hold the same value.}
  5335. %
  5336. \python{The next instruction is \lstinline{movq x, y}, and the
  5337. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5338. applies, so \ttm{y} interferes with \ttm{w} but not
  5339. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5340. \ttm{x} and \ttm{y} hold the same value.}
  5341. %
  5342. Figure~\ref{fig:interference-results} lists the interference results
  5343. for all the instructions, and the resulting interference graph is
  5344. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5345. the interference graph in figure~\ref{fig:interfere} because there
  5346. were no interference edges involving registers and we did not wish to
  5347. clutter the graph, but in general one needs to include all the
  5348. registers in the interference graph.
  5349. \begin{figure}[tbp]
  5350. \begin{tcolorbox}[colback=white]
  5351. \begin{quote}
  5352. {\if\edition\racketEd
  5353. \begin{tabular}{ll}
  5354. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5355. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5356. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5357. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5358. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5359. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5360. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5361. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5362. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5363. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5364. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5365. \lstinline!jmp conclusion!& no interference.
  5366. \end{tabular}
  5367. \fi}
  5368. {\if\edition\pythonEd\pythonColor
  5369. \begin{tabular}{ll}
  5370. \lstinline!movq $1, v!& no interference\\
  5371. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5372. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5373. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5374. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5375. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5376. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5377. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5378. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5379. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5380. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5381. \lstinline!movq tmp_1, %rdi! & no interference \\
  5382. \lstinline!callq print_int!& no interference.
  5383. \end{tabular}
  5384. \fi}
  5385. \end{quote}
  5386. \end{tcolorbox}
  5387. \caption{Interference results for the running example.}
  5388. \label{fig:interference-results}
  5389. \end{figure}
  5390. \begin{figure}[tbp]
  5391. \begin{tcolorbox}[colback=white]
  5392. \large
  5393. {\if\edition\racketEd
  5394. \[
  5395. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5396. \node (rax) at (0,0) {$\ttm{rax}$};
  5397. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5398. \node (t1) at (0,2) {$\ttm{t}$};
  5399. \node (z) at (3,2) {$\ttm{z}$};
  5400. \node (x) at (6,2) {$\ttm{x}$};
  5401. \node (y) at (3,0) {$\ttm{y}$};
  5402. \node (w) at (6,0) {$\ttm{w}$};
  5403. \node (v) at (9,0) {$\ttm{v}$};
  5404. \draw (t1) to (rax);
  5405. \draw (t1) to (z);
  5406. \draw (z) to (y);
  5407. \draw (z) to (w);
  5408. \draw (x) to (w);
  5409. \draw (y) to (w);
  5410. \draw (v) to (w);
  5411. \draw (v) to (rsp);
  5412. \draw (w) to (rsp);
  5413. \draw (x) to (rsp);
  5414. \draw (y) to (rsp);
  5415. \path[-.,bend left=15] (z) edge node {} (rsp);
  5416. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5417. \draw (rax) to (rsp);
  5418. \end{tikzpicture}
  5419. \]
  5420. \fi}
  5421. {\if\edition\pythonEd\pythonColor
  5422. \[
  5423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5424. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5425. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5426. \node (z) at (3,2) {$\ttm{z}$};
  5427. \node (x) at (6,2) {$\ttm{x}$};
  5428. \node (y) at (3,0) {$\ttm{y}$};
  5429. \node (w) at (6,0) {$\ttm{w}$};
  5430. \node (v) at (9,0) {$\ttm{v}$};
  5431. \draw (t0) to (t1);
  5432. \draw (t0) to (z);
  5433. \draw (z) to (y);
  5434. \draw (z) to (w);
  5435. \draw (x) to (w);
  5436. \draw (y) to (w);
  5437. \draw (v) to (w);
  5438. \end{tikzpicture}
  5439. \]
  5440. \fi}
  5441. \end{tcolorbox}
  5442. \caption{The interference graph of the example program.}
  5443. \label{fig:interfere}
  5444. \end{figure}
  5445. \begin{exercise}\normalfont\normalsize
  5446. \racket{Implement the compiler pass named \code{build\_interference} according
  5447. to the algorithm suggested here. We recommend using the Racket
  5448. \code{graph} package to create and inspect the interference graph.
  5449. The output graph of this pass should be stored in the $\itm{info}$ field of
  5450. the program, under the key \code{conflicts}.}
  5451. %
  5452. \python{Implement a function named \code{build\_interference}
  5453. according to the algorithm suggested above that
  5454. returns the interference graph.}
  5455. \end{exercise}
  5456. \section{Graph Coloring via Sudoku}
  5457. \label{sec:graph-coloring}
  5458. \index{subject}{graph coloring}
  5459. \index{subject}{sudoku}
  5460. \index{subject}{color}
  5461. We come to the main event discussed in this chapter, mapping variables
  5462. to registers and stack locations. Variables that interfere with each
  5463. other must be mapped to different locations. In terms of the
  5464. interference graph, this means that adjacent vertices must be mapped
  5465. to different locations. If we think of locations as colors, the
  5466. register allocation problem becomes the graph coloring
  5467. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5468. The reader may be more familiar with the graph coloring problem than he
  5469. or she realizes; the popular game of sudoku is an instance of the
  5470. graph coloring problem. The following describes how to build a graph
  5471. out of an initial sudoku board.
  5472. \begin{itemize}
  5473. \item There is one vertex in the graph for each sudoku square.
  5474. \item There is an edge between two vertices if the corresponding squares
  5475. are in the same row, in the same column, or in the same $3\times 3$ region.
  5476. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5477. \item On the basis of the initial assignment of numbers to squares on the
  5478. sudoku board, assign the corresponding colors to the corresponding
  5479. vertices in the graph.
  5480. \end{itemize}
  5481. If you can color the remaining vertices in the graph with the nine
  5482. colors, then you have also solved the corresponding game of sudoku.
  5483. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5484. the corresponding graph with colored vertices. Here we use a
  5485. monochrome representation of colors, mapping the sudoku number 1 to
  5486. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5487. of the vertices (the colored ones) because showing edges for all the
  5488. vertices would make the graph unreadable.
  5489. \begin{figure}[tbp]
  5490. \begin{tcolorbox}[colback=white]
  5491. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5492. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5493. \end{tcolorbox}
  5494. \caption{A sudoku game board and the corresponding colored graph.}
  5495. \label{fig:sudoku-graph}
  5496. \end{figure}
  5497. Some techniques for playing sudoku correspond to heuristics used in
  5498. graph coloring algorithms. For example, one of the basic techniques
  5499. for sudoku is called Pencil Marks. The idea is to use a process of
  5500. elimination to determine what numbers are no longer available for a
  5501. square and to write those numbers in the square (writing very
  5502. small). For example, if the number $1$ is assigned to a square, then
  5503. write the pencil mark $1$ in all the squares in the same row, column,
  5504. and region to indicate that $1$ is no longer an option for those other
  5505. squares.
  5506. %
  5507. The Pencil Marks technique corresponds to the notion of
  5508. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5509. saturation of a vertex, in sudoku terms, is the set of numbers that
  5510. are no longer available. In graph terminology, we have the following
  5511. definition:
  5512. \begin{equation*}
  5513. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5514. \text{ and } \mathrm{color}(v) = c \}
  5515. \end{equation*}
  5516. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5517. edge with $u$.
  5518. The Pencil Marks technique leads to a simple strategy for filling in
  5519. numbers: if there is a square with only one possible number left, then
  5520. choose that number! But what if there are no squares with only one
  5521. possibility left? One brute-force approach is to try them all: choose
  5522. the first one, and if that ultimately leads to a solution, great. If
  5523. not, backtrack and choose the next possibility. One good thing about
  5524. Pencil Marks is that it reduces the degree of branching in the search
  5525. tree. Nevertheless, backtracking can be terribly time consuming. One
  5526. way to reduce the amount of backtracking is to use the
  5527. most-constrained-first heuristic (aka minimum remaining
  5528. values)~\citep{Russell2003}. That is, in choosing a square, always
  5529. choose one with the fewest possibilities left (the vertex with the
  5530. highest saturation). The idea is that choosing highly constrained
  5531. squares earlier rather than later is better, because later on there may
  5532. not be any possibilities left in the highly saturated squares.
  5533. However, register allocation is easier than sudoku, because the
  5534. register allocator can fall back to assigning variables to stack
  5535. locations when the registers run out. Thus, it makes sense to replace
  5536. backtracking with greedy search: make the best choice at the time and
  5537. keep going. We still wish to minimize the number of colors needed, so
  5538. we use the most-constrained-first heuristic in the greedy search.
  5539. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5540. algorithm for register allocation based on saturation and the
  5541. most-constrained-first heuristic. It is roughly equivalent to the
  5542. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5543. sudoku, the algorithm represents colors with integers. The integers
  5544. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5545. register allocation. In particular, we recommend the following
  5546. correspondence, with $k=11$.
  5547. \begin{lstlisting}
  5548. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5549. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5550. \end{lstlisting}
  5551. The integers $k$ and larger correspond to stack locations. The
  5552. registers that are not used for register allocation, such as
  5553. \code{rax}, are assigned to negative integers. In particular, we
  5554. recommend the following correspondence.
  5555. \begin{lstlisting}
  5556. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5557. \end{lstlisting}
  5558. %% One might wonder why we include registers at all in the liveness
  5559. %% analysis and interference graph. For example, we never allocate a
  5560. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5561. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5562. %% to use register for passing arguments to functions, it will be
  5563. %% necessary for those registers to appear in the interference graph
  5564. %% because those registers will also be assigned to variables, and we
  5565. %% don't want those two uses to encroach on each other. Regarding
  5566. %% registers such as \code{rax} and \code{rsp} that are not used for
  5567. %% variables, we could omit them from the interference graph but that
  5568. %% would require adding special cases to our algorithm, which would
  5569. %% complicate the logic for little gain.
  5570. \begin{figure}[btp]
  5571. \begin{tcolorbox}[colback=white]
  5572. \centering
  5573. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5574. Algorithm: DSATUR
  5575. Input: A graph |$G$|
  5576. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5577. |$W \gets \mathrm{vertices}(G)$|
  5578. while |$W \neq \emptyset$| do
  5579. pick a vertex |$u$| from |$W$| with the highest saturation,
  5580. breaking ties randomly
  5581. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5582. |$\mathrm{color}[u] \gets c$|
  5583. |$W \gets W - \{u\}$|
  5584. \end{lstlisting}
  5585. \end{tcolorbox}
  5586. \caption{The saturation-based greedy graph coloring algorithm.}
  5587. \label{fig:satur-algo}
  5588. \end{figure}
  5589. {\if\edition\racketEd
  5590. With the DSATUR algorithm in hand, let us return to the running
  5591. example and consider how to color the interference graph shown in
  5592. figure~\ref{fig:interfere}.
  5593. %
  5594. We start by assigning each register node to its own color. For
  5595. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5596. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5597. (To reduce clutter in the interference graph, we elide nodes
  5598. that do not have interference edges, such as \code{rcx}.)
  5599. The variables are not yet colored, so they are annotated with a dash. We
  5600. then update the saturation for vertices that are adjacent to a
  5601. register, obtaining the following annotated graph. For example, the
  5602. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5603. \code{rax} and \code{rsp}.
  5604. \[
  5605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5606. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5607. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5608. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5609. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5610. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5611. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5612. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5613. \node (v) at (10,0) {$\ttm{v}:-,\{-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. The algorithm says to select a maximally saturated vertex. So, we pick
  5631. $\ttm{t}$ and color it with the first available integer, which is
  5632. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5633. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5634. \[
  5635. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5636. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5637. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5638. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5639. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5640. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5641. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5642. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5643. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5644. \draw (t1) to (rax);
  5645. \draw (t1) to (z);
  5646. \draw (z) to (y);
  5647. \draw (z) to (w);
  5648. \draw (x) to (w);
  5649. \draw (y) to (w);
  5650. \draw (v) to (w);
  5651. \draw (v) to (rsp);
  5652. \draw (w) to (rsp);
  5653. \draw (x) to (rsp);
  5654. \draw (y) to (rsp);
  5655. \path[-.,bend left=15] (z) edge node {} (rsp);
  5656. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5657. \draw (rax) to (rsp);
  5658. \end{tikzpicture}
  5659. \]
  5660. We repeat the process, selecting a maximally saturated vertex,
  5661. choosing \code{z}, and coloring it with the first available number, which
  5662. is $1$. We add $1$ to the saturation for the neighboring vertices
  5663. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5664. \[
  5665. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5666. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5667. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5668. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5669. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5670. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5671. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5672. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5673. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5674. \draw (t1) to (rax);
  5675. \draw (t1) to (z);
  5676. \draw (z) to (y);
  5677. \draw (z) to (w);
  5678. \draw (x) to (w);
  5679. \draw (y) to (w);
  5680. \draw (v) to (w);
  5681. \draw (v) to (rsp);
  5682. \draw (w) to (rsp);
  5683. \draw (x) to (rsp);
  5684. \draw (y) to (rsp);
  5685. \path[-.,bend left=15] (z) edge node {} (rsp);
  5686. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5687. \draw (rax) to (rsp);
  5688. \end{tikzpicture}
  5689. \]
  5690. The most saturated vertices are now \code{w} and \code{y}. We color
  5691. \code{w} with the first available color, which is $0$.
  5692. \[
  5693. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5694. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5695. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5696. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5697. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5698. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5699. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5700. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5701. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5702. \draw (t1) to (rax);
  5703. \draw (t1) to (z);
  5704. \draw (z) to (y);
  5705. \draw (z) to (w);
  5706. \draw (x) to (w);
  5707. \draw (y) to (w);
  5708. \draw (v) to (w);
  5709. \draw (v) to (rsp);
  5710. \draw (w) to (rsp);
  5711. \draw (x) to (rsp);
  5712. \draw (y) to (rsp);
  5713. \path[-.,bend left=15] (z) edge node {} (rsp);
  5714. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5715. \draw (rax) to (rsp);
  5716. \end{tikzpicture}
  5717. \]
  5718. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5719. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5720. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5721. and \code{z}, whose colors are $0$ and $1$ respectively.
  5722. \[
  5723. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5724. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5725. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5726. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5727. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5728. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5729. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5730. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5731. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5732. \draw (t1) to (rax);
  5733. \draw (t1) to (z);
  5734. \draw (z) to (y);
  5735. \draw (z) to (w);
  5736. \draw (x) to (w);
  5737. \draw (y) to (w);
  5738. \draw (v) to (w);
  5739. \draw (v) to (rsp);
  5740. \draw (w) to (rsp);
  5741. \draw (x) to (rsp);
  5742. \draw (y) to (rsp);
  5743. \path[-.,bend left=15] (z) edge node {} (rsp);
  5744. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5745. \draw (rax) to (rsp);
  5746. \end{tikzpicture}
  5747. \]
  5748. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5749. \[
  5750. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5751. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5752. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5753. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5754. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5755. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5756. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5757. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5758. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5759. \draw (t1) to (rax);
  5760. \draw (t1) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \draw (v) to (rsp);
  5767. \draw (w) to (rsp);
  5768. \draw (x) to (rsp);
  5769. \draw (y) to (rsp);
  5770. \path[-.,bend left=15] (z) edge node {} (rsp);
  5771. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5772. \draw (rax) to (rsp);
  5773. \end{tikzpicture}
  5774. \]
  5775. In the last step of the algorithm, we color \code{x} with $1$.
  5776. \[
  5777. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5778. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5779. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5780. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5781. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5782. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5783. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5784. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5785. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5786. \draw (t1) to (rax);
  5787. \draw (t1) to (z);
  5788. \draw (z) to (y);
  5789. \draw (z) to (w);
  5790. \draw (x) to (w);
  5791. \draw (y) to (w);
  5792. \draw (v) to (w);
  5793. \draw (v) to (rsp);
  5794. \draw (w) to (rsp);
  5795. \draw (x) to (rsp);
  5796. \draw (y) to (rsp);
  5797. \path[-.,bend left=15] (z) edge node {} (rsp);
  5798. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5799. \draw (rax) to (rsp);
  5800. \end{tikzpicture}
  5801. \]
  5802. So, we obtain the following coloring:
  5803. \[
  5804. \{
  5805. \ttm{rax} \mapsto -1,
  5806. \ttm{rsp} \mapsto -2,
  5807. \ttm{t} \mapsto 0,
  5808. \ttm{z} \mapsto 1,
  5809. \ttm{x} \mapsto 1,
  5810. \ttm{y} \mapsto 2,
  5811. \ttm{w} \mapsto 0,
  5812. \ttm{v} \mapsto 1
  5813. \}
  5814. \]
  5815. \fi}
  5816. %
  5817. {\if\edition\pythonEd\pythonColor
  5818. %
  5819. With the DSATUR algorithm in hand, let us return to the running
  5820. example and consider how to color the interference graph shown in
  5821. figure~\ref{fig:interfere}, again mapping 1 to blank, 2 to white, and
  5822. 3 to gray. We annotate each variable node with a dash to indicate that
  5823. it has not yet been assigned a color. Each register node (not shown)
  5824. should be assigned the number that the register corresponds to, for
  5825. example, color \code{rcx} with the number \code{0} and \code{rdx} with
  5826. \code{1}. The saturation sets are also shown for each node; all of
  5827. them start as the empty set. We do not show the register nodes in the
  5828. following graph because there were no interference edges involving
  5829. registers in this program; however, in general there can be inference
  5830. edges that involve registers.
  5831. %
  5832. \[
  5833. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5834. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5835. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5836. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5837. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5838. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5839. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5840. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5841. \draw (t0) to (t1);
  5842. \draw (t0) to (z);
  5843. \draw (z) to (y);
  5844. \draw (z) to (w);
  5845. \draw (x) to (w);
  5846. \draw (y) to (w);
  5847. \draw (v) to (w);
  5848. \end{tikzpicture}
  5849. \]
  5850. The algorithm says to select a maximally saturated vertex, but they
  5851. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5852. and then we color it with the first available integer, which is $0$. We mark
  5853. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5854. they interfere with $\ttm{tmp\_0}$.
  5855. \[
  5856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5857. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5858. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5859. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5860. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5861. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5862. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5863. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5864. \draw (t0) to (t1);
  5865. \draw (t0) to (z);
  5866. \draw (z) to (y);
  5867. \draw (z) to (w);
  5868. \draw (x) to (w);
  5869. \draw (y) to (w);
  5870. \draw (v) to (w);
  5871. \end{tikzpicture}
  5872. \]
  5873. We repeat the process. The most saturated vertices are \code{z} and
  5874. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5875. available number, which is $1$. We add $1$ to the saturation for the
  5876. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5877. \[
  5878. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5879. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5880. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5881. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5882. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5883. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5884. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5885. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5886. \draw (t0) to (t1);
  5887. \draw (t0) to (z);
  5888. \draw (z) to (y);
  5889. \draw (z) to (w);
  5890. \draw (x) to (w);
  5891. \draw (y) to (w);
  5892. \draw (v) to (w);
  5893. \end{tikzpicture}
  5894. \]
  5895. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5896. \code{y}. We color \code{w} with the first available color, which
  5897. is $0$.
  5898. \[
  5899. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5900. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5901. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5902. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5903. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5904. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5905. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5906. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5907. \draw (t0) to (t1);
  5908. \draw (t0) to (z);
  5909. \draw (z) to (y);
  5910. \draw (z) to (w);
  5911. \draw (x) to (w);
  5912. \draw (y) to (w);
  5913. \draw (v) to (w);
  5914. \end{tikzpicture}
  5915. \]
  5916. Now \code{y} is the most saturated, so we color it with $2$.
  5917. \[
  5918. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5919. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5920. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5921. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5922. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5923. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5924. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5925. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5926. \draw (t0) to (t1);
  5927. \draw (t0) to (z);
  5928. \draw (z) to (y);
  5929. \draw (z) to (w);
  5930. \draw (x) to (w);
  5931. \draw (y) to (w);
  5932. \draw (v) to (w);
  5933. \end{tikzpicture}
  5934. \]
  5935. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5936. We choose to color \code{v} with $1$.
  5937. \[
  5938. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5939. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5940. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5941. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5942. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5943. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5944. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5945. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5946. \draw (t0) to (t1);
  5947. \draw (t0) to (z);
  5948. \draw (z) to (y);
  5949. \draw (z) to (w);
  5950. \draw (x) to (w);
  5951. \draw (y) to (w);
  5952. \draw (v) to (w);
  5953. \end{tikzpicture}
  5954. \]
  5955. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5956. \[
  5957. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5958. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5959. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5960. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5961. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5962. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5963. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5964. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5965. \draw (t0) to (t1);
  5966. \draw (t0) to (z);
  5967. \draw (z) to (y);
  5968. \draw (z) to (w);
  5969. \draw (x) to (w);
  5970. \draw (y) to (w);
  5971. \draw (v) to (w);
  5972. \end{tikzpicture}
  5973. \]
  5974. So, we obtain the following coloring:
  5975. \[
  5976. \{ \ttm{tmp\_0} \mapsto 0,
  5977. \ttm{tmp\_1} \mapsto 1,
  5978. \ttm{z} \mapsto 1,
  5979. \ttm{x} \mapsto 1,
  5980. \ttm{y} \mapsto 2,
  5981. \ttm{w} \mapsto 0,
  5982. \ttm{v} \mapsto 1 \}
  5983. \]
  5984. \fi}
  5985. We recommend creating an auxiliary function named \code{color\_graph}
  5986. that takes an interference graph and a list of all the variables in
  5987. the program. This function should return a mapping of variables to
  5988. their colors (represented as natural numbers). By creating this helper
  5989. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5990. when we add support for functions.
  5991. To prioritize the processing of highly saturated nodes inside the
  5992. \code{color\_graph} function, we recommend using the priority queue
  5993. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5994. addition, you will need to maintain a mapping from variables to their
  5995. handles in the priority queue so that you can notify the priority
  5996. queue when their saturation changes.}
  5997. {\if\edition\racketEd
  5998. \begin{figure}[tp]
  5999. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6000. \small
  6001. \begin{tcolorbox}[title=Priority Queue]
  6002. A \emph{priority queue}\index{subject}{priority queue}
  6003. is a collection of items in which the
  6004. removal of items is governed by priority. In a \emph{min} queue,
  6005. lower priority items are removed first. An implementation is in
  6006. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6007. \begin{description}
  6008. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6009. priority queue that uses the $\itm{cmp}$ predicate to determine
  6010. whether its first argument has lower or equal priority to its
  6011. second argument.
  6012. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6013. items in the queue.
  6014. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6015. the item into the queue and returns a handle for the item in the
  6016. queue.
  6017. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6018. the lowest priority.
  6019. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6020. notifies the queue that the priority has decreased for the item
  6021. associated with the given handle.
  6022. \end{description}
  6023. \end{tcolorbox}
  6024. %\end{wrapfigure}
  6025. \caption{The priority queue data structure.}
  6026. \label{fig:priority-queue}
  6027. \end{figure}
  6028. \fi}
  6029. With the coloring complete, we finalize the assignment of variables to
  6030. registers and stack locations. We map the first $k$ colors to the $k$
  6031. registers and the rest of the colors to stack locations. Suppose for
  6032. the moment that we have just one register to use for register
  6033. allocation, \key{rcx}. Then we have the following map from colors to
  6034. locations.
  6035. \[
  6036. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6037. \]
  6038. Composing this mapping with the coloring, we arrive at the following
  6039. assignment of variables to locations.
  6040. {\if\edition\racketEd
  6041. \begin{gather*}
  6042. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6043. \ttm{w} \mapsto \key{\%rcx}, \,
  6044. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6045. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6046. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6047. \ttm{t} \mapsto \key{\%rcx} \}
  6048. \end{gather*}
  6049. \fi}
  6050. {\if\edition\pythonEd\pythonColor
  6051. \begin{gather*}
  6052. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6053. \ttm{w} \mapsto \key{\%rcx}, \,
  6054. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6055. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6056. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6057. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6058. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6059. \end{gather*}
  6060. \fi}
  6061. Adapt the code from the \code{assign\_homes} pass
  6062. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6063. assigned location. Applying this assignment to our running
  6064. example shown next, on the left, yields the program on the right.
  6065. % why frame size of 32? -JGS
  6066. \begin{center}
  6067. {\if\edition\racketEd
  6068. \begin{minipage}{0.35\textwidth}
  6069. \begin{lstlisting}
  6070. movq $1, v
  6071. movq $42, w
  6072. movq v, x
  6073. addq $7, x
  6074. movq x, y
  6075. movq x, z
  6076. addq w, z
  6077. movq y, t
  6078. negq t
  6079. movq z, %rax
  6080. addq t, %rax
  6081. jmp conclusion
  6082. \end{lstlisting}
  6083. \end{minipage}
  6084. $\Rightarrow\qquad$
  6085. \begin{minipage}{0.45\textwidth}
  6086. \begin{lstlisting}
  6087. movq $1, -8(%rbp)
  6088. movq $42, %rcx
  6089. movq -8(%rbp), -8(%rbp)
  6090. addq $7, -8(%rbp)
  6091. movq -8(%rbp), -16(%rbp)
  6092. movq -8(%rbp), -8(%rbp)
  6093. addq %rcx, -8(%rbp)
  6094. movq -16(%rbp), %rcx
  6095. negq %rcx
  6096. movq -8(%rbp), %rax
  6097. addq %rcx, %rax
  6098. jmp conclusion
  6099. \end{lstlisting}
  6100. \end{minipage}
  6101. \fi}
  6102. {\if\edition\pythonEd\pythonColor
  6103. \begin{minipage}{0.35\textwidth}
  6104. \begin{lstlisting}
  6105. movq $1, v
  6106. movq $42, w
  6107. movq v, x
  6108. addq $7, x
  6109. movq x, y
  6110. movq x, z
  6111. addq w, z
  6112. movq y, tmp_0
  6113. negq tmp_0
  6114. movq z, tmp_1
  6115. addq tmp_0, tmp_1
  6116. movq tmp_1, %rdi
  6117. callq print_int
  6118. \end{lstlisting}
  6119. \end{minipage}
  6120. $\Rightarrow\qquad$
  6121. \begin{minipage}{0.45\textwidth}
  6122. \begin{lstlisting}
  6123. movq $1, -8(%rbp)
  6124. movq $42, %rcx
  6125. movq -8(%rbp), -8(%rbp)
  6126. addq $7, -8(%rbp)
  6127. movq -8(%rbp), -16(%rbp)
  6128. movq -8(%rbp), -8(%rbp)
  6129. addq %rcx, -8(%rbp)
  6130. movq -16(%rbp), %rcx
  6131. negq %rcx
  6132. movq -8(%rbp), -8(%rbp)
  6133. addq %rcx, -8(%rbp)
  6134. movq -8(%rbp), %rdi
  6135. callq print_int
  6136. \end{lstlisting}
  6137. \end{minipage}
  6138. \fi}
  6139. \end{center}
  6140. \begin{exercise}\normalfont\normalsize
  6141. Implement the \code{allocate\_registers} pass.
  6142. Create five programs that exercise all aspects of the register
  6143. allocation algorithm, including spilling variables to the stack.
  6144. %
  6145. {\if\edition\racketEd
  6146. Replace \code{assign\_homes} in the list of \code{passes} in the
  6147. \code{run-tests.rkt} script with the three new passes:
  6148. \code{uncover\_live}, \code{build\_interference}, and
  6149. \code{allocate\_registers}.
  6150. Temporarily remove the call to \code{compiler-tests}.
  6151. Run the script to test the register allocator.
  6152. \fi}
  6153. %
  6154. {\if\edition\pythonEd\pythonColor
  6155. Run the \code{run-tests.py} script to check whether the
  6156. output programs produce the same result as the input programs.
  6157. \fi}
  6158. \end{exercise}
  6159. \section{Patch Instructions}
  6160. \label{sec:patch-instructions}
  6161. The remaining step in the compilation to x86 is to ensure that the
  6162. instructions have at most one argument that is a memory access.
  6163. %
  6164. In the running example, the instruction \code{movq -8(\%rbp),
  6165. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6166. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6167. then move \code{rax} into \code{-16(\%rbp)}.
  6168. %
  6169. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6170. problematic, but they can simply be deleted. In general, we recommend
  6171. deleting all the trivial moves whose source and destination are the
  6172. same location.
  6173. %
  6174. The following is the output of \code{patch\_instructions} on the
  6175. running example.
  6176. \begin{center}
  6177. {\if\edition\racketEd
  6178. \begin{minipage}{0.35\textwidth}
  6179. \begin{lstlisting}
  6180. movq $1, -8(%rbp)
  6181. movq $42, %rcx
  6182. movq -8(%rbp), -8(%rbp)
  6183. addq $7, -8(%rbp)
  6184. movq -8(%rbp), -16(%rbp)
  6185. movq -8(%rbp), -8(%rbp)
  6186. addq %rcx, -8(%rbp)
  6187. movq -16(%rbp), %rcx
  6188. negq %rcx
  6189. movq -8(%rbp), %rax
  6190. addq %rcx, %rax
  6191. jmp conclusion
  6192. \end{lstlisting}
  6193. \end{minipage}
  6194. $\Rightarrow\qquad$
  6195. \begin{minipage}{0.45\textwidth}
  6196. \begin{lstlisting}
  6197. movq $1, -8(%rbp)
  6198. movq $42, %rcx
  6199. addq $7, -8(%rbp)
  6200. movq -8(%rbp), %rax
  6201. movq %rax, -16(%rbp)
  6202. addq %rcx, -8(%rbp)
  6203. movq -16(%rbp), %rcx
  6204. negq %rcx
  6205. movq -8(%rbp), %rax
  6206. addq %rcx, %rax
  6207. jmp conclusion
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. \fi}
  6211. {\if\edition\pythonEd\pythonColor
  6212. \begin{minipage}{0.35\textwidth}
  6213. \begin{lstlisting}
  6214. movq $1, -8(%rbp)
  6215. movq $42, %rcx
  6216. movq -8(%rbp), -8(%rbp)
  6217. addq $7, -8(%rbp)
  6218. movq -8(%rbp), -16(%rbp)
  6219. movq -8(%rbp), -8(%rbp)
  6220. addq %rcx, -8(%rbp)
  6221. movq -16(%rbp), %rcx
  6222. negq %rcx
  6223. movq -8(%rbp), -8(%rbp)
  6224. addq %rcx, -8(%rbp)
  6225. movq -8(%rbp), %rdi
  6226. callq print_int
  6227. \end{lstlisting}
  6228. \end{minipage}
  6229. $\Rightarrow\qquad$
  6230. \begin{minipage}{0.45\textwidth}
  6231. \begin{lstlisting}
  6232. movq $1, -8(%rbp)
  6233. movq $42, %rcx
  6234. addq $7, -8(%rbp)
  6235. movq -8(%rbp), %rax
  6236. movq %rax, -16(%rbp)
  6237. addq %rcx, -8(%rbp)
  6238. movq -16(%rbp), %rcx
  6239. negq %rcx
  6240. addq %rcx, -8(%rbp)
  6241. movq -8(%rbp), %rdi
  6242. callq print_int
  6243. \end{lstlisting}
  6244. \end{minipage}
  6245. \fi}
  6246. \end{center}
  6247. \begin{exercise}\normalfont\normalsize
  6248. %
  6249. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6250. %
  6251. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6252. %in the \code{run-tests.rkt} script.
  6253. %
  6254. Run the script to test the \code{patch\_instructions} pass.
  6255. \end{exercise}
  6256. \section{Prelude and Conclusion}
  6257. \label{sec:print-x86-reg-alloc}
  6258. \index{subject}{calling conventions}
  6259. \index{subject}{prelude}\index{subject}{conclusion}
  6260. Recall that this pass generates the prelude and conclusion
  6261. instructions to satisfy the x86 calling conventions
  6262. (section~\ref{sec:calling-conventions}). With the addition of the
  6263. register allocator, the callee-saved registers used by the register
  6264. allocator must be saved in the prelude and restored in the conclusion.
  6265. In the \code{allocate\_registers} pass,
  6266. %
  6267. \racket{add an entry to the \itm{info}
  6268. of \code{X86Program} named \code{used\_callee}}
  6269. %
  6270. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6271. %
  6272. that stores the set of callee-saved registers that were assigned to
  6273. variables. The \code{prelude\_and\_conclusion} pass can then access
  6274. this information to decide which callee-saved registers need to be
  6275. saved and restored.
  6276. %
  6277. When calculating the amount to adjust the \code{rsp} in the prelude,
  6278. make sure to take into account the space used for saving the
  6279. callee-saved registers. Also, remember that the frame needs to be a
  6280. multiple of 16 bytes! We recommend using the following equation for
  6281. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6282. of stack locations used by spilled variables\footnote{Sometimes two or
  6283. more spilled variables are assigned to the same stack location, so
  6284. $S$ can be less than the number of spilled variables.} and $C$ be
  6285. the number of callee-saved registers that were
  6286. allocated\index{subject}{allocate} to
  6287. variables. The $\itm{align}$ function rounds a number up to the
  6288. nearest 16 bytes.
  6289. \[
  6290. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6291. \]
  6292. The reason we subtract $8\itm{C}$ in this equation is that the
  6293. prelude uses \code{pushq} to save each of the callee-saved registers,
  6294. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6295. \racket{An overview of all the passes involved in register
  6296. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6297. {\if\edition\racketEd
  6298. \begin{figure}[tbp]
  6299. \begin{tcolorbox}[colback=white]
  6300. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6301. \node (Lvar) at (0,2) {\large \LangVar{}};
  6302. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6303. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6304. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6305. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6306. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6307. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6308. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6309. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6310. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6311. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6312. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6313. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6314. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6315. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6316. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6317. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6318. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6319. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6320. \end{tikzpicture}
  6321. \end{tcolorbox}
  6322. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6323. \label{fig:reg-alloc-passes}
  6324. \end{figure}
  6325. \fi}
  6326. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6327. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6328. use of registers and the stack, we limit the register allocator for
  6329. this example to use just two registers: \code{rcx} (color $0$) and
  6330. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6331. \code{main} function, we push \code{rbx} onto the stack because it is
  6332. a callee-saved register and it was assigned to a variable by the
  6333. register allocator. We subtract \code{8} from the \code{rsp} at the
  6334. end of the prelude to reserve space for the one spilled variable.
  6335. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6336. Moving on to the program proper, we see how the registers were
  6337. allocated.
  6338. %
  6339. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6340. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6341. %
  6342. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6343. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6344. were assigned to \code{rbx}.}
  6345. %
  6346. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6347. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6348. callee-save register \code{rbx} onto the stack. The spilled variables
  6349. must be placed lower on the stack than the saved callee-save
  6350. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6351. \code{-16(\%rbp)}.
  6352. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6353. done in the prelude. We move the stack pointer up by \code{8} bytes
  6354. (the room for spilled variables), then pop the old values of
  6355. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6356. \code{retq} to return control to the operating system.
  6357. \begin{figure}[tbp]
  6358. \begin{minipage}{0.55\textwidth}
  6359. \begin{tcolorbox}[colback=white]
  6360. % var_test_28.rkt
  6361. % (use-minimal-set-of-registers! #t)
  6362. % 0 -> rcx
  6363. % 1 -> rbx
  6364. %
  6365. % t 0 rcx
  6366. % z 1 rbx
  6367. % w 0 rcx
  6368. % y 2 rbp -16
  6369. % v 1 rbx
  6370. % x 1 rbx
  6371. {\if\edition\racketEd
  6372. \begin{lstlisting}
  6373. start:
  6374. movq $1, %rbx
  6375. movq $42, %rcx
  6376. addq $7, %rbx
  6377. movq %rbx, -16(%rbp)
  6378. addq %rcx, %rbx
  6379. movq -16(%rbp), %rcx
  6380. negq %rcx
  6381. movq %rbx, %rax
  6382. addq %rcx, %rax
  6383. jmp conclusion
  6384. .globl main
  6385. main:
  6386. pushq %rbp
  6387. movq %rsp, %rbp
  6388. pushq %rbx
  6389. subq $8, %rsp
  6390. jmp start
  6391. conclusion:
  6392. addq $8, %rsp
  6393. popq %rbx
  6394. popq %rbp
  6395. retq
  6396. \end{lstlisting}
  6397. \fi}
  6398. {\if\edition\pythonEd\pythonColor
  6399. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6400. \begin{lstlisting}
  6401. .globl main
  6402. main:
  6403. pushq %rbp
  6404. movq %rsp, %rbp
  6405. pushq %rbx
  6406. subq $8, %rsp
  6407. movq $1, %rcx
  6408. movq $42, %rbx
  6409. addq $7, %rcx
  6410. movq %rcx, -16(%rbp)
  6411. addq %rbx, -16(%rbp)
  6412. negq %rcx
  6413. movq -16(%rbp), %rbx
  6414. addq %rcx, %rbx
  6415. movq %rbx, %rdi
  6416. callq print_int
  6417. addq $8, %rsp
  6418. popq %rbx
  6419. popq %rbp
  6420. retq
  6421. \end{lstlisting}
  6422. \fi}
  6423. \end{tcolorbox}
  6424. \end{minipage}
  6425. \caption{The x86 output from the running example
  6426. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6427. and \code{rcx}.}
  6428. \label{fig:running-example-x86}
  6429. \end{figure}
  6430. \begin{exercise}\normalfont\normalsize
  6431. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6432. %
  6433. \racket{
  6434. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6435. list of passes and the call to \code{compiler-tests}.}
  6436. %
  6437. Run the script to test the complete compiler for \LangVar{} that
  6438. performs register allocation.
  6439. \end{exercise}
  6440. \section{Challenge: Move Biasing}
  6441. \label{sec:move-biasing}
  6442. \index{subject}{move biasing}
  6443. This section describes an enhancement to the register allocator,
  6444. called move biasing, for students who are looking for an extra
  6445. challenge.
  6446. {\if\edition\racketEd
  6447. To motivate the need for move biasing we return to the running example,
  6448. but this time we use all the general purpose registers. So, we have
  6449. the following mapping of color numbers to registers.
  6450. \[
  6451. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6452. \]
  6453. Using the same assignment of variables to color numbers that was
  6454. produced by the register allocator described in the last section, we
  6455. get the following program.
  6456. \begin{center}
  6457. \begin{minipage}{0.35\textwidth}
  6458. \begin{lstlisting}
  6459. movq $1, v
  6460. movq $42, w
  6461. movq v, x
  6462. addq $7, x
  6463. movq x, y
  6464. movq x, z
  6465. addq w, z
  6466. movq y, t
  6467. negq t
  6468. movq z, %rax
  6469. addq t, %rax
  6470. jmp conclusion
  6471. \end{lstlisting}
  6472. \end{minipage}
  6473. $\Rightarrow\qquad$
  6474. \begin{minipage}{0.45\textwidth}
  6475. \begin{lstlisting}
  6476. movq $1, %rdx
  6477. movq $42, %rcx
  6478. movq %rdx, %rdx
  6479. addq $7, %rdx
  6480. movq %rdx, %rsi
  6481. movq %rdx, %rdx
  6482. addq %rcx, %rdx
  6483. movq %rsi, %rcx
  6484. negq %rcx
  6485. movq %rdx, %rax
  6486. addq %rcx, %rax
  6487. jmp conclusion
  6488. \end{lstlisting}
  6489. \end{minipage}
  6490. \end{center}
  6491. In this output code there are two \key{movq} instructions that
  6492. can be removed because their source and target are the same. However,
  6493. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6494. register, we could instead remove three \key{movq} instructions. We
  6495. can accomplish this by taking into account which variables appear in
  6496. \key{movq} instructions with which other variables.
  6497. \fi}
  6498. {\if\edition\pythonEd\pythonColor
  6499. %
  6500. To motivate the need for move biasing we return to the running example
  6501. and recall that in section~\ref{sec:patch-instructions} we were able to
  6502. remove three trivial move instructions from the running
  6503. example. However, we could remove another trivial move if we were able
  6504. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6505. We say that two variables $p$ and $q$ are \emph{move
  6506. related}\index{subject}{move related} if they participate together in
  6507. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6508. \key{movq} $q$\key{,} $p$.
  6509. %
  6510. Recall that we color variables that are more saturated before coloring
  6511. variables that are less saturated, and in the case of equally
  6512. saturated variables, we choose randomly. Now we break such ties by
  6513. giving preference to variables that have an available color that is
  6514. the same as the color of a move-related variable.
  6515. %
  6516. Furthermore, when the register allocator chooses a color for a
  6517. variable, it should prefer a color that has already been used for a
  6518. move-related variable if one exists (and assuming that they do not
  6519. interfere). This preference should not override the preference for
  6520. registers over stack locations. So, this preference should be used as
  6521. a tie breaker in choosing between two registers or in choosing between
  6522. two stack locations.
  6523. We recommend representing the move relationships in a graph, similarly
  6524. to how we represented interference. The following is the \emph{move
  6525. graph} for our running example.
  6526. {\if\edition\racketEd
  6527. \[
  6528. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6529. \node (rax) at (0,0) {$\ttm{rax}$};
  6530. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6531. \node (t) at (0,2) {$\ttm{t}$};
  6532. \node (z) at (3,2) {$\ttm{z}$};
  6533. \node (x) at (6,2) {$\ttm{x}$};
  6534. \node (y) at (3,0) {$\ttm{y}$};
  6535. \node (w) at (6,0) {$\ttm{w}$};
  6536. \node (v) at (9,0) {$\ttm{v}$};
  6537. \draw (v) to (x);
  6538. \draw (x) to (y);
  6539. \draw (x) to (z);
  6540. \draw (y) to (t);
  6541. \end{tikzpicture}
  6542. \]
  6543. \fi}
  6544. %
  6545. {\if\edition\pythonEd\pythonColor
  6546. \[
  6547. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6548. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6549. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6550. \node (z) at (3,2) {$\ttm{z}$};
  6551. \node (x) at (6,2) {$\ttm{x}$};
  6552. \node (y) at (3,0) {$\ttm{y}$};
  6553. \node (w) at (6,0) {$\ttm{w}$};
  6554. \node (v) at (9,0) {$\ttm{v}$};
  6555. \draw (y) to (t0);
  6556. \draw (z) to (x);
  6557. \draw (z) to (t1);
  6558. \draw (x) to (y);
  6559. \draw (x) to (v);
  6560. \end{tikzpicture}
  6561. \]
  6562. \fi}
  6563. {\if\edition\racketEd
  6564. Now we replay the graph coloring, pausing to see the coloring of
  6565. \code{y}. Recall the following configuration. The most saturated vertices
  6566. were \code{w} and \code{y}.
  6567. \[
  6568. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6569. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6570. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6571. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6572. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6573. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6574. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6575. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6576. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6577. \draw (t1) to (rax);
  6578. \draw (t1) to (z);
  6579. \draw (z) to (y);
  6580. \draw (z) to (w);
  6581. \draw (x) to (w);
  6582. \draw (y) to (w);
  6583. \draw (v) to (w);
  6584. \draw (v) to (rsp);
  6585. \draw (w) to (rsp);
  6586. \draw (x) to (rsp);
  6587. \draw (y) to (rsp);
  6588. \path[-.,bend left=15] (z) edge node {} (rsp);
  6589. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6590. \draw (rax) to (rsp);
  6591. \end{tikzpicture}
  6592. \]
  6593. %
  6594. The last time, we chose to color \code{w} with $0$. This time, we see
  6595. that \code{w} is not move-related to any vertex, but \code{y} is
  6596. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6597. the same color as \code{t}.
  6598. \[
  6599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6601. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6602. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6603. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6604. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6605. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6606. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6607. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6608. \draw (t1) to (rax);
  6609. \draw (t1) to (z);
  6610. \draw (z) to (y);
  6611. \draw (z) to (w);
  6612. \draw (x) to (w);
  6613. \draw (y) to (w);
  6614. \draw (v) to (w);
  6615. \draw (v) to (rsp);
  6616. \draw (w) to (rsp);
  6617. \draw (x) to (rsp);
  6618. \draw (y) to (rsp);
  6619. \path[-.,bend left=15] (z) edge node {} (rsp);
  6620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6621. \draw (rax) to (rsp);
  6622. \end{tikzpicture}
  6623. \]
  6624. Now \code{w} is the most saturated, so we color it $2$.
  6625. \[
  6626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6627. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6628. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6629. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6630. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6631. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6632. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6633. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6634. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6635. \draw (t1) to (rax);
  6636. \draw (t1) to (z);
  6637. \draw (z) to (y);
  6638. \draw (z) to (w);
  6639. \draw (x) to (w);
  6640. \draw (y) to (w);
  6641. \draw (v) to (w);
  6642. \draw (v) to (rsp);
  6643. \draw (w) to (rsp);
  6644. \draw (x) to (rsp);
  6645. \draw (y) to (rsp);
  6646. \path[-.,bend left=15] (z) edge node {} (rsp);
  6647. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6648. \draw (rax) to (rsp);
  6649. \end{tikzpicture}
  6650. \]
  6651. At this point, vertices \code{x} and \code{v} are most saturated, but
  6652. \code{x} is move related to \code{y} and \code{z}, so we color
  6653. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6654. \[
  6655. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6656. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6657. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6658. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6659. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6660. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6661. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6662. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6663. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6664. \draw (t1) to (rax);
  6665. \draw (t) to (z);
  6666. \draw (z) to (y);
  6667. \draw (z) to (w);
  6668. \draw (x) to (w);
  6669. \draw (y) to (w);
  6670. \draw (v) to (w);
  6671. \draw (v) to (rsp);
  6672. \draw (w) to (rsp);
  6673. \draw (x) to (rsp);
  6674. \draw (y) to (rsp);
  6675. \path[-.,bend left=15] (z) edge node {} (rsp);
  6676. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6677. \draw (rax) to (rsp);
  6678. \end{tikzpicture}
  6679. \]
  6680. \fi}
  6681. %
  6682. {\if\edition\pythonEd\pythonColor
  6683. Now we replay the graph coloring, pausing before the coloring of
  6684. \code{w}. Recall the following configuration. The most saturated vertices
  6685. were \code{tmp\_1}, \code{w}, and \code{y}.
  6686. \[
  6687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6688. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6689. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6690. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6691. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6692. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6693. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6694. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6695. \draw (t0) to (t1);
  6696. \draw (t0) to (z);
  6697. \draw (z) to (y);
  6698. \draw (z) to (w);
  6699. \draw (x) to (w);
  6700. \draw (y) to (w);
  6701. \draw (v) to (w);
  6702. \end{tikzpicture}
  6703. \]
  6704. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6705. or \code{y}. Note, however, that \code{w} is not move related to any
  6706. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6707. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6708. \code{y} and color it $0$, we can delete another move instruction.
  6709. \[
  6710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6711. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6712. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6713. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6714. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6715. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6716. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6717. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6718. \draw (t0) to (t1);
  6719. \draw (t0) to (z);
  6720. \draw (z) to (y);
  6721. \draw (z) to (w);
  6722. \draw (x) to (w);
  6723. \draw (y) to (w);
  6724. \draw (v) to (w);
  6725. \end{tikzpicture}
  6726. \]
  6727. Now \code{w} is the most saturated, so we color it $2$.
  6728. \[
  6729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6730. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6731. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6732. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6733. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6734. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6735. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6736. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6737. \draw (t0) to (t1);
  6738. \draw (t0) to (z);
  6739. \draw (z) to (y);
  6740. \draw (z) to (w);
  6741. \draw (x) to (w);
  6742. \draw (y) to (w);
  6743. \draw (v) to (w);
  6744. \end{tikzpicture}
  6745. \]
  6746. To finish the coloring, \code{x} and \code{v} get $0$ and
  6747. \code{tmp\_1} gets $1$.
  6748. \[
  6749. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6750. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6751. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6752. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6753. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6754. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6755. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6756. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6757. \draw (t0) to (t1);
  6758. \draw (t0) to (z);
  6759. \draw (z) to (y);
  6760. \draw (z) to (w);
  6761. \draw (x) to (w);
  6762. \draw (y) to (w);
  6763. \draw (v) to (w);
  6764. \end{tikzpicture}
  6765. \]
  6766. \fi}
  6767. So, we have the following assignment of variables to registers.
  6768. {\if\edition\racketEd
  6769. \begin{gather*}
  6770. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6771. \ttm{w} \mapsto \key{\%rsi}, \,
  6772. \ttm{x} \mapsto \key{\%rcx}, \,
  6773. \ttm{y} \mapsto \key{\%rcx}, \,
  6774. \ttm{z} \mapsto \key{\%rdx}, \,
  6775. \ttm{t} \mapsto \key{\%rcx} \}
  6776. \end{gather*}
  6777. \fi}
  6778. {\if\edition\pythonEd\pythonColor
  6779. \begin{gather*}
  6780. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6781. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6782. \ttm{x} \mapsto \key{\%rcx}, \,
  6783. \ttm{y} \mapsto \key{\%rcx}, \\
  6784. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6785. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6786. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6787. \end{gather*}
  6788. \fi}
  6789. %
  6790. We apply this register assignment to the running example shown next,
  6791. on the left, to obtain the code in the middle. The
  6792. \code{patch\_instructions} then deletes the trivial moves to obtain
  6793. the code on the right.
  6794. {\if\edition\racketEd
  6795. \begin{center}
  6796. \begin{minipage}{0.2\textwidth}
  6797. \begin{lstlisting}
  6798. movq $1, v
  6799. movq $42, w
  6800. movq v, x
  6801. addq $7, x
  6802. movq x, y
  6803. movq x, z
  6804. addq w, z
  6805. movq y, t
  6806. negq t
  6807. movq z, %rax
  6808. addq t, %rax
  6809. jmp conclusion
  6810. \end{lstlisting}
  6811. \end{minipage}
  6812. $\Rightarrow\qquad$
  6813. \begin{minipage}{0.25\textwidth}
  6814. \begin{lstlisting}
  6815. movq $1, %rcx
  6816. movq $42, %rsi
  6817. movq %rcx, %rcx
  6818. addq $7, %rcx
  6819. movq %rcx, %rcx
  6820. movq %rcx, %rdx
  6821. addq %rsi, %rdx
  6822. movq %rcx, %rcx
  6823. negq %rcx
  6824. movq %rdx, %rax
  6825. addq %rcx, %rax
  6826. jmp conclusion
  6827. \end{lstlisting}
  6828. \end{minipage}
  6829. $\Rightarrow\qquad$
  6830. \begin{minipage}{0.23\textwidth}
  6831. \begin{lstlisting}
  6832. movq $1, %rcx
  6833. movq $42, %rsi
  6834. addq $7, %rcx
  6835. movq %rcx, %rdx
  6836. addq %rsi, %rdx
  6837. negq %rcx
  6838. movq %rdx, %rax
  6839. addq %rcx, %rax
  6840. jmp conclusion
  6841. \end{lstlisting}
  6842. \end{minipage}
  6843. \end{center}
  6844. \fi}
  6845. {\if\edition\pythonEd\pythonColor
  6846. \begin{center}
  6847. \begin{minipage}{0.20\textwidth}
  6848. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6849. movq $1, v
  6850. movq $42, w
  6851. movq v, x
  6852. addq $7, x
  6853. movq x, y
  6854. movq x, z
  6855. addq w, z
  6856. movq y, tmp_0
  6857. negq tmp_0
  6858. movq z, tmp_1
  6859. addq tmp_0, tmp_1
  6860. movq tmp_1, %rdi
  6861. callq _print_int
  6862. \end{lstlisting}
  6863. \end{minipage}
  6864. ${\Rightarrow\qquad}$
  6865. \begin{minipage}{0.35\textwidth}
  6866. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6867. movq $1, %rcx
  6868. movq $42, -16(%rbp)
  6869. movq %rcx, %rcx
  6870. addq $7, %rcx
  6871. movq %rcx, %rcx
  6872. movq %rcx, -8(%rbp)
  6873. addq -16(%rbp), -8(%rbp)
  6874. movq %rcx, %rcx
  6875. negq %rcx
  6876. movq -8(%rbp), -8(%rbp)
  6877. addq %rcx, -8(%rbp)
  6878. movq -8(%rbp), %rdi
  6879. callq _print_int
  6880. \end{lstlisting}
  6881. \end{minipage}
  6882. ${\Rightarrow\qquad}$
  6883. \begin{minipage}{0.20\textwidth}
  6884. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6885. movq $1, %rcx
  6886. movq $42, -16(%rbp)
  6887. addq $7, %rcx
  6888. movq %rcx, -8(%rbp)
  6889. movq -16(%rbp), %rax
  6890. addq %rax, -8(%rbp)
  6891. negq %rcx
  6892. addq %rcx, -8(%rbp)
  6893. movq -8(%rbp), %rdi
  6894. callq print_int
  6895. \end{lstlisting}
  6896. \end{minipage}
  6897. \end{center}
  6898. \fi}
  6899. \begin{exercise}\normalfont\normalsize
  6900. Change your implementation of \code{allocate\_registers} to take move
  6901. biasing into account. Create two new tests that include at least one
  6902. opportunity for move biasing, and visually inspect the output x86
  6903. programs to make sure that your move biasing is working properly. Make
  6904. sure that your compiler still passes all the tests.
  6905. \end{exercise}
  6906. %To do: another neat challenge would be to do
  6907. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6908. %% \subsection{Output of the Running Example}
  6909. %% \label{sec:reg-alloc-output}
  6910. % challenge: prioritize variables based on execution frequencies
  6911. % and the number of uses of a variable
  6912. % challenge: enhance the coloring algorithm using Chaitin's
  6913. % approach of prioritizing high-degree variables
  6914. % by removing low-degree variables (coloring them later)
  6915. % from the interference graph
  6916. \section{Further Reading}
  6917. \label{sec:register-allocation-further-reading}
  6918. Early register allocation algorithms were developed for Fortran
  6919. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6920. of graph coloring began in the late 1970s and early 1980s with the
  6921. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6922. algorithm is based on the following observation of
  6923. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6924. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6925. $v$ removed is also $k$ colorable. To see why, suppose that the
  6926. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6927. different colors, but because there are fewer than $k$ neighbors, there
  6928. will be one or more colors left over to use for coloring $v$ in $G$.
  6929. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6930. less than $k$ from the graph and recursively colors the rest of the
  6931. graph. Upon returning from the recursion, it colors $v$ with one of
  6932. the available colors and returns. \citet{Chaitin:1982vn} augments
  6933. this algorithm to handle spilling as follows. If there are no vertices
  6934. of degree lower than $k$ then pick a vertex at random, spill it,
  6935. remove it from the graph, and proceed recursively to color the rest of
  6936. the graph.
  6937. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6938. move-related and that don't interfere with each other, in a process
  6939. called \emph{coalescing}. Although coalescing decreases the number of
  6940. moves, it can make the graph more difficult to
  6941. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6942. which two variables are merged only if they have fewer than $k$
  6943. neighbors of high degree. \citet{George:1996aa} observes that
  6944. conservative coalescing is sometimes too conservative and made it more
  6945. aggressive by iterating the coalescing with the removal of low-degree
  6946. vertices.
  6947. %
  6948. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6949. also proposed \emph{biased coloring}, in which a variable is assigned to
  6950. the same color as another move-related variable if possible, as
  6951. discussed in section~\ref{sec:move-biasing}.
  6952. %
  6953. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6954. performs coalescing, graph coloring, and spill code insertion until
  6955. all variables have been assigned a location.
  6956. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6957. spilled variables that don't have to be: a high-degree variable can be
  6958. colorable if many of its neighbors are assigned the same color.
  6959. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6960. high-degree vertex is not immediately spilled. Instead the decision is
  6961. deferred until after the recursive call, when it is apparent whether
  6962. there is an available color or not. We observe that this algorithm is
  6963. equivalent to the smallest-last ordering
  6964. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6965. be registers and the rest to be stack locations.
  6966. %% biased coloring
  6967. Earlier editions of the compiler course at Indiana University
  6968. \citep{Dybvig:2010aa} were based on the algorithm of
  6969. \citet{Briggs:1994kx}.
  6970. The smallest-last ordering algorithm is one of many \emph{greedy}
  6971. coloring algorithms. A greedy coloring algorithm visits all the
  6972. vertices in a particular order and assigns each one the first
  6973. available color. An \emph{offline} greedy algorithm chooses the
  6974. ordering up front, prior to assigning colors. The algorithm of
  6975. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6976. ordering does not depend on the colors assigned. Other orderings are
  6977. possible. For example, \citet{Chow:1984ys} ordered variables according
  6978. to an estimate of runtime cost.
  6979. An \emph{online} greedy coloring algorithm uses information about the
  6980. current assignment of colors to influence the order in which the
  6981. remaining vertices are colored. The saturation-based algorithm
  6982. described in this chapter is one such algorithm. We choose to use
  6983. saturation-based coloring because it is fun to introduce graph
  6984. coloring via sudoku!
  6985. A register allocator may choose to map each variable to just one
  6986. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6987. variable to one or more locations. The latter can be achieved by
  6988. \emph{live range splitting}, where a variable is replaced by several
  6989. variables that each handle part of its live
  6990. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6991. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6992. %% replacement algorithm, bottom-up local
  6993. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6994. %% Cooper: top-down (priority bassed), bottom-up
  6995. %% top-down
  6996. %% order variables by priority (estimated cost)
  6997. %% caveat: split variables into two groups:
  6998. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6999. %% color the constrained ones first
  7000. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7001. %% cite J. Cocke for an algorithm that colors variables
  7002. %% in a high-degree first ordering
  7003. %Register Allocation via Usage Counts, Freiburghouse CACM
  7004. \citet{Palsberg:2007si} observes that many of the interference graphs
  7005. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7006. that is, every cycle with four or more edges has an edge that is not
  7007. part of the cycle but that connects two vertices on the cycle. Such
  7008. graphs can be optimally colored by the greedy algorithm with a vertex
  7009. ordering determined by maximum cardinality search.
  7010. In situations in which compile time is of utmost importance, such as
  7011. in just-in-time compilers, graph coloring algorithms can be too
  7012. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7013. be more appropriate.
  7014. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7015. {\if\edition\racketEd
  7016. \addtocontents{toc}{\newpage}
  7017. \fi}
  7018. \chapter{Booleans and Conditionals}
  7019. \label{ch:Lif}
  7020. \setcounter{footnote}{0}
  7021. The \LangVar{} language has only a single kind of value, the
  7022. integers. In this chapter we add a second kind of value, the Booleans,
  7023. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7024. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7025. are written
  7026. \TRUE{}\index{subject}{True@\TRUE{}} and
  7027. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7028. language includes several operations that involve Booleans
  7029. (\key{and}\index{subject}{and@\ANDNAME{}},
  7030. \key{or}\index{subject}{or@\ORNAME{}},
  7031. \key{not}\index{subject}{not@\NOTNAME{}},
  7032. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7033. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7034. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7035. conditional expression\index{subject}{conditional expression}
  7036. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7037. With the addition of \key{if}, programs can have
  7038. nontrivial control flow\index{subject}{control flow}, which
  7039. %
  7040. \racket{impacts \code{explicate\_control} and liveness analysis.}
  7041. %
  7042. \python{impacts liveness analysis and motivates a new pass named
  7043. \code{explicate\_control}.}
  7044. %
  7045. Also, because we now have two kinds of values, we need to handle
  7046. programs that apply an operation to the wrong kind of value, such as
  7047. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7048. There are two language design options for such situations. One option
  7049. is to signal an error and the other is to provide a wider
  7050. interpretation of the operation. \racket{The Racket
  7051. language}\python{Python} uses a mixture of these two options,
  7052. depending on the operation and the kind of value. For example, the
  7053. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7054. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7055. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7056. %
  7057. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7058. in Racket because \code{car} expects a pair.}
  7059. %
  7060. \python{On the other hand, \code{1[0]} results in a runtime error
  7061. in Python because an ``\code{int} object is not subscriptable.''}
  7062. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7063. design choices as \racket{Racket}\python{Python}, except that much of the
  7064. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7065. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7066. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7067. \python{MyPy} reports a compile-time error
  7068. %
  7069. \racket{because Racket expects the type of the argument to be of the form
  7070. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7071. %
  7072. \python{stating that a ``value of type \code{int} is not indexable.''}
  7073. The \LangIf{} language performs type checking during compilation just as
  7074. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7075. the alternative choice, that is, a dynamically typed language like
  7076. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7077. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7078. restrictive, for example, rejecting \racket{\code{(not
  7079. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7080. fairly simple because the focus of this book is on compilation and not
  7081. type systems, about which there are already several excellent
  7082. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7083. This chapter is organized as follows. We begin by defining the syntax
  7084. and interpreter for the \LangIf{} language
  7085. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7086. checking (aka semantic analysis\index{subject}{semantic analysis})
  7087. and define a type checker for \LangIf{}
  7088. (section~\ref{sec:type-check-Lif}).
  7089. %
  7090. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7091. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7092. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7093. %
  7094. The remaining sections of this chapter discuss how Booleans and
  7095. conditional control flow require changes to the existing compiler
  7096. passes and the addition of new ones. We introduce the \code{shrink}
  7097. pass to translate some operators into others, thereby reducing the
  7098. number of operators that need to be handled in later passes.
  7099. %
  7100. The main event of this chapter is the \code{explicate\_control} pass
  7101. that is responsible for translating \code{if}s into conditional
  7102. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7103. %
  7104. Regarding register allocation, there is the interesting question of
  7105. how to handle conditional \code{goto}s during liveness analysis.
  7106. \section{The \LangIf{} Language}
  7107. \label{sec:lang-if}
  7108. Definitions of the concrete syntax and abstract syntax of the
  7109. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7110. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7111. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7112. literals\index{subject}{literals}
  7113. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7114. \python{, and the \code{if} statement}. We expand the set of
  7115. operators to include
  7116. \begin{enumerate}
  7117. \item the logical operators \key{and}, \key{or}, and \key{not},
  7118. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7119. for comparing integers or Booleans for equality, and
  7120. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7121. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7122. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7123. comparing integers.
  7124. \end{enumerate}
  7125. \racket{We reorganize the abstract syntax for the primitive
  7126. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7127. rule for all of them. This means that the grammar no longer checks
  7128. whether the arity of an operator matches the number of
  7129. arguments. That responsibility is moved to the type checker for
  7130. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7131. \newcommand{\LifGrammarRacket}{
  7132. \begin{array}{lcl}
  7133. \Type &::=& \key{Boolean} \\
  7134. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7135. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7136. \Exp &::=& \itm{bool}
  7137. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7138. \MID (\key{not}\;\Exp) \\
  7139. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7140. \end{array}
  7141. }
  7142. \newcommand{\LifASTRacket}{
  7143. \begin{array}{lcl}
  7144. \Type &::=& \key{Boolean} \\
  7145. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7146. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7147. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7148. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7149. \end{array}
  7150. }
  7151. \newcommand{\LintOpAST}{
  7152. \begin{array}{rcl}
  7153. \Type &::=& \key{Integer} \\
  7154. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7155. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7156. \end{array}
  7157. }
  7158. \newcommand{\LifGrammarPython}{
  7159. \begin{array}{rcl}
  7160. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7161. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7162. \MID \key{not}~\Exp \\
  7163. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7164. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7165. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7166. \end{array}
  7167. }
  7168. \newcommand{\LifASTPython}{
  7169. \begin{array}{lcl}
  7170. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7171. \itm{unaryop} &::=& \code{Not()} \\
  7172. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7173. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7174. \Exp &::=& \BOOL{\itm{bool}}
  7175. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7176. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7177. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7178. \end{array}
  7179. }
  7180. \begin{figure}[tp]
  7181. \centering
  7182. \begin{tcolorbox}[colback=white]
  7183. {\if\edition\racketEd
  7184. \[
  7185. \begin{array}{l}
  7186. \gray{\LintGrammarRacket{}} \\ \hline
  7187. \gray{\LvarGrammarRacket{}} \\ \hline
  7188. \LifGrammarRacket{} \\
  7189. \begin{array}{lcl}
  7190. \LangIfM{} &::=& \Exp
  7191. \end{array}
  7192. \end{array}
  7193. \]
  7194. \fi}
  7195. {\if\edition\pythonEd\pythonColor
  7196. \[
  7197. \begin{array}{l}
  7198. \gray{\LintGrammarPython} \\ \hline
  7199. \gray{\LvarGrammarPython} \\ \hline
  7200. \LifGrammarPython \\
  7201. \begin{array}{rcl}
  7202. \LangIfM{} &::=& \Stmt^{*}
  7203. \end{array}
  7204. \end{array}
  7205. \]
  7206. \fi}
  7207. \end{tcolorbox}
  7208. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7209. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7210. \label{fig:Lif-concrete-syntax}
  7211. \end{figure}
  7212. \begin{figure}[tp]
  7213. %\begin{minipage}{0.66\textwidth}
  7214. \begin{tcolorbox}[colback=white]
  7215. \centering
  7216. {\if\edition\racketEd
  7217. \[
  7218. \begin{array}{l}
  7219. \gray{\LintOpAST} \\ \hline
  7220. \gray{\LvarASTRacket{}} \\ \hline
  7221. \LifASTRacket{} \\
  7222. \begin{array}{lcl}
  7223. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7224. \end{array}
  7225. \end{array}
  7226. \]
  7227. \fi}
  7228. {\if\edition\pythonEd\pythonColor
  7229. \[
  7230. \begin{array}{l}
  7231. \gray{\LintASTPython} \\ \hline
  7232. \gray{\LvarASTPython} \\ \hline
  7233. \LifASTPython \\
  7234. \begin{array}{lcl}
  7235. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7236. \end{array}
  7237. \end{array}
  7238. \]
  7239. \fi}
  7240. \end{tcolorbox}
  7241. %\end{minipage}
  7242. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7243. \python{
  7244. \index{subject}{BoolOp@\texttt{BoolOp}}
  7245. \index{subject}{Compare@\texttt{Compare}}
  7246. \index{subject}{Lt@\texttt{Lt}}
  7247. \index{subject}{LtE@\texttt{LtE}}
  7248. \index{subject}{Gt@\texttt{Gt}}
  7249. \index{subject}{GtE@\texttt{GtE}}
  7250. }
  7251. \caption{The abstract syntax of \LangIf{}.}
  7252. \label{fig:Lif-syntax}
  7253. \end{figure}
  7254. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7255. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7256. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7257. evaluate to the corresponding Boolean values. The conditional
  7258. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7259. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7260. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7261. \code{or}, and \code{not} behave according to propositional logic. In
  7262. addition, the \code{and} and \code{or} operations perform
  7263. \emph{short-circuit evaluation}.
  7264. %
  7265. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7266. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7267. %
  7268. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7269. evaluated if $e_1$ evaluates to \TRUE{}.
  7270. \racket{With the increase in the number of primitive operations, the
  7271. interpreter would become repetitive without some care. We refactor
  7272. the case for \code{Prim}, moving the code that differs with each
  7273. operation into the \code{interp\_op} method shown in
  7274. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7275. \code{or} operations separately because of their short-circuiting
  7276. behavior.}
  7277. \begin{figure}[tbp]
  7278. \begin{tcolorbox}[colback=white]
  7279. {\if\edition\racketEd
  7280. \begin{lstlisting}
  7281. (define interp-Lif-class
  7282. (class interp-Lvar-class
  7283. (super-new)
  7284. (define/public (interp_op op) ...)
  7285. (define/override ((interp_exp env) e)
  7286. (define recur (interp_exp env))
  7287. (match e
  7288. [(Bool b) b]
  7289. [(If cnd thn els)
  7290. (match (recur cnd)
  7291. [#t (recur thn)]
  7292. [#f (recur els)])]
  7293. [(Prim 'and (list e1 e2))
  7294. (match (recur e1)
  7295. [#t (match (recur e2) [#t #t] [#f #f])]
  7296. [#f #f])]
  7297. [(Prim 'or (list e1 e2))
  7298. (define v1 (recur e1))
  7299. (match v1
  7300. [#t #t]
  7301. [#f (match (recur e2) [#t #t] [#f #f])])]
  7302. [(Prim op args)
  7303. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7304. [else ((super interp_exp env) e)]))
  7305. ))
  7306. (define (interp_Lif p)
  7307. (send (new interp-Lif-class) interp_program p))
  7308. \end{lstlisting}
  7309. \fi}
  7310. {\if\edition\pythonEd\pythonColor
  7311. \begin{lstlisting}
  7312. class InterpLif(InterpLvar):
  7313. def interp_exp(self, e, env):
  7314. match e:
  7315. case IfExp(test, body, orelse):
  7316. if self.interp_exp(test, env):
  7317. return self.interp_exp(body, env)
  7318. else:
  7319. return self.interp_exp(orelse, env)
  7320. case UnaryOp(Not(), v):
  7321. return not self.interp_exp(v, env)
  7322. case BoolOp(And(), values):
  7323. if self.interp_exp(values[0], env):
  7324. return self.interp_exp(values[1], env)
  7325. else:
  7326. return False
  7327. case BoolOp(Or(), values):
  7328. if self.interp_exp(values[0], env):
  7329. return True
  7330. else:
  7331. return self.interp_exp(values[1], env)
  7332. case Compare(left, [cmp], [right]):
  7333. l = self.interp_exp(left, env)
  7334. r = self.interp_exp(right, env)
  7335. return self.interp_cmp(cmp)(l, r)
  7336. case _:
  7337. return super().interp_exp(e, env)
  7338. def interp_stmt(self, s, env, cont):
  7339. match s:
  7340. case If(test, body, orelse):
  7341. match self.interp_exp(test, env):
  7342. case True:
  7343. return self.interp_stmts(body + cont, env)
  7344. case False:
  7345. return self.interp_stmts(orelse + cont, env)
  7346. case _:
  7347. return super().interp_stmt(s, env, cont)
  7348. ...
  7349. \end{lstlisting}
  7350. \fi}
  7351. \end{tcolorbox}
  7352. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7353. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7354. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7355. \label{fig:interp-Lif}
  7356. \end{figure}
  7357. {\if\edition\racketEd
  7358. \begin{figure}[tbp]
  7359. \begin{tcolorbox}[colback=white]
  7360. \begin{lstlisting}
  7361. (define/public (interp_op op)
  7362. (match op
  7363. ['+ fx+]
  7364. ['- fx-]
  7365. ['read read-fixnum]
  7366. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7367. ['eq? (lambda (v1 v2)
  7368. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7369. (and (boolean? v1) (boolean? v2))
  7370. (and (vector? v1) (vector? v2)))
  7371. (eq? v1 v2)]))]
  7372. ['< (lambda (v1 v2)
  7373. (cond [(and (fixnum? v1) (fixnum? v2))
  7374. (< v1 v2)]))]
  7375. ['<= (lambda (v1 v2)
  7376. (cond [(and (fixnum? v1) (fixnum? v2))
  7377. (<= v1 v2)]))]
  7378. ['> (lambda (v1 v2)
  7379. (cond [(and (fixnum? v1) (fixnum? v2))
  7380. (> v1 v2)]))]
  7381. ['>= (lambda (v1 v2)
  7382. (cond [(and (fixnum? v1) (fixnum? v2))
  7383. (>= v1 v2)]))]
  7384. [else (error 'interp_op "unknown operator")]))
  7385. \end{lstlisting}
  7386. \end{tcolorbox}
  7387. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7388. \label{fig:interp-op-Lif}
  7389. \end{figure}
  7390. \fi}
  7391. {\if\edition\pythonEd\pythonColor
  7392. \begin{figure}
  7393. \begin{tcolorbox}[colback=white]
  7394. \begin{lstlisting}
  7395. class InterpLif(InterpLvar):
  7396. ...
  7397. def interp_cmp(self, cmp):
  7398. match cmp:
  7399. case Lt():
  7400. return lambda x, y: x < y
  7401. case LtE():
  7402. return lambda x, y: x <= y
  7403. case Gt():
  7404. return lambda x, y: x > y
  7405. case GtE():
  7406. return lambda x, y: x >= y
  7407. case Eq():
  7408. return lambda x, y: x == y
  7409. case NotEq():
  7410. return lambda x, y: x != y
  7411. \end{lstlisting}
  7412. \end{tcolorbox}
  7413. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7414. \label{fig:interp-cmp-Lif}
  7415. \end{figure}
  7416. \fi}
  7417. \section{Type Checking \LangIf{} Programs}
  7418. \label{sec:type-check-Lif}
  7419. It is helpful to think about type checking\index{subject}{type
  7420. checking} in two complementary ways. A type checker predicts the
  7421. type of value that will be produced by each expression in the program.
  7422. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7423. type checker should predict that {\if\edition\racketEd
  7424. \begin{lstlisting}
  7425. (+ 10 (- (+ 12 20)))
  7426. \end{lstlisting}
  7427. \fi}
  7428. {\if\edition\pythonEd\pythonColor
  7429. \begin{lstlisting}
  7430. 10 + -(12 + 20)
  7431. \end{lstlisting}
  7432. \fi}
  7433. \noindent produces a value of type \INTTY{}, whereas
  7434. {\if\edition\racketEd
  7435. \begin{lstlisting}
  7436. (and (not #f) #t)
  7437. \end{lstlisting}
  7438. \fi}
  7439. {\if\edition\pythonEd\pythonColor
  7440. \begin{lstlisting}
  7441. (not False) and True
  7442. \end{lstlisting}
  7443. \fi}
  7444. \noindent produces a value of type \BOOLTY{}.
  7445. A second way to think about type checking is that it enforces a set of
  7446. rules about which operators can be applied to which kinds of
  7447. values. For example, our type checker for \LangIf{} signals an error
  7448. for the following expression:
  7449. %
  7450. {\if\edition\racketEd
  7451. \begin{lstlisting}
  7452. (not (+ 10 (- (+ 12 20))))
  7453. \end{lstlisting}
  7454. \fi}
  7455. {\if\edition\pythonEd\pythonColor
  7456. \begin{lstlisting}
  7457. not (10 + -(12 + 20))
  7458. \end{lstlisting}
  7459. \fi}
  7460. \noindent The subexpression
  7461. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7462. \python{\code{(10 + -(12 + 20))}}
  7463. has type \INTTY{}, but the type checker enforces the rule that the
  7464. argument of \code{not} must be an expression of type \BOOLTY{}.
  7465. We implement type checking using classes and methods because they
  7466. provide the open recursion needed to reuse code as we extend the type
  7467. checker in subsequent chapters, analogous to the use of classes and methods
  7468. for the interpreters (section~\ref{sec:extensible-interp}).
  7469. We separate the type checker for the \LangVar{} subset into its own
  7470. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7471. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7472. from the type checker for \LangVar{}. These type checkers are in the
  7473. files
  7474. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7475. and
  7476. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7477. of the support code.
  7478. %
  7479. Each type checker is a structurally recursive function over the AST.
  7480. Given an input expression \code{e}, the type checker either signals an
  7481. error or returns \racket{an expression and} its type.
  7482. %
  7483. \racket{It returns an expression because there are situations in which
  7484. we want to change or update the expression.}
  7485. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7486. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7487. constant is \INTTY{}. To handle variables, the type checker uses the
  7488. environment \code{env} to map variables to types.
  7489. %
  7490. \racket{Consider the case for \key{let}. We type check the
  7491. initializing expression to obtain its type \key{T} and then
  7492. associate type \code{T} with the variable \code{x} in the
  7493. environment used to type check the body of the \key{let}. Thus,
  7494. when the type checker encounters a use of variable \code{x}, it can
  7495. find its type in the environment.}
  7496. %
  7497. \python{Consider the case for assignment. We type check the
  7498. initializing expression to obtain its type \key{t}. If the variable
  7499. \code{lhs.id} is already in the environment because there was a
  7500. prior assignment, we check that this initializer has the same type
  7501. as the prior one. If this is the first assignment to the variable,
  7502. we associate type \code{t} with the variable \code{lhs.id} in the
  7503. environment. Thus, when the type checker encounters a use of
  7504. variable \code{x}, it can find its type in the environment.}
  7505. %
  7506. \racket{Regarding primitive operators, we recursively analyze the
  7507. arguments and then invoke \code{type\_check\_op} to check whether
  7508. the argument types are allowed.}
  7509. %
  7510. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7511. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7512. \racket{Several auxiliary methods are used in the type checker. The
  7513. method \code{operator-types} defines a dictionary that maps the
  7514. operator names to their parameter and return types. The
  7515. \code{type-equal?} method determines whether two types are equal,
  7516. which for now simply dispatches to \code{equal?} (deep
  7517. equality). The \code{check-type-equal?} method triggers an error if
  7518. the two types are not equal. The \code{type-check-op} method looks
  7519. up the operator in the \code{operator-types} dictionary and then
  7520. checks whether the argument types are equal to the parameter types.
  7521. The result is the return type of the operator.}
  7522. %
  7523. \python{The auxiliary method \code{check\_type\_equal} triggers
  7524. an error if the two types are not equal.}
  7525. \begin{figure}[tbp]
  7526. \begin{tcolorbox}[colback=white]
  7527. {\if\edition\racketEd
  7528. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7529. (define type-check-Lvar-class
  7530. (class object%
  7531. (super-new)
  7532. (define/public (operator-types)
  7533. '((+ . ((Integer Integer) . Integer))
  7534. (- . ((Integer Integer) . Integer))
  7535. (read . (() . Integer))))
  7536. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7537. (define/public (check-type-equal? t1 t2 e)
  7538. (unless (type-equal? t1 t2)
  7539. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7540. (define/public (type-check-op op arg-types e)
  7541. (match (dict-ref (operator-types) op)
  7542. [`(,param-types . ,return-type)
  7543. (for ([at arg-types] [pt param-types])
  7544. (check-type-equal? at pt e))
  7545. return-type]
  7546. [else (error 'type-check-op "unrecognized ~a" op)]))
  7547. (define/public (type-check-exp env)
  7548. (lambda (e)
  7549. (match e
  7550. [(Int n) (values (Int n) 'Integer)]
  7551. [(Var x) (values (Var x) (dict-ref env x))]
  7552. [(Let x e body)
  7553. (define-values (e^ Te) ((type-check-exp env) e))
  7554. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7555. (values (Let x e^ b) Tb)]
  7556. [(Prim op es)
  7557. (define-values (new-es ts)
  7558. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7559. (values (Prim op new-es) (type-check-op op ts e))]
  7560. [else (error 'type-check-exp "couldn't match" e)])))
  7561. (define/public (type-check-program e)
  7562. (match e
  7563. [(Program info body)
  7564. (define-values (body^ Tb) ((type-check-exp '()) body))
  7565. (check-type-equal? Tb 'Integer body)
  7566. (Program info body^)]
  7567. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7568. ))
  7569. (define (type-check-Lvar p)
  7570. (send (new type-check-Lvar-class) type-check-program p))
  7571. \end{lstlisting}
  7572. \fi}
  7573. {\if\edition\pythonEd\pythonColor
  7574. \begin{lstlisting}[escapechar=`]
  7575. class TypeCheckLvar:
  7576. def check_type_equal(self, t1, t2, e):
  7577. if t1 != t2:
  7578. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7579. raise Exception(msg)
  7580. def type_check_exp(self, e, env):
  7581. match e:
  7582. case BinOp(left, (Add() | Sub()), right):
  7583. l = self.type_check_exp(left, env)
  7584. check_type_equal(l, int, left)
  7585. r = self.type_check_exp(right, env)
  7586. check_type_equal(r, int, right)
  7587. return int
  7588. case UnaryOp(USub(), v):
  7589. t = self.type_check_exp(v, env)
  7590. check_type_equal(t, int, v)
  7591. return int
  7592. case Name(id):
  7593. return env[id]
  7594. case Constant(value) if isinstance(value, int):
  7595. return int
  7596. case Call(Name('input_int'), []):
  7597. return int
  7598. def type_check_stmts(self, ss, env):
  7599. if len(ss) == 0:
  7600. return
  7601. match ss[0]:
  7602. case Assign([lhs], value):
  7603. t = self.type_check_exp(value, env)
  7604. if lhs.id in env:
  7605. check_type_equal(env[lhs.id], t, value)
  7606. else:
  7607. env[lhs.id] = t
  7608. return self.type_check_stmts(ss[1:], env)
  7609. case Expr(Call(Name('print'), [arg])):
  7610. t = self.type_check_exp(arg, env)
  7611. check_type_equal(t, int, arg)
  7612. return self.type_check_stmts(ss[1:], env)
  7613. case Expr(value):
  7614. self.type_check_exp(value, env)
  7615. return self.type_check_stmts(ss[1:], env)
  7616. def type_check_P(self, p):
  7617. match p:
  7618. case Module(body):
  7619. self.type_check_stmts(body, {})
  7620. \end{lstlisting}
  7621. \fi}
  7622. \end{tcolorbox}
  7623. \caption{Type checker for the \LangVar{} language.}
  7624. \label{fig:type-check-Lvar}
  7625. \end{figure}
  7626. \begin{figure}[tbp]
  7627. \begin{tcolorbox}[colback=white]
  7628. {\if\edition\racketEd
  7629. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7630. (define type-check-Lif-class
  7631. (class type-check-Lvar-class
  7632. (super-new)
  7633. (inherit check-type-equal?)
  7634. (define/override (operator-types)
  7635. (append '((and . ((Boolean Boolean) . Boolean))
  7636. (or . ((Boolean Boolean) . Boolean))
  7637. (< . ((Integer Integer) . Boolean))
  7638. (<= . ((Integer Integer) . Boolean))
  7639. (> . ((Integer Integer) . Boolean))
  7640. (>= . ((Integer Integer) . Boolean))
  7641. (not . ((Boolean) . Boolean)))
  7642. (super operator-types)))
  7643. (define/override (type-check-exp env)
  7644. (lambda (e)
  7645. (match e
  7646. [(Bool b) (values (Bool b) 'Boolean)]
  7647. [(Prim 'eq? (list e1 e2))
  7648. (define-values (e1^ T1) ((type-check-exp env) e1))
  7649. (define-values (e2^ T2) ((type-check-exp env) e2))
  7650. (check-type-equal? T1 T2 e)
  7651. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7652. [(If cnd thn els)
  7653. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7654. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7655. (define-values (els^ Te) ((type-check-exp env) els))
  7656. (check-type-equal? Tc 'Boolean e)
  7657. (check-type-equal? Tt Te e)
  7658. (values (If cnd^ thn^ els^) Te)]
  7659. [else ((super type-check-exp env) e)])))
  7660. ))
  7661. (define (type-check-Lif p)
  7662. (send (new type-check-Lif-class) type-check-program p))
  7663. \end{lstlisting}
  7664. \fi}
  7665. {\if\edition\pythonEd\pythonColor
  7666. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7667. class TypeCheckLif(TypeCheckLvar):
  7668. def type_check_exp(self, e, env):
  7669. match e:
  7670. case Constant(value) if isinstance(value, bool):
  7671. return bool
  7672. case BinOp(left, Sub(), right):
  7673. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7674. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7675. return int
  7676. case UnaryOp(Not(), v):
  7677. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7678. return bool
  7679. case BoolOp(op, values):
  7680. left = values[0] ; right = values[1]
  7681. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7682. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7683. return bool
  7684. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7685. or isinstance(cmp, NotEq):
  7686. l = self.type_check_exp(left, env)
  7687. r = self.type_check_exp(right, env)
  7688. check_type_equal(l, r, e)
  7689. return bool
  7690. case Compare(left, [cmp], [right]):
  7691. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7692. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7693. return bool
  7694. case IfExp(test, body, orelse):
  7695. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7696. b = self.type_check_exp(body, env)
  7697. o = self.type_check_exp(orelse, env)
  7698. check_type_equal(b, o, e)
  7699. return b
  7700. case _:
  7701. return super().type_check_exp(e, env)
  7702. def type_check_stmts(self, ss, env):
  7703. if len(ss) == 0:
  7704. return
  7705. match ss[0]:
  7706. case If(test, body, orelse):
  7707. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7708. b = self.type_check_stmts(body, env)
  7709. o = self.type_check_stmts(orelse, env)
  7710. check_type_equal(b, o, ss[0])
  7711. return self.type_check_stmts(ss[1:], env)
  7712. case _:
  7713. return super().type_check_stmts(ss, env)
  7714. \end{lstlisting}
  7715. \fi}
  7716. \end{tcolorbox}
  7717. \caption{Type checker for the \LangIf{} language.}
  7718. \label{fig:type-check-Lif}
  7719. \end{figure}
  7720. The definition of the type checker for \LangIf{} is shown in
  7721. figure~\ref{fig:type-check-Lif}.
  7722. %
  7723. The type of a Boolean constant is \BOOLTY{}.
  7724. %
  7725. \racket{The \code{operator-types} function adds dictionary entries for
  7726. the new operators.}
  7727. %
  7728. \python{The logical \code{not} operator requires its argument to be a
  7729. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7730. and logical \code{or} operators.}
  7731. %
  7732. The equality operator requires the two arguments to have the same type,
  7733. and therefore we handle it separately from the other operators.
  7734. %
  7735. \python{The other comparisons (less-than, etc.) require their
  7736. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7737. %
  7738. The condition of an \code{if} must
  7739. be of \BOOLTY{} type, and the two branches must have the same type.
  7740. \begin{exercise}\normalfont\normalsize
  7741. Create ten new test programs in \LangIf{}. Half the programs should
  7742. have a type error. For those programs, create an empty file with the
  7743. same base name and with file extension \code{.tyerr}. For example, if
  7744. the test
  7745. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7746. is expected to error, then create
  7747. an empty file named \code{cond\_test\_14.tyerr}.
  7748. %
  7749. \racket{This indicates to \code{interp-tests} and
  7750. \code{compiler-tests} that a type error is expected. }
  7751. %
  7752. The other half of the test programs should not have type errors.
  7753. %
  7754. \racket{In the \code{run-tests.rkt} script, change the second argument
  7755. of \code{interp-tests} and \code{compiler-tests} to
  7756. \code{type-check-Lif}, which causes the type checker to run prior to
  7757. the compiler passes. Temporarily change the \code{passes} to an
  7758. empty list and run the script, thereby checking that the new test
  7759. programs either type check or do not, as intended.}
  7760. %
  7761. Run the test script to check that these test programs type check as
  7762. expected.
  7763. \end{exercise}
  7764. \clearpage
  7765. \section{The \LangCIf{} Intermediate Language}
  7766. \label{sec:Cif}
  7767. {\if\edition\racketEd
  7768. %
  7769. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7770. comparison operators to the \Exp{} nonterminal and the literals
  7771. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7772. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7773. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7774. comparison operation and the branches are \code{goto} statements,
  7775. making it straightforward to compile \code{if} statements to x86. The
  7776. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7777. expressions. A \code{goto} statement transfers control to the $\Tail$
  7778. expression corresponding to its label.
  7779. %
  7780. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7781. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7782. defines its abstract syntax.
  7783. %
  7784. \fi}
  7785. %
  7786. {\if\edition\pythonEd\pythonColor
  7787. %
  7788. The output of \key{explicate\_control} is a language similar to the
  7789. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7790. \code{goto} statements, so we name it \LangCIf{}.
  7791. %
  7792. The \LangCIf{} language supports the same operators as \LangIf{} but
  7793. the arguments of operators are restricted to atomic expressions. The
  7794. \LangCIf{} language does not include \code{if} expressions, but it does
  7795. include a restricted form of \code{if} statement. The condition must be
  7796. a comparison, and the two branches may contain only \code{goto}
  7797. statements. These restrictions make it easier to translate \code{if}
  7798. statements to x86. The \LangCIf{} language also adds a \code{return}
  7799. statement to finish the program with a specified value.
  7800. %
  7801. The \key{CProgram} construct contains a dictionary mapping labels to
  7802. lists of statements that end with a \emph{tail} statement, which is
  7803. either a \code{return} statement, a \code{goto}, or an
  7804. \code{if} statement.
  7805. %
  7806. A \code{goto} transfers control to the sequence of statements
  7807. associated with its label.
  7808. %
  7809. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7810. and figure~\ref{fig:c1-syntax} shows its
  7811. abstract syntax.
  7812. %
  7813. \fi}
  7814. %
  7815. \newcommand{\CifGrammarRacket}{
  7816. \begin{array}{lcl}
  7817. \Atm &::=& \itm{bool} \\
  7818. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7819. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7820. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7821. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7822. \end{array}
  7823. }
  7824. \newcommand{\CifASTRacket}{
  7825. \begin{array}{lcl}
  7826. \Atm &::=& \BOOL{\itm{bool}} \\
  7827. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7828. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7829. \Tail &::= & \GOTO{\itm{label}} \\
  7830. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7831. \end{array}
  7832. }
  7833. \newcommand{\CifGrammarPython}{
  7834. \begin{array}{lcl}
  7835. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7836. \Exp &::= & \Atm \MID \CREAD{}
  7837. \MID \CUNIOP{\key{-}}{\Atm}
  7838. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7839. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7840. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7841. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7842. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7843. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7844. \end{array}
  7845. }
  7846. \newcommand{\CifASTPython}{
  7847. \begin{array}{lcl}
  7848. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7849. \Exp &::= & \Atm \MID \READ{}
  7850. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7851. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7852. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7853. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7854. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7855. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7856. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7857. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7858. \end{array}
  7859. }
  7860. \begin{figure}[tbp]
  7861. \begin{tcolorbox}[colback=white]
  7862. \small
  7863. {\if\edition\racketEd
  7864. \[
  7865. \begin{array}{l}
  7866. \gray{\CvarGrammarRacket} \\ \hline
  7867. \CifGrammarRacket \\
  7868. \begin{array}{lcl}
  7869. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7870. \end{array}
  7871. \end{array}
  7872. \]
  7873. \fi}
  7874. {\if\edition\pythonEd\pythonColor
  7875. \[
  7876. \begin{array}{l}
  7877. \CifGrammarPython \\
  7878. \begin{array}{lcl}
  7879. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7880. \end{array}
  7881. \end{array}
  7882. \]
  7883. \fi}
  7884. \end{tcolorbox}
  7885. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7886. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7887. \label{fig:c1-concrete-syntax}
  7888. \end{figure}
  7889. \begin{figure}[tp]
  7890. \begin{tcolorbox}[colback=white]
  7891. \small
  7892. {\if\edition\racketEd
  7893. \[
  7894. \begin{array}{l}
  7895. \gray{\CvarASTRacket} \\ \hline
  7896. \CifASTRacket \\
  7897. \begin{array}{lcl}
  7898. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7899. \end{array}
  7900. \end{array}
  7901. \]
  7902. \fi}
  7903. {\if\edition\pythonEd\pythonColor
  7904. \[
  7905. \begin{array}{l}
  7906. \CifASTPython \\
  7907. \begin{array}{lcl}
  7908. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7909. \end{array}
  7910. \end{array}
  7911. \]
  7912. \fi}
  7913. \end{tcolorbox}
  7914. \racket{
  7915. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7916. }
  7917. \index{subject}{Goto@\texttt{Goto}}
  7918. \index{subject}{Return@\texttt{Return}}
  7919. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7920. (figure~\ref{fig:c0-syntax})}.}
  7921. \label{fig:c1-syntax}
  7922. \end{figure}
  7923. \section{The \LangXIf{} Language}
  7924. \label{sec:x86-if}
  7925. \index{subject}{x86}
  7926. To implement Booleans, the new logical operations, the
  7927. comparison operations, and the \key{if} expression\python{ and
  7928. statement}, we delve further into the x86
  7929. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7930. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7931. subset of x86, which includes instructions for logical operations,
  7932. comparisons, and \racket{conditional} jumps.
  7933. %
  7934. \python{The abstract syntax for an \LangXIf{} program contains a
  7935. dictionary mapping labels to sequences of instructions, each of
  7936. which we refer to as a \emph{basic block}\index{subject}{basic
  7937. block}.}
  7938. As x86 does not provide direct support for Booleans, we take the usual
  7939. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7940. \code{False} as $0$.
  7941. Furthermore, x86 does not provide an instruction that directly
  7942. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7943. However, the \code{xorq} instruction can be used to encode \code{not}.
  7944. The \key{xorq} instruction takes two arguments, performs a pairwise
  7945. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7946. and writes the results into its second argument. Recall the following
  7947. truth table for exclusive-or:
  7948. \begin{center}
  7949. \begin{tabular}{l|cc}
  7950. & 0 & 1 \\ \hline
  7951. 0 & 0 & 1 \\
  7952. 1 & 1 & 0
  7953. \end{tabular}
  7954. \end{center}
  7955. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7956. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7957. for the bit $1$, the result is the opposite of the second bit. Thus,
  7958. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7959. the first argument, as follows, where $\Arg$ is the translation of
  7960. $\Atm$ to x86:
  7961. \[
  7962. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7963. \qquad\Rightarrow\qquad
  7964. \begin{array}{l}
  7965. \key{movq}~ \Arg\key{,} \Var\\
  7966. \key{xorq}~ \key{\$1,} \Var
  7967. \end{array}
  7968. \]
  7969. \newcommand{\GrammarXIf}{
  7970. \begin{array}{lcl}
  7971. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7972. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7973. \Arg &::=& \key{\%}\itm{bytereg}\\
  7974. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7975. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7976. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7977. \MID \key{set}cc~\Arg
  7978. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7979. &\MID& \key{j}cc~\itm{label} \\
  7980. \end{array}
  7981. }
  7982. \begin{figure}[tp]
  7983. \begin{tcolorbox}[colback=white]
  7984. \[
  7985. \begin{array}{l}
  7986. \gray{\GrammarXInt} \\ \hline
  7987. \GrammarXIf \\
  7988. \begin{array}{lcl}
  7989. \LangXIfM{} &::= & \key{.globl main} \\
  7990. & & \key{main:} \; \Instr\ldots
  7991. \end{array}
  7992. \end{array}
  7993. \]
  7994. \end{tcolorbox}
  7995. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7996. \label{fig:x86-1-concrete}
  7997. \end{figure}
  7998. \newcommand{\ASTXIfRacket}{
  7999. \begin{array}{lcl}
  8000. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8001. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8002. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8003. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8004. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8005. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8006. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8007. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8008. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8009. \end{array}
  8010. }
  8011. \newcommand{\ASTXIfPython}{
  8012. \begin{array}{lcl}
  8013. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8014. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8015. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8016. \MID \BYTEREG{\itm{bytereg}} \\
  8017. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8018. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8019. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8020. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8021. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8022. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8023. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8024. \end{array}
  8025. }
  8026. \begin{figure}[tp]
  8027. \begin{tcolorbox}[colback=white]
  8028. \small
  8029. {\if\edition\racketEd
  8030. \[\arraycolsep=3pt
  8031. \begin{array}{l}
  8032. \gray{\ASTXIntRacket} \\ \hline
  8033. \ASTXIfRacket \\
  8034. \begin{array}{lcl}
  8035. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8036. \end{array}
  8037. \end{array}
  8038. \]
  8039. \fi}
  8040. %
  8041. {\if\edition\pythonEd\pythonColor
  8042. \[
  8043. \begin{array}{l}
  8044. \gray{\ASTXIntPython} \\ \hline
  8045. \ASTXIfPython \\
  8046. \begin{array}{lcl}
  8047. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8048. \end{array}
  8049. \end{array}
  8050. \]
  8051. \fi}
  8052. \end{tcolorbox}
  8053. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8054. \label{fig:x86-1}
  8055. \end{figure}
  8056. Next we consider the x86 instructions that are relevant for compiling
  8057. the comparison operations. The \key{cmpq} instruction compares its two
  8058. arguments to determine whether one argument is less than, equal to, or
  8059. greater than the other argument. The \key{cmpq} instruction is unusual
  8060. regarding the order of its arguments and where the result is
  8061. placed. The argument order is backward: if you want to test whether
  8062. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8063. \key{cmpq} is placed in the special EFLAGS register. This register
  8064. cannot be accessed directly, but it can be queried by a number of
  8065. instructions, including the \key{set} instruction. The instruction
  8066. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8067. depending on whether the contents of the EFLAGS register matches the
  8068. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8069. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8070. The \key{set} instruction has a quirk in that its destination argument
  8071. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8072. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8073. register. Thankfully, the \key{movzbq} instruction can be used to
  8074. move from a single-byte register to a normal 64-bit register. The
  8075. abstract syntax for the \code{set} instruction differs from the
  8076. concrete syntax in that it separates the instruction name from the
  8077. condition code.
  8078. \python{The x86 instructions for jumping are relevant to the
  8079. compilation of \key{if} expressions.}
  8080. %
  8081. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8082. counter to the address of the instruction after the specified
  8083. label.}
  8084. %
  8085. \racket{The x86 instruction for conditional jump is relevant to the
  8086. compilation of \key{if} expressions.}
  8087. %
  8088. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8089. counter to point to the instruction after \itm{label}, depending on
  8090. whether the result in the EFLAGS register matches the condition code
  8091. \itm{cc}; otherwise, the jump instruction falls through to the next
  8092. instruction. Like the abstract syntax for \code{set}, the abstract
  8093. syntax for conditional jump separates the instruction name from the
  8094. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8095. corresponds to \code{jle foo}. Because the conditional jump instruction
  8096. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8097. a \key{cmpq} instruction to set the EFLAGS register.
  8098. \section{Shrink the \LangIf{} Language}
  8099. \label{sec:shrink-Lif}
  8100. The \code{shrink} pass translates some of the language features into
  8101. other features, thereby reducing the kinds of expressions in the
  8102. language. For example, the short-circuiting nature of the \code{and}
  8103. and \code{or} logical operators can be expressed using \code{if} as
  8104. follows.
  8105. \begin{align*}
  8106. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8107. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8108. \end{align*}
  8109. By performing these translations in the front end of the compiler,
  8110. subsequent passes of the compiler can be shorter.
  8111. On the other hand, translations sometimes reduce the efficiency of the
  8112. generated code by increasing the number of instructions. For example,
  8113. expressing subtraction in terms of addition and negation
  8114. \[
  8115. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8116. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8117. \]
  8118. produces code with two x86 instructions (\code{negq} and \code{addq})
  8119. instead of just one (\code{subq}). Thus, we do not recommend
  8120. translating subtraction into addition and negation.
  8121. \begin{exercise}\normalfont\normalsize
  8122. %
  8123. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8124. the language by translating them to \code{if} expressions in \LangIf{}.
  8125. %
  8126. Create four test programs that involve these operators.
  8127. %
  8128. {\if\edition\racketEd
  8129. In the \code{run-tests.rkt} script, add the following entry for
  8130. \code{shrink} to the list of passes (it should be the only pass at
  8131. this point).
  8132. \begin{lstlisting}
  8133. (list "shrink" shrink interp_Lif type-check-Lif)
  8134. \end{lstlisting}
  8135. This instructs \code{interp-tests} to run the interpreter
  8136. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8137. output of \code{shrink}.
  8138. \fi}
  8139. %
  8140. Run the script to test your compiler on all the test programs.
  8141. \end{exercise}
  8142. {\if\edition\racketEd
  8143. \section{Uniquify Variables}
  8144. \label{sec:uniquify-Lif}
  8145. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8146. \code{if} expressions.
  8147. \begin{exercise}\normalfont\normalsize
  8148. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8149. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8150. \begin{lstlisting}
  8151. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8152. \end{lstlisting}
  8153. Run the script to test your compiler.
  8154. \end{exercise}
  8155. \fi}
  8156. \section{Remove Complex Operands}
  8157. \label{sec:remove-complex-opera-Lif}
  8158. The output language of \code{remove\_complex\_operands} is
  8159. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8160. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8161. but the \code{if} expression is not. All three subexpressions of an
  8162. \code{if} are allowed to be complex expressions, but the operands of
  8163. the \code{not} operator and comparison operators must be atomic.
  8164. %
  8165. \python{We add a new language form, the \code{Begin} expression, to aid
  8166. in the translation of \code{if} expressions. When we recursively
  8167. process the two branches of the \code{if}, we generate temporary
  8168. variables and their initializing expressions. However, these
  8169. expressions may contain side effects and should be executed only
  8170. when the condition of the \code{if} is true (for the ``then''
  8171. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8172. a way to initialize the temporary variables within the two branches
  8173. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8174. form executes the statements $ss$ and then returns the result of
  8175. expression $e$.}
  8176. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8177. the new features in \LangIf{}. In recursively processing
  8178. subexpressions, recall that you should invoke \code{rco\_atom} when
  8179. the output needs to be an \Atm{} (as specified in the grammar for
  8180. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8181. \Exp{}. Regarding \code{if}, it is particularly important
  8182. \emph{not} to replace its condition with a temporary variable, because
  8183. that would interfere with the generation of high-quality output in the
  8184. upcoming \code{explicate\_control} pass.
  8185. \newcommand{\LifMonadASTRacket}{
  8186. \begin{array}{rcl}
  8187. \Atm &::=& \BOOL{\itm{bool}}\\
  8188. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8189. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8190. \MID \IF{\Exp}{\Exp}{\Exp}
  8191. \end{array}
  8192. }
  8193. \newcommand{\LifMonadASTPython}{
  8194. \begin{array}{rcl}
  8195. \Atm &::=& \BOOL{\itm{bool}}\\
  8196. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8197. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8198. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8199. \end{array}
  8200. }
  8201. \begin{figure}[tp]
  8202. \centering
  8203. \begin{tcolorbox}[colback=white]
  8204. {\if\edition\racketEd
  8205. \[
  8206. \begin{array}{l}
  8207. \gray{\LvarMonadASTRacket} \\ \hline
  8208. \LifMonadASTRacket \\
  8209. \begin{array}{rcl}
  8210. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8211. \end{array}
  8212. \end{array}
  8213. \]
  8214. \fi}
  8215. {\if\edition\pythonEd\pythonColor
  8216. \[
  8217. \begin{array}{l}
  8218. \gray{\LvarMonadASTPython} \\ \hline
  8219. \LifMonadASTPython \\
  8220. \begin{array}{rcl}
  8221. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8222. \end{array}
  8223. \end{array}
  8224. \]
  8225. \fi}
  8226. \end{tcolorbox}
  8227. \python{\index{subject}{Begin@\texttt{Begin}}}
  8228. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8229. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8230. \label{fig:Lif-anf-syntax}
  8231. \end{figure}
  8232. \begin{exercise}\normalfont\normalsize
  8233. %
  8234. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8235. and \code{rco\_exp} functions.
  8236. %
  8237. Create three new \LangIf{} programs that exercise the interesting
  8238. code in this pass.
  8239. %
  8240. {\if\edition\racketEd
  8241. In the \code{run-tests.rkt} script, add the following entry to the
  8242. list of \code{passes} and then run the script to test your compiler.
  8243. \begin{lstlisting}
  8244. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8245. \end{lstlisting}
  8246. \fi}
  8247. \end{exercise}
  8248. \section{Explicate Control}
  8249. \label{sec:explicate-control-Lif}
  8250. \racket{Recall that the purpose of \code{explicate\_control} is to
  8251. make the order of evaluation explicit in the syntax of the program.
  8252. With the addition of \key{if}, this becomes more interesting.}
  8253. %
  8254. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8255. %
  8256. The main challenge to overcome is that the condition of an \key{if}
  8257. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8258. condition must be a comparison.
  8259. As a motivating example, consider the following program that has an
  8260. \key{if} expression nested in the condition of another \key{if}:%
  8261. \python{\footnote{Programmers rarely write nested \code{if}
  8262. expressions, but they do write nested expressions involving
  8263. logical \code{and}, which, as we have seen, translates to
  8264. \code{if}.}}
  8265. % cond_test_41.rkt, if_lt_eq.py
  8266. \begin{center}
  8267. \begin{minipage}{0.96\textwidth}
  8268. {\if\edition\racketEd
  8269. \begin{lstlisting}
  8270. (let ([x (read)])
  8271. (let ([y (read)])
  8272. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8273. (+ y 2)
  8274. (+ y 10))))
  8275. \end{lstlisting}
  8276. \fi}
  8277. {\if\edition\pythonEd\pythonColor
  8278. \begin{lstlisting}
  8279. x = input_int()
  8280. y = input_int()
  8281. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8282. \end{lstlisting}
  8283. \fi}
  8284. \end{minipage}
  8285. \end{center}
  8286. %
  8287. The naive way to compile \key{if} and the comparison operations would
  8288. be to handle each of them in isolation, regardless of their context.
  8289. Each comparison would be translated into a \key{cmpq} instruction
  8290. followed by several instructions to move the result from the EFLAGS
  8291. register into a general purpose register or stack location. Each
  8292. \key{if} would be translated into a \key{cmpq} instruction followed by
  8293. a conditional jump. The generated code for the inner \key{if} in this
  8294. example would be as follows:
  8295. \begin{center}
  8296. \begin{minipage}{0.96\textwidth}
  8297. \begin{lstlisting}
  8298. cmpq $1, x
  8299. setl %al
  8300. movzbq %al, tmp
  8301. cmpq $1, tmp
  8302. je then_branch_1
  8303. jmp else_branch_1
  8304. \end{lstlisting}
  8305. \end{minipage}
  8306. \end{center}
  8307. Notice that the three instructions starting with \code{setl} are
  8308. redundant; the conditional jump could come immediately after the first
  8309. \code{cmpq}.
  8310. Our goal is to compile \key{if} expressions so that the relevant
  8311. comparison instruction appears directly before the conditional jump.
  8312. For example, we want to generate the following code for the inner
  8313. \code{if}:
  8314. \begin{center}
  8315. \begin{minipage}{0.96\textwidth}
  8316. \begin{lstlisting}
  8317. cmpq $1, x
  8318. jl then_branch_1
  8319. jmp else_branch_1
  8320. \end{lstlisting}
  8321. \end{minipage}
  8322. \end{center}
  8323. One way to achieve this goal is to reorganize the code at the level of
  8324. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8325. the following code:
  8326. \begin{center}
  8327. \begin{minipage}{0.96\textwidth}
  8328. {\if\edition\racketEd
  8329. \begin{lstlisting}
  8330. (let ([x (read)])
  8331. (let ([y (read)])
  8332. (if (< x 1)
  8333. (if (eq? x 0)
  8334. (+ y 2)
  8335. (+ y 10))
  8336. (if (eq? x 2)
  8337. (+ y 2)
  8338. (+ y 10)))))
  8339. \end{lstlisting}
  8340. \fi}
  8341. {\if\edition\pythonEd\pythonColor
  8342. \begin{lstlisting}
  8343. x = input_int()
  8344. y = input_int()
  8345. print(((y + 2) if x == 0 else (y + 10)) \
  8346. if (x < 1) \
  8347. else ((y + 2) if (x == 2) else (y + 10)))
  8348. \end{lstlisting}
  8349. \fi}
  8350. \end{minipage}
  8351. \end{center}
  8352. Unfortunately, this approach duplicates the two branches from the
  8353. outer \code{if}, and a compiler must never duplicate code! After all,
  8354. the two branches could be very large expressions.
  8355. How can we apply this transformation without duplicating code? In
  8356. other words, how can two different parts of a program refer to one
  8357. piece of code?
  8358. %
  8359. The answer is that we must move away from abstract syntax \emph{trees}
  8360. and instead use \emph{graphs}.
  8361. %
  8362. At the level of x86 assembly, this is straightforward because we can
  8363. label the code for each branch and insert jumps in all the places that
  8364. need to execute the branch. In this way, jump instructions are edges
  8365. in the graph and the basic blocks are the nodes.
  8366. %
  8367. Likewise, our language \LangCIf{} provides the ability to label a
  8368. sequence of statements and to jump to a label via \code{goto}.
  8369. As a preview of what \code{explicate\_control} will do,
  8370. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8371. \code{explicate\_control} on this example. Note how the condition of
  8372. every \code{if} is a comparison operation and that we have not
  8373. duplicated any code but instead have used labels and \code{goto} to
  8374. enable sharing of code.
  8375. \begin{figure}[tbp]
  8376. \begin{tcolorbox}[colback=white]
  8377. {\if\edition\racketEd
  8378. \begin{tabular}{lll}
  8379. \begin{minipage}{0.4\textwidth}
  8380. % cond_test_41.rkt
  8381. \begin{lstlisting}
  8382. (let ([x (read)])
  8383. (let ([y (read)])
  8384. (if (if (< x 1)
  8385. (eq? x 0)
  8386. (eq? x 2))
  8387. (+ y 2)
  8388. (+ y 10))))
  8389. \end{lstlisting}
  8390. \end{minipage}
  8391. &
  8392. $\Rightarrow$
  8393. &
  8394. \begin{minipage}{0.55\textwidth}
  8395. \begin{lstlisting}
  8396. start:
  8397. x = (read);
  8398. y = (read);
  8399. if (< x 1)
  8400. goto block_4;
  8401. else
  8402. goto block_5;
  8403. block_4:
  8404. if (eq? x 0)
  8405. goto block_2;
  8406. else
  8407. goto block_3;
  8408. block_5:
  8409. if (eq? x 2)
  8410. goto block_2;
  8411. else
  8412. goto block_3;
  8413. block_2:
  8414. return (+ y 2);
  8415. block_3:
  8416. return (+ y 10);
  8417. \end{lstlisting}
  8418. \end{minipage}
  8419. \end{tabular}
  8420. \fi}
  8421. {\if\edition\pythonEd\pythonColor
  8422. \begin{tabular}{lll}
  8423. \begin{minipage}{0.4\textwidth}
  8424. % cond_test_41.rkt
  8425. \begin{lstlisting}
  8426. x = input_int()
  8427. y = input_int()
  8428. print(y + 2 \
  8429. if (x == 0 \
  8430. if x < 1 \
  8431. else x == 2) \
  8432. else y + 10)
  8433. \end{lstlisting}
  8434. \end{minipage}
  8435. &
  8436. $\Rightarrow$
  8437. &
  8438. \begin{minipage}{0.55\textwidth}
  8439. \begin{lstlisting}
  8440. start:
  8441. x = input_int()
  8442. y = input_int()
  8443. if x < 1:
  8444. goto block_8
  8445. else:
  8446. goto block_9
  8447. block_8:
  8448. if x == 0:
  8449. goto block_4
  8450. else:
  8451. goto block_5
  8452. block_9:
  8453. if x == 2:
  8454. goto block_6
  8455. else:
  8456. goto block_7
  8457. block_4:
  8458. goto block_2
  8459. block_5:
  8460. goto block_3
  8461. block_6:
  8462. goto block_2
  8463. block_7:
  8464. goto block_3
  8465. block_2:
  8466. tmp_0 = y + 2
  8467. goto block_1
  8468. block_3:
  8469. tmp_0 = y + 10
  8470. goto block_1
  8471. block_1:
  8472. print(tmp_0)
  8473. return 0
  8474. \end{lstlisting}
  8475. \end{minipage}
  8476. \end{tabular}
  8477. \fi}
  8478. \end{tcolorbox}
  8479. \caption{Translation from \LangIf{} to \LangCIf{}
  8480. via the \code{explicate\_control}.}
  8481. \label{fig:explicate-control-s1-38}
  8482. \end{figure}
  8483. {\if\edition\racketEd
  8484. %
  8485. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8486. \code{explicate\_control} for \LangVar{} using two recursive
  8487. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8488. former function translates expressions in tail position, whereas the
  8489. latter function translates expressions on the right-hand side of a
  8490. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8491. have a new kind of position to deal with: the predicate position of
  8492. the \key{if}. We need another function, \code{explicate\_pred}, that
  8493. decides how to compile an \key{if} by analyzing its condition. So,
  8494. \code{explicate\_pred} takes an \LangIf{} expression and two
  8495. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8496. and outputs a tail. In the following paragraphs we discuss specific
  8497. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8498. \code{explicate\_pred} functions.
  8499. %
  8500. \fi}
  8501. %
  8502. {\if\edition\pythonEd\pythonColor
  8503. %
  8504. We recommend implementing \code{explicate\_control} using the
  8505. following four auxiliary functions.
  8506. \begin{description}
  8507. \item[\code{explicate\_effect}] generates code for expressions as
  8508. statements, so their result is ignored and only their side effects
  8509. matter.
  8510. \item[\code{explicate\_assign}] generates code for expressions
  8511. on the right-hand side of an assignment.
  8512. \item[\code{explicate\_pred}] generates code for an \code{if}
  8513. expression or statement by analyzing the condition expression.
  8514. \item[\code{explicate\_stmt}] generates code for statements.
  8515. \end{description}
  8516. These four functions should build the dictionary of basic blocks. The
  8517. following auxiliary function can be used to create a new basic block
  8518. from a list of statements. It returns a \code{goto} statement that
  8519. jumps to the new basic block.
  8520. \begin{center}
  8521. \begin{minipage}{\textwidth}
  8522. \begin{lstlisting}
  8523. def create_block(stmts, basic_blocks):
  8524. label = label_name(generate_name('block'))
  8525. basic_blocks[label] = stmts
  8526. return [Goto(label)]
  8527. \end{lstlisting}
  8528. \end{minipage}
  8529. \end{center}
  8530. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8531. \code{explicate\_control} pass.
  8532. The \code{explicate\_effect} function has three parameters: (1) the
  8533. expression to be compiled; (2) the already-compiled code for this
  8534. expression's \emph{continuation}, that is, the list of statements that
  8535. should execute after this expression; and (3) the dictionary of
  8536. generated basic blocks. The \code{explicate\_effect} function returns
  8537. a list of \LangCIf{} statements and it may add to the dictionary of
  8538. basic blocks.
  8539. %
  8540. Let's consider a few of the cases for the expression to be compiled.
  8541. If the expression to be compiled is a constant, then it can be
  8542. discarded because it has no side effects. If it's a \CREAD{}, then it
  8543. has a side effect and should be preserved. So the expression should be
  8544. translated into a statement using the \code{Expr} AST class. If the
  8545. expression to be compiled is an \code{if} expression, we translate the
  8546. two branches using \code{explicate\_effect} and then translate the
  8547. condition expression using \code{explicate\_pred}, which generates
  8548. code for the entire \code{if}.
  8549. The \code{explicate\_assign} function has four parameters: (1) the
  8550. right-hand side of the assignment, (2) the left-hand side of the
  8551. assignment (the variable), (3) the continuation, and (4) the dictionary
  8552. of basic blocks. The \code{explicate\_assign} function returns a list
  8553. of \LangCIf{} statements, and it may add to the dictionary of basic
  8554. blocks.
  8555. When the right-hand side is an \code{if} expression, there is some
  8556. work to do. In particular, the two branches should be translated using
  8557. \code{explicate\_assign} and the condition expression should be
  8558. translated using \code{explicate\_pred}. Otherwise we can simply
  8559. generate an assignment statement, with the given left and right-hand
  8560. sides, concatenated with its continuation.
  8561. \begin{figure}[tbp]
  8562. \begin{tcolorbox}[colback=white]
  8563. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8564. def explicate_effect(e, cont, basic_blocks):
  8565. match e:
  8566. case IfExp(test, body, orelse):
  8567. ...
  8568. case Call(func, args):
  8569. ...
  8570. case Begin(body, result):
  8571. ...
  8572. case _:
  8573. ...
  8574. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8575. match rhs:
  8576. case IfExp(test, body, orelse):
  8577. ...
  8578. case Begin(body, result):
  8579. ...
  8580. case _:
  8581. return [Assign([lhs], rhs)] + cont
  8582. def explicate_pred(cnd, thn, els, basic_blocks):
  8583. match cnd:
  8584. case Compare(left, [op], [right]):
  8585. goto_thn = create_block(thn, basic_blocks)
  8586. goto_els = create_block(els, basic_blocks)
  8587. return [If(cnd, goto_thn, goto_els)]
  8588. case Constant(True):
  8589. return thn;
  8590. case Constant(False):
  8591. return els;
  8592. case UnaryOp(Not(), operand):
  8593. ...
  8594. case IfExp(test, body, orelse):
  8595. ...
  8596. case Begin(body, result):
  8597. ...
  8598. case _:
  8599. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8600. create_block(els, basic_blocks),
  8601. create_block(thn, basic_blocks))]
  8602. def explicate_stmt(s, cont, basic_blocks):
  8603. match s:
  8604. case Assign([lhs], rhs):
  8605. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8606. case Expr(value):
  8607. return explicate_effect(value, cont, basic_blocks)
  8608. case If(test, body, orelse):
  8609. ...
  8610. def explicate_control(p):
  8611. match p:
  8612. case Module(body):
  8613. new_body = [Return(Constant(0))]
  8614. basic_blocks = {}
  8615. for s in reversed(body):
  8616. new_body = explicate_stmt(s, new_body, basic_blocks)
  8617. basic_blocks[label_name('start')] = new_body
  8618. return CProgram(basic_blocks)
  8619. \end{lstlisting}
  8620. \end{tcolorbox}
  8621. \caption{Skeleton for the \code{explicate\_control} pass.}
  8622. \label{fig:explicate-control-Lif}
  8623. \end{figure}
  8624. \fi}
  8625. {\if\edition\racketEd
  8626. \subsection{Explicate Tail and Assign}
  8627. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8628. additional cases for Boolean constants and \key{if}. The cases for
  8629. \code{if} should recursively compile the two branches using either
  8630. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8631. cases should then invoke \code{explicate\_pred} on the condition
  8632. expression, passing in the generated code for the two branches. For
  8633. example, consider the following program with an \code{if} in tail
  8634. position.
  8635. % cond_test_6.rkt
  8636. \begin{lstlisting}
  8637. (let ([x (read)])
  8638. (if (eq? x 0) 42 777))
  8639. \end{lstlisting}
  8640. The two branches are recursively compiled to return statements. We
  8641. then delegate to \code{explicate\_pred}, passing the condition
  8642. \code{(eq? x 0)} and the two return statements. We return to this
  8643. example shortly when we discuss \code{explicate\_pred}.
  8644. Next let us consider a program with an \code{if} on the right-hand
  8645. side of a \code{let}.
  8646. \begin{lstlisting}
  8647. (let ([y (read)])
  8648. (let ([x (if (eq? y 0) 40 777)])
  8649. (+ x 2)))
  8650. \end{lstlisting}
  8651. Note that the body of the inner \code{let} will have already been
  8652. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8653. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8654. to recursively process both branches of the \code{if}, and we do not
  8655. want to duplicate code, so we generate the following block using an
  8656. auxiliary function named \code{create\_block}, discussed in the next
  8657. section.
  8658. \begin{lstlisting}
  8659. block_6:
  8660. return (+ x 2)
  8661. \end{lstlisting}
  8662. We then use \code{goto block\_6;} as the \code{cont} argument for
  8663. compiling the branches. So the two branches compile to
  8664. \begin{center}
  8665. \begin{minipage}{0.2\textwidth}
  8666. \begin{lstlisting}
  8667. x = 40;
  8668. goto block_6;
  8669. \end{lstlisting}
  8670. \end{minipage}
  8671. \hspace{0.5in} and \hspace{0.5in}
  8672. \begin{minipage}{0.2\textwidth}
  8673. \begin{lstlisting}
  8674. x = 777;
  8675. goto block_6;
  8676. \end{lstlisting}
  8677. \end{minipage}
  8678. \end{center}
  8679. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8680. \code{(eq? y 0)} and the previously presented code for the branches.
  8681. \subsection{Create Block}
  8682. We recommend implementing the \code{create\_block} auxiliary function
  8683. as follows, using a global variable \code{basic-blocks} to store a
  8684. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8685. that \code{create\_block} generates a new label and then associates
  8686. the given \code{tail} with the new label in the \code{basic-blocks}
  8687. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8688. new label. However, if the given \code{tail} is already a \code{Goto},
  8689. then there is no need to generate a new label and entry in
  8690. \code{basic-blocks}; we can simply return that \code{Goto}.
  8691. %
  8692. \begin{lstlisting}
  8693. (define (create_block tail)
  8694. (match tail
  8695. [(Goto label) (Goto label)]
  8696. [else
  8697. (let ([label (gensym 'block)])
  8698. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8699. (Goto label))]))
  8700. \end{lstlisting}
  8701. \fi}
  8702. {\if\edition\racketEd
  8703. \subsection{Explicate Predicate}
  8704. The skeleton for the \code{explicate\_pred} function is given in
  8705. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8706. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8707. the code generated by explicate for the \emph{then} branch; and (3)
  8708. \code{els}, the code generated by explicate for the \emph{else}
  8709. branch. The \code{explicate\_pred} function should match on
  8710. \code{cnd} with a case for every kind of expression that can have type
  8711. \BOOLTY{}.
  8712. \begin{figure}[tbp]
  8713. \begin{tcolorbox}[colback=white]
  8714. \begin{lstlisting}
  8715. (define (explicate_pred cnd thn els)
  8716. (match cnd
  8717. [(Var x) ___]
  8718. [(Let x rhs body) ___]
  8719. [(Prim 'not (list e)) ___]
  8720. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8721. (IfStmt (Prim op es) (create_block thn)
  8722. (create_block els))]
  8723. [(Bool b) (if b thn els)]
  8724. [(If cnd^ thn^ els^) ___]
  8725. [else (error "explicate_pred unhandled case" cnd)]))
  8726. \end{lstlisting}
  8727. \end{tcolorbox}
  8728. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8729. \label{fig:explicate-pred}
  8730. \end{figure}
  8731. \fi}
  8732. %
  8733. {\if\edition\pythonEd\pythonColor
  8734. The \code{explicate\_pred} function has four parameters: 1) the
  8735. condition expression, 2) the generated statements for the ``then''
  8736. branch, 3) the generated statements for the ``else'' branch, and 4)
  8737. the dictionary of basic blocks. The \code{explicate\_pred} function
  8738. returns a list of \LangCIf{} statements and it may add to the
  8739. dictionary of basic blocks.
  8740. \fi}
  8741. Consider the case for comparison operators. We translate the
  8742. comparison to an \code{if} statement whose branches are \code{goto}
  8743. statements created by applying \code{create\_block} to the code
  8744. generated for the \code{thn} and \code{els} branches. Let us
  8745. illustrate this translation by returning to the program with an
  8746. \code{if} expression in tail position, shown next. We invoke
  8747. \code{explicate\_pred} on its condition
  8748. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8749. %
  8750. {\if\edition\racketEd
  8751. \begin{lstlisting}
  8752. (let ([x (read)])
  8753. (if (eq? x 0) 42 777))
  8754. \end{lstlisting}
  8755. \fi}
  8756. %
  8757. {\if\edition\pythonEd\pythonColor
  8758. \begin{lstlisting}
  8759. x = input_int()
  8760. 42 if x == 0 else 777
  8761. \end{lstlisting}
  8762. \fi}
  8763. %
  8764. \noindent The two branches \code{42} and \code{777} were already
  8765. compiled to \code{return} statements, from which we now create the
  8766. following blocks:
  8767. %
  8768. \begin{center}
  8769. \begin{minipage}{\textwidth}
  8770. \begin{lstlisting}
  8771. block_1:
  8772. return 42;
  8773. block_2:
  8774. return 777;
  8775. \end{lstlisting}
  8776. \end{minipage}
  8777. \end{center}
  8778. %
  8779. After that, \code{explicate\_pred} compiles the comparison
  8780. \racket{\code{(eq? x 0)}}
  8781. \python{\code{x == 0}}
  8782. to the following \code{if} statement:
  8783. %
  8784. {\if\edition\racketEd
  8785. \begin{center}
  8786. \begin{minipage}{\textwidth}
  8787. \begin{lstlisting}
  8788. if (eq? x 0)
  8789. goto block_1;
  8790. else
  8791. goto block_2;
  8792. \end{lstlisting}
  8793. \end{minipage}
  8794. \end{center}
  8795. \fi}
  8796. {\if\edition\pythonEd\pythonColor
  8797. \begin{center}
  8798. \begin{minipage}{\textwidth}
  8799. \begin{lstlisting}
  8800. if x == 0:
  8801. goto block_1;
  8802. else
  8803. goto block_2;
  8804. \end{lstlisting}
  8805. \end{minipage}
  8806. \end{center}
  8807. \fi}
  8808. Next consider the case for Boolean constants. We perform a kind of
  8809. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8810. either the \code{thn} or \code{els} branch, depending on whether the
  8811. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8812. following program:
  8813. {\if\edition\racketEd
  8814. \begin{lstlisting}
  8815. (if #t 42 777)
  8816. \end{lstlisting}
  8817. \fi}
  8818. {\if\edition\pythonEd\pythonColor
  8819. \begin{lstlisting}
  8820. 42 if True else 777
  8821. \end{lstlisting}
  8822. \fi}
  8823. %
  8824. \noindent Again, the two branches \code{42} and \code{777} were
  8825. compiled to \code{return} statements, so \code{explicate\_pred}
  8826. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8827. code for the \emph{then} branch.
  8828. \begin{lstlisting}
  8829. return 42;
  8830. \end{lstlisting}
  8831. This case demonstrates that we sometimes discard the \code{thn} or
  8832. \code{els} blocks that are input to \code{explicate\_pred}.
  8833. The case for \key{if} expressions in \code{explicate\_pred} is
  8834. particularly illuminating because it deals with the challenges
  8835. discussed previously regarding nested \key{if} expressions
  8836. (figure~\ref{fig:explicate-control-s1-38}). The
  8837. \racket{\lstinline{thn^}}\python{\code{body}} and
  8838. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8839. \key{if} inherit their context from the current one, that is,
  8840. predicate context. So, you should recursively apply
  8841. \code{explicate\_pred} to the
  8842. \racket{\lstinline{thn^}}\python{\code{body}} and
  8843. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8844. those recursive calls, pass \code{thn} and \code{els} as the extra
  8845. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8846. inside each recursive call. As discussed previously, to avoid
  8847. duplicating code, we need to add them to the dictionary of basic
  8848. blocks so that we can instead refer to them by name and execute them
  8849. with a \key{goto}.
  8850. {\if\edition\pythonEd\pythonColor
  8851. %
  8852. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8853. three parameters: (1) the statement to be compiled, (2) the code for its
  8854. continuation, and (3) the dictionary of basic blocks. The
  8855. \code{explicate\_stmt} returns a list of statements, and it may add to
  8856. the dictionary of basic blocks. The cases for assignment and an
  8857. expression-statement are given in full in the skeleton code: they
  8858. simply dispatch to \code{explicate\_assign} and
  8859. \code{explicate\_effect}, respectively. The case for \code{if}
  8860. statements is not given; it is similar to the case for \code{if}
  8861. expressions.
  8862. The \code{explicate\_control} function itself is given in
  8863. figure~\ref{fig:explicate-control-Lif}. It applies
  8864. \code{explicate\_stmt} to each statement in the program, from back to
  8865. front. Thus, the result so far, stored in \code{new\_body}, can be
  8866. used as the continuation parameter in the next call to
  8867. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8868. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8869. the dictionary of basic blocks, labeling it the ``start'' block.
  8870. %
  8871. \fi}
  8872. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8873. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8874. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8875. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8876. %% results from the two recursive calls. We complete the case for
  8877. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8878. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8879. %% the result $B_5$.
  8880. %% \[
  8881. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8882. %% \quad\Rightarrow\quad
  8883. %% B_5
  8884. %% \]
  8885. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8886. %% inherit the current context, so they are in tail position. Thus, the
  8887. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8888. %% \code{explicate\_tail}.
  8889. %% %
  8890. %% We need to pass $B_0$ as the accumulator argument for both of these
  8891. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8892. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8893. %% to the control-flow graph and obtain a promised goto $G_0$.
  8894. %% %
  8895. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8896. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8897. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8898. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8899. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8900. %% \[
  8901. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8902. %% \]
  8903. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8904. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8905. %% should not be confused with the labels for the blocks that appear in
  8906. %% the generated code. We initially construct unlabeled blocks; we only
  8907. %% attach labels to blocks when we add them to the control-flow graph, as
  8908. %% we see in the next case.
  8909. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8910. %% function. The context of the \key{if} is an assignment to some
  8911. %% variable $x$ and then the control continues to some promised block
  8912. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8913. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8914. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8915. %% branches of the \key{if} inherit the current context, so they are in
  8916. %% assignment positions. Let $B_2$ be the result of applying
  8917. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8918. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8919. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8920. %% the result of applying \code{explicate\_pred} to the predicate
  8921. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8922. %% translates to the promise $B_4$.
  8923. %% \[
  8924. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8925. %% \]
  8926. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8927. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8928. \code{remove\_complex\_operands} pass and then the
  8929. \code{explicate\_control} pass on the example program. We walk through
  8930. the output program.
  8931. %
  8932. Following the order of evaluation in the output of
  8933. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8934. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8935. in the predicate of the inner \key{if}. In the output of
  8936. \code{explicate\_control}, in the
  8937. block labeled \code{start}, two assignment statements are followed by an
  8938. \code{if} statement that branches to \code{block\_4} or
  8939. \code{block\_5}. The blocks associated with those labels contain the
  8940. translations of the code
  8941. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8942. and
  8943. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8944. respectively. In particular, we start \code{block\_4} with the
  8945. comparison
  8946. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8947. and then branch to \code{block\_2} or \code{block\_3},
  8948. which correspond to the two branches of the outer \key{if}, that is,
  8949. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8950. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8951. %
  8952. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8953. %
  8954. \python{The \code{block\_1} corresponds to the \code{print} statement
  8955. at the end of the program.}
  8956. {\if\edition\racketEd
  8957. \subsection{Interactions between Explicate and Shrink}
  8958. The way in which the \code{shrink} pass transforms logical operations
  8959. such as \code{and} and \code{or} can impact the quality of code
  8960. generated by \code{explicate\_control}. For example, consider the
  8961. following program:
  8962. % cond_test_21.rkt, and_eq_input.py
  8963. \begin{lstlisting}
  8964. (if (and (eq? (read) 0) (eq? (read) 1))
  8965. 0
  8966. 42)
  8967. \end{lstlisting}
  8968. The \code{and} operation should transform into something that the
  8969. \code{explicate\_pred} function can analyze and descend through to
  8970. reach the underlying \code{eq?} conditions. Ideally, for this program
  8971. your \code{explicate\_control} pass should generate code similar to
  8972. the following:
  8973. \begin{center}
  8974. \begin{minipage}{\textwidth}
  8975. \begin{lstlisting}
  8976. start:
  8977. tmp1 = (read);
  8978. if (eq? tmp1 0) goto block40;
  8979. else goto block39;
  8980. block40:
  8981. tmp2 = (read);
  8982. if (eq? tmp2 1) goto block38;
  8983. else goto block39;
  8984. block38:
  8985. return 0;
  8986. block39:
  8987. return 42;
  8988. \end{lstlisting}
  8989. \end{minipage}
  8990. \end{center}
  8991. \fi}
  8992. \begin{exercise}\normalfont\normalsize
  8993. \racket{
  8994. Implement the pass \code{explicate\_control} by adding the cases for
  8995. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8996. \code{explicate\_assign} functions. Implement the auxiliary function
  8997. \code{explicate\_pred} for predicate contexts.}
  8998. \python{Implement \code{explicate\_control} pass with its
  8999. four auxiliary functions.}
  9000. %
  9001. Create test cases that exercise all the new cases in the code for
  9002. this pass.
  9003. %
  9004. {\if\edition\racketEd
  9005. Add the following entry to the list of \code{passes} in
  9006. \code{run-tests.rkt}:
  9007. \begin{lstlisting}
  9008. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9009. \end{lstlisting}
  9010. and then run \code{run-tests.rkt} to test your compiler.
  9011. \fi}
  9012. \end{exercise}
  9013. \section{Select Instructions}
  9014. \label{sec:select-Lif}
  9015. \index{subject}{select instructions}
  9016. The \code{select\_instructions} pass translates \LangCIf{} to
  9017. \LangXIfVar{}.
  9018. %
  9019. \racket{Recall that we implement this pass using three auxiliary
  9020. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9021. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9022. %
  9023. \racket{For $\Atm$, we have new cases for the Booleans.}
  9024. %
  9025. \python{We begin with the Boolean constants.}
  9026. As previously discussed, we encode them as integers.
  9027. \[
  9028. \TRUE{} \quad\Rightarrow\quad \key{1}
  9029. \qquad\qquad
  9030. \FALSE{} \quad\Rightarrow\quad \key{0}
  9031. \]
  9032. For translating statements, we discuss some of the cases. The
  9033. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9034. discussed at the beginning of this section. Given an assignment, if
  9035. the left-hand-side variable is the same as the argument of \code{not},
  9036. then just the \code{xorq} instruction suffices.
  9037. \[
  9038. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9039. \quad\Rightarrow\quad
  9040. \key{xorq}~\key{\$}1\key{,}~\Var
  9041. \]
  9042. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9043. semantics of x86. In the following translation, let $\Arg$ be the
  9044. result of translating $\Atm$ to x86.
  9045. \[
  9046. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9047. \quad\Rightarrow\quad
  9048. \begin{array}{l}
  9049. \key{movq}~\Arg\key{,}~\Var\\
  9050. \key{xorq}~\key{\$}1\key{,}~\Var
  9051. \end{array}
  9052. \]
  9053. Next consider the cases for equality comparisons. Translating this
  9054. operation to x86 is slightly involved due to the unusual nature of the
  9055. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9056. We recommend translating an assignment with an equality on the
  9057. right-hand side into a sequence of three instructions. \\
  9058. \begin{tabular}{lll}
  9059. \begin{minipage}{0.4\textwidth}
  9060. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9061. \end{minipage}
  9062. &
  9063. $\Rightarrow$
  9064. &
  9065. \begin{minipage}{0.4\textwidth}
  9066. \begin{lstlisting}
  9067. cmpq |$\Arg_2$|, |$\Arg_1$|
  9068. sete %al
  9069. movzbq %al, |$\Var$|
  9070. \end{lstlisting}
  9071. \end{minipage}
  9072. \end{tabular} \\
  9073. The translations for the other comparison operators are similar to
  9074. this but use different condition codes for the \code{set} instruction.
  9075. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9076. \key{goto} and \key{if} statements. Both are straightforward to
  9077. translate to x86.}
  9078. %
  9079. A \key{goto} statement becomes a jump instruction.
  9080. \[
  9081. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9082. \]
  9083. %
  9084. An \key{if} statement becomes a compare instruction followed by a
  9085. conditional jump (for the \emph{then} branch), and the fall-through is to
  9086. a regular jump (for the \emph{else} branch).\\
  9087. \begin{tabular}{lll}
  9088. \begin{minipage}{0.4\textwidth}
  9089. \begin{lstlisting}
  9090. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9091. goto |$\ell_1$||$\racket{\key{;}}$|
  9092. else|$\python{\key{:}}$|
  9093. goto |$\ell_2$||$\racket{\key{;}}$|
  9094. \end{lstlisting}
  9095. \end{minipage}
  9096. &
  9097. $\Rightarrow$
  9098. &
  9099. \begin{minipage}{0.4\textwidth}
  9100. \begin{lstlisting}
  9101. cmpq |$\Arg_2$|, |$\Arg_1$|
  9102. je |$\ell_1$|
  9103. jmp |$\ell_2$|
  9104. \end{lstlisting}
  9105. \end{minipage}
  9106. \end{tabular} \\
  9107. Again, the translations for the other comparison operators are similar to this
  9108. but use different condition codes for the conditional jump instruction.
  9109. \python{Regarding the \key{return} statement, we recommend treating it
  9110. as an assignment to the \key{rax} register followed by a jump to the
  9111. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9112. \begin{exercise}\normalfont\normalsize
  9113. Expand your \code{select\_instructions} pass to handle the new
  9114. features of the \LangCIf{} language.
  9115. %
  9116. {\if\edition\racketEd
  9117. Add the following entry to the list of \code{passes} in
  9118. \code{run-tests.rkt}
  9119. \begin{lstlisting}
  9120. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9121. \end{lstlisting}
  9122. \fi}
  9123. %
  9124. Run the script to test your compiler on all the test programs.
  9125. \end{exercise}
  9126. \section{Register Allocation}
  9127. \label{sec:register-allocation-Lif}
  9128. \index{subject}{register allocation}
  9129. The changes required for compiling \LangIf{} affect liveness analysis,
  9130. building the interference graph, and assigning homes, but the graph
  9131. coloring algorithm itself does not change.
  9132. \subsection{Liveness Analysis}
  9133. \label{sec:liveness-analysis-Lif}
  9134. \index{subject}{liveness analysis}
  9135. Recall that for \LangVar{} we implemented liveness analysis for a
  9136. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9137. the addition of \key{if} expressions to \LangIf{},
  9138. \code{explicate\_control} produces many basic blocks.
  9139. %% We recommend that you create a new auxiliary function named
  9140. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9141. %% control-flow graph.
  9142. The first question is, in what order should we process the basic blocks?
  9143. Recall that to perform liveness analysis on a basic block we need to
  9144. know the live-after set for the last instruction in the block. If a
  9145. basic block has no successors (i.e., contains no jumps to other
  9146. blocks), then it has an empty live-after set and we can immediately
  9147. apply liveness analysis to it. If a basic block has some successors,
  9148. then we need to complete liveness analysis on those blocks
  9149. first. These ordering constraints are the reverse of a
  9150. \emph{topological order}\index{subject}{topological order} on a graph
  9151. representation of the program. In particular, the \emph{control flow
  9152. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9153. of a program has a node for each basic block and an edge for each jump
  9154. from one block to another. It is straightforward to generate a CFG
  9155. from the dictionary of basic blocks. One then transposes the CFG and
  9156. applies the topological sort algorithm.
  9157. %
  9158. %
  9159. \racket{We recommend using the \code{tsort} and \code{transpose}
  9160. functions of the Racket \code{graph} package to accomplish this.}
  9161. %
  9162. \python{We provide implementations of \code{topological\_sort} and
  9163. \code{transpose} in the file \code{graph.py} of the support code.}
  9164. %
  9165. As an aside, a topological ordering is only guaranteed to exist if the
  9166. graph does not contain any cycles. This is the case for the
  9167. control-flow graphs that we generate from \LangIf{} programs.
  9168. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9169. and learn how to handle cycles in the control-flow graph.
  9170. \racket{You need to construct a directed graph to represent the
  9171. control-flow graph. Do not use the \code{directed-graph} of the
  9172. \code{graph} package because that allows at most one edge
  9173. between each pair of vertices, whereas a control-flow graph may have
  9174. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9175. file in the support code implements a graph representation that
  9176. allows multiple edges between a pair of vertices.}
  9177. {\if\edition\racketEd
  9178. The next question is how to analyze jump instructions. Recall that in
  9179. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9180. \code{label->live} that maps each label to the set of live locations
  9181. at the beginning of its block. We use \code{label->live} to determine
  9182. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9183. that we have many basic blocks, \code{label->live} needs to be updated
  9184. as we process the blocks. In particular, after performing liveness
  9185. analysis on a block, we take the live-before set of its first
  9186. instruction and associate that with the block's label in the
  9187. \code{label->live} alist.
  9188. \fi}
  9189. %
  9190. {\if\edition\pythonEd\pythonColor
  9191. %
  9192. The next question is how to analyze jump instructions. The locations
  9193. that are live before a \code{jmp} should be the locations in
  9194. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9195. maintaining a dictionary named \code{live\_before\_block} that maps each
  9196. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9197. block. After performing liveness analysis on each block, we take the
  9198. live-before set of its first instruction and associate that with the
  9199. block's label in the \code{live\_before\_block} dictionary.
  9200. %
  9201. \fi}
  9202. In \LangXIfVar{} we also have the conditional jump
  9203. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9204. this instruction is particularly interesting because during
  9205. compilation, we do not know which way a conditional jump will go. Thus
  9206. we do not know whether to use the live-before set for the block
  9207. associated with the $\itm{label}$ or the live-before set for the
  9208. following instruction. So we use both, by taking the union of the
  9209. live-before sets from the following instruction and from the mapping
  9210. for $\itm{label}$ in
  9211. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9212. The auxiliary functions for computing the variables in an
  9213. instruction's argument and for computing the variables read-from ($R$)
  9214. or written-to ($W$) by an instruction need to be updated to handle the
  9215. new kinds of arguments and instructions in \LangXIfVar{}.
  9216. \begin{exercise}\normalfont\normalsize
  9217. {\if\edition\racketEd
  9218. %
  9219. Update the \code{uncover\_live} pass to apply liveness analysis to
  9220. every basic block in the program.
  9221. %
  9222. Add the following entry to the list of \code{passes} in the
  9223. \code{run-tests.rkt} script:
  9224. \begin{lstlisting}
  9225. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9226. \end{lstlisting}
  9227. \fi}
  9228. {\if\edition\pythonEd\pythonColor
  9229. %
  9230. Update the \code{uncover\_live} function to perform liveness analysis,
  9231. in reverse topological order, on all the basic blocks in the
  9232. program.
  9233. %
  9234. \fi}
  9235. % Check that the live-after sets that you generate for
  9236. % example X matches the following... -Jeremy
  9237. \end{exercise}
  9238. \subsection{Build the Interference Graph}
  9239. \label{sec:build-interference-Lif}
  9240. Many of the new instructions in \LangXIfVar{} can be handled in the
  9241. same way as the instructions in \LangXVar{}.
  9242. % Thus, if your code was
  9243. % already quite general, it will not need to be changed to handle the
  9244. % new instructions. If your code is not general enough, we recommend that
  9245. % you change your code to be more general. For example, you can factor
  9246. % out the computing of the the read and write sets for each kind of
  9247. % instruction into auxiliary functions.
  9248. %
  9249. Some instructions, such as the \key{movzbq} instruction, require special care,
  9250. similar to the \key{movq} instruction. Refer to rule number 1 in
  9251. section~\ref{sec:build-interference}.
  9252. \begin{exercise}\normalfont\normalsize
  9253. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9254. {\if\edition\racketEd
  9255. Add the following entries to the list of \code{passes} in the
  9256. \code{run-tests.rkt} script:
  9257. \begin{lstlisting}
  9258. (list "build_interference" build_interference interp-pseudo-x86-1)
  9259. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9260. \end{lstlisting}
  9261. \fi}
  9262. % Check that the interference graph that you generate for
  9263. % example X matches the following graph G... -Jeremy
  9264. \end{exercise}
  9265. \section{Patch Instructions}
  9266. The new instructions \key{cmpq} and \key{movzbq} have some special
  9267. restrictions that need to be handled in the \code{patch\_instructions}
  9268. pass.
  9269. %
  9270. The second argument of the \key{cmpq} instruction must not be an
  9271. immediate value (such as an integer). So, if you are comparing two
  9272. immediates, we recommend inserting a \key{movq} instruction to put the
  9273. second argument in \key{rax}. On the other hand, if you implemented
  9274. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9275. update it for \LangIf{} and then this situation would not arise.
  9276. %
  9277. As usual, \key{cmpq} may have at most one memory reference.
  9278. %
  9279. The second argument of the \key{movzbq} must be a register.
  9280. \begin{exercise}\normalfont\normalsize
  9281. %
  9282. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9283. %
  9284. {\if\edition\racketEd
  9285. Add the following entry to the list of \code{passes} in
  9286. \code{run-tests.rkt}, and then run this script to test your compiler.
  9287. \begin{lstlisting}
  9288. (list "patch_instructions" patch_instructions interp-x86-1)
  9289. \end{lstlisting}
  9290. \fi}
  9291. \end{exercise}
  9292. {\if\edition\pythonEd\pythonColor
  9293. \section{Prelude and Conclusion}
  9294. \label{sec:prelude-conclusion-cond}
  9295. The generation of the \code{main} function with its prelude and
  9296. conclusion must change to accommodate how the program now consists of
  9297. one or more basic blocks. After the prelude in \code{main}, jump to
  9298. the \code{start} block. Place the conclusion in a basic block labeled
  9299. with \code{conclusion}.
  9300. \fi}
  9301. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9302. \LangIf{} translated to x86, showing the results of
  9303. \code{explicate\_control}, \code{select\_instructions}, and the final
  9304. x86 assembly.
  9305. \begin{figure}[tbp]
  9306. \begin{tcolorbox}[colback=white]
  9307. {\if\edition\racketEd
  9308. \begin{tabular}{lll}
  9309. \begin{minipage}{0.4\textwidth}
  9310. % cond_test_20.rkt, eq_input.py
  9311. \begin{lstlisting}
  9312. (if (eq? (read) 1) 42 0)
  9313. \end{lstlisting}
  9314. $\Downarrow$
  9315. \begin{lstlisting}
  9316. start:
  9317. tmp7951 = (read);
  9318. if (eq? tmp7951 1)
  9319. goto block7952;
  9320. else
  9321. goto block7953;
  9322. block7952:
  9323. return 42;
  9324. block7953:
  9325. return 0;
  9326. \end{lstlisting}
  9327. $\Downarrow$
  9328. \begin{lstlisting}
  9329. start:
  9330. callq read_int
  9331. movq %rax, tmp7951
  9332. cmpq $1, tmp7951
  9333. je block7952
  9334. jmp block7953
  9335. block7953:
  9336. movq $0, %rax
  9337. jmp conclusion
  9338. block7952:
  9339. movq $42, %rax
  9340. jmp conclusion
  9341. \end{lstlisting}
  9342. \end{minipage}
  9343. &
  9344. $\Rightarrow\qquad$
  9345. \begin{minipage}{0.4\textwidth}
  9346. \begin{lstlisting}
  9347. start:
  9348. callq read_int
  9349. movq %rax, %rcx
  9350. cmpq $1, %rcx
  9351. je block7952
  9352. jmp block7953
  9353. block7953:
  9354. movq $0, %rax
  9355. jmp conclusion
  9356. block7952:
  9357. movq $42, %rax
  9358. jmp conclusion
  9359. .globl main
  9360. main:
  9361. pushq %rbp
  9362. movq %rsp, %rbp
  9363. pushq %r13
  9364. pushq %r12
  9365. pushq %rbx
  9366. pushq %r14
  9367. subq $0, %rsp
  9368. jmp start
  9369. conclusion:
  9370. addq $0, %rsp
  9371. popq %r14
  9372. popq %rbx
  9373. popq %r12
  9374. popq %r13
  9375. popq %rbp
  9376. retq
  9377. \end{lstlisting}
  9378. \end{minipage}
  9379. \end{tabular}
  9380. \fi}
  9381. {\if\edition\pythonEd\pythonColor
  9382. \begin{tabular}{lll}
  9383. \begin{minipage}{0.4\textwidth}
  9384. % cond_test_20.rkt, eq_input.py
  9385. \begin{lstlisting}
  9386. print(42 if input_int() == 1 else 0)
  9387. \end{lstlisting}
  9388. $\Downarrow$
  9389. \begin{lstlisting}
  9390. start:
  9391. tmp_0 = input_int()
  9392. if tmp_0 == 1:
  9393. goto block_3
  9394. else:
  9395. goto block_4
  9396. block_3:
  9397. tmp_1 = 42
  9398. goto block_2
  9399. block_4:
  9400. tmp_1 = 0
  9401. goto block_2
  9402. block_2:
  9403. print(tmp_1)
  9404. return 0
  9405. \end{lstlisting}
  9406. $\Downarrow$
  9407. \begin{lstlisting}
  9408. start:
  9409. callq read_int
  9410. movq %rax, tmp_0
  9411. cmpq 1, tmp_0
  9412. je block_3
  9413. jmp block_4
  9414. block_3:
  9415. movq 42, tmp_1
  9416. jmp block_2
  9417. block_4:
  9418. movq 0, tmp_1
  9419. jmp block_2
  9420. block_2:
  9421. movq tmp_1, %rdi
  9422. callq print_int
  9423. movq 0, %rax
  9424. jmp conclusion
  9425. \end{lstlisting}
  9426. \end{minipage}
  9427. &
  9428. $\Rightarrow\qquad$
  9429. \begin{minipage}{0.4\textwidth}
  9430. \begin{lstlisting}
  9431. .globl main
  9432. main:
  9433. pushq %rbp
  9434. movq %rsp, %rbp
  9435. subq $0, %rsp
  9436. jmp start
  9437. start:
  9438. callq read_int
  9439. movq %rax, %rcx
  9440. cmpq $1, %rcx
  9441. je block_3
  9442. jmp block_4
  9443. block_3:
  9444. movq $42, %rcx
  9445. jmp block_2
  9446. block_4:
  9447. movq $0, %rcx
  9448. jmp block_2
  9449. block_2:
  9450. movq %rcx, %rdi
  9451. callq print_int
  9452. movq $0, %rax
  9453. jmp conclusion
  9454. conclusion:
  9455. addq $0, %rsp
  9456. popq %rbp
  9457. retq
  9458. \end{lstlisting}
  9459. \end{minipage}
  9460. \end{tabular}
  9461. \fi}
  9462. \end{tcolorbox}
  9463. \caption{Example compilation of an \key{if} expression to x86, showing
  9464. the results of \code{explicate\_control},
  9465. \code{select\_instructions}, and the final x86 assembly code. }
  9466. \label{fig:if-example-x86}
  9467. \end{figure}
  9468. \begin{figure}[tbp]
  9469. \begin{tcolorbox}[colback=white]
  9470. {\if\edition\racketEd
  9471. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9472. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9473. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9474. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9475. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9476. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9477. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9478. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9479. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9480. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9481. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9482. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9483. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9484. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9485. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9486. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9487. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9488. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9489. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9490. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9491. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9492. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9493. \end{tikzpicture}
  9494. \fi}
  9495. {\if\edition\pythonEd\pythonColor
  9496. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9497. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9498. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9499. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9500. \node (C-1) at (0,0) {\large \LangCIf{}};
  9501. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9502. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9503. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9504. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9505. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9506. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9507. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9508. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9509. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9510. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9511. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9512. \end{tikzpicture}
  9513. \fi}
  9514. \end{tcolorbox}
  9515. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9516. \label{fig:Lif-passes}
  9517. \end{figure}
  9518. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9519. compilation of \LangIf{}.
  9520. \section{Challenge: Optimize Blocks and Remove Jumps}
  9521. \label{sec:opt-jumps}
  9522. We discuss two challenges that involve optimizing the control-flow of
  9523. the program.
  9524. \subsection{Optimize Blocks}
  9525. The algorithm for \code{explicate\_control} that we discussed in
  9526. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9527. blocks. It creates a block whenever a continuation \emph{might} get
  9528. used more than once (for example, whenever the \code{cont} parameter
  9529. is passed into two or more recursive calls). However, some
  9530. continuation arguments may not be used at all. Consider the case for
  9531. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9532. the \code{els} continuation.
  9533. %
  9534. {\if\edition\racketEd
  9535. The following example program falls into this
  9536. case, and it creates two unused blocks.
  9537. \begin{center}
  9538. \begin{tabular}{lll}
  9539. \begin{minipage}{0.4\textwidth}
  9540. % cond_test_82.rkt
  9541. \begin{lstlisting}
  9542. (let ([y (if #t
  9543. (read)
  9544. (if (eq? (read) 0)
  9545. 777
  9546. (let ([x (read)])
  9547. (+ 1 x))))])
  9548. (+ y 2))
  9549. \end{lstlisting}
  9550. \end{minipage}
  9551. &
  9552. $\Rightarrow$
  9553. &
  9554. \begin{minipage}{0.55\textwidth}
  9555. \begin{lstlisting}
  9556. start:
  9557. y = (read);
  9558. goto block_5;
  9559. block_5:
  9560. return (+ y 2);
  9561. block_6:
  9562. y = 777;
  9563. goto block_5;
  9564. block_7:
  9565. x = (read);
  9566. y = (+ 1 x2);
  9567. goto block_5;
  9568. \end{lstlisting}
  9569. \end{minipage}
  9570. \end{tabular}
  9571. \end{center}
  9572. \fi}
  9573. The question is, how can we decide whether to create a basic block?
  9574. \emph{Lazy evaluation}\index{subject}{lazy
  9575. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9576. delaying the creation of a basic block until the point in time at which
  9577. we know that it will be used.
  9578. %
  9579. {\if\edition\racketEd
  9580. %
  9581. Racket provides support for
  9582. lazy evaluation with the
  9583. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9584. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9585. \index{subject}{delay} creates a
  9586. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9587. expressions is postponed. When \key{(force}
  9588. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9589. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9590. result of $e_n$ is cached in the promise and returned. If \code{force}
  9591. is applied again to the same promise, then the cached result is
  9592. returned. If \code{force} is applied to an argument that is not a
  9593. promise, \code{force} simply returns the argument.
  9594. %
  9595. \fi}
  9596. %
  9597. {\if\edition\pythonEd\pythonColor
  9598. %
  9599. Although Python does not provide direct support for lazy evaluation,
  9600. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9601. by wrapping it inside a function with no parameters. We \emph{force}
  9602. its evaluation by calling the function. However, we might need to
  9603. force multiple times, so we store the result of calling the
  9604. function instead of recomputing it each time. The following
  9605. \code{Promise} class handles this memoization process.
  9606. %
  9607. \begin{lstlisting}
  9608. @dataclass
  9609. class Promise:
  9610. fun : typing.Any
  9611. cache : list[stmt] = None
  9612. def force(self):
  9613. if self.cache is None:
  9614. self.cache = self.fun(); return self.cache
  9615. else:
  9616. return self.cache
  9617. \end{lstlisting}
  9618. %
  9619. However, in some cases of \code{explicate\_pred} we return a list
  9620. of statements, and in other cases we return a function that
  9621. computes a list of statements. To uniformly deal with both regular
  9622. data and promises, we define the following \code{force} function that
  9623. checks whether its input is delayed (i.e., whether it is a
  9624. \code{Promise}) and then either (1) forces the promise or (2) returns
  9625. the input.
  9626. %
  9627. \begin{lstlisting}
  9628. def force(promise):
  9629. if isinstance(promise, Promise):
  9630. return promise.force()
  9631. else:
  9632. return promise
  9633. \end{lstlisting}
  9634. %
  9635. \fi}
  9636. We use promises for the input and output of the functions
  9637. \code{explicate\_pred}, \code{explicate\_assign},
  9638. %
  9639. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9640. %
  9641. So, instead of taking and returning \racket{$\Tail$
  9642. expressions}\python{lists of statements}, they take and return
  9643. promises. Furthermore, when we come to a situation in which a
  9644. continuation might be used more than once, as in the case for
  9645. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9646. that creates a basic block for each continuation (if there is not
  9647. already one) and then returns a \code{goto} statement to that basic
  9648. block. When we come to a situation in which we have a promise but need an
  9649. actual piece of code, for example, to create a larger piece of code with a
  9650. constructor such as \code{Seq}, then insert a call to \code{force}.
  9651. %
  9652. {\if\edition\racketEd
  9653. %
  9654. Also, we must modify the \code{create\_block} function to begin with
  9655. \code{delay} to create a promise. When forced, this promise forces the
  9656. original promise. If that returns a \code{Goto} (because the block was
  9657. already added to \code{basic-blocks}), then we return the
  9658. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9659. return a \code{Goto} to the new label.
  9660. \begin{center}
  9661. \begin{minipage}{\textwidth}
  9662. \begin{lstlisting}
  9663. (define (create_block tail)
  9664. (delay
  9665. (define t (force tail))
  9666. (match t
  9667. [(Goto label) (Goto label)]
  9668. [else
  9669. (let ([label (gensym 'block)])
  9670. (set! basic-blocks (cons (cons label t) basic-blocks))
  9671. (Goto label))])))
  9672. \end{lstlisting}
  9673. \end{minipage}
  9674. \end{center}
  9675. \fi}
  9676. {\if\edition\pythonEd\pythonColor
  9677. %
  9678. Here is the new version of the \code{create\_block} auxiliary function
  9679. that works on promises and that checks whether the block consists of a
  9680. solitary \code{goto} statement.\\
  9681. \begin{minipage}{\textwidth}
  9682. \begin{lstlisting}
  9683. def create_block(promise, basic_blocks):
  9684. def delay():
  9685. stmts = force(promise)
  9686. match stmts:
  9687. case [Goto(l)]:
  9688. return [Goto(l)]
  9689. case _:
  9690. label = label_name(generate_name('block'))
  9691. basic_blocks[label] = stmts
  9692. return [Goto(label)]
  9693. return Promise(delay)
  9694. \end{lstlisting}
  9695. \end{minipage}
  9696. \fi}
  9697. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9698. improved \code{explicate\_control} on this example. As you can
  9699. see, the number of basic blocks has been reduced from four blocks (see
  9700. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9701. \begin{figure}[tbp]
  9702. \begin{tcolorbox}[colback=white]
  9703. {\if\edition\racketEd
  9704. \begin{tabular}{lll}
  9705. \begin{minipage}{0.4\textwidth}
  9706. % cond_test_82.rkt
  9707. \begin{lstlisting}
  9708. (let ([y (if #t
  9709. (read)
  9710. (if (eq? (read) 0)
  9711. 777
  9712. (let ([x (read)])
  9713. (+ 1 x))))])
  9714. (+ y 2))
  9715. \end{lstlisting}
  9716. \end{minipage}
  9717. &
  9718. $\Rightarrow$
  9719. &
  9720. \begin{minipage}{0.55\textwidth}
  9721. \begin{lstlisting}
  9722. start:
  9723. y = (read);
  9724. goto block_5;
  9725. block_5:
  9726. return (+ y 2);
  9727. \end{lstlisting}
  9728. \end{minipage}
  9729. \end{tabular}
  9730. \fi}
  9731. {\if\edition\pythonEd\pythonColor
  9732. \begin{tabular}{lll}
  9733. \begin{minipage}{0.4\textwidth}
  9734. % cond_test_41.rkt
  9735. \begin{lstlisting}
  9736. x = input_int()
  9737. y = input_int()
  9738. print(y + 2 \
  9739. if (x == 0 \
  9740. if x < 1 \
  9741. else x == 2) \
  9742. else y + 10)
  9743. \end{lstlisting}
  9744. \end{minipage}
  9745. &
  9746. $\Rightarrow$
  9747. &
  9748. \begin{minipage}{0.55\textwidth}
  9749. \begin{lstlisting}
  9750. start:
  9751. x = input_int()
  9752. y = input_int()
  9753. if x < 1:
  9754. goto block_4
  9755. else:
  9756. goto block_5
  9757. block_4:
  9758. if x == 0:
  9759. goto block_2
  9760. else:
  9761. goto block_3
  9762. block_5:
  9763. if x == 2:
  9764. goto block_2
  9765. else:
  9766. goto block_3
  9767. block_2:
  9768. tmp_0 = y + 2
  9769. goto block_1
  9770. block_3:
  9771. tmp_0 = y + 10
  9772. goto block_1
  9773. block_1:
  9774. print(tmp_0)
  9775. return 0
  9776. \end{lstlisting}
  9777. \end{minipage}
  9778. \end{tabular}
  9779. \fi}
  9780. \end{tcolorbox}
  9781. \caption{Translation from \LangIf{} to \LangCIf{}
  9782. via the improved \code{explicate\_control}.}
  9783. \label{fig:explicate-control-challenge}
  9784. \end{figure}
  9785. %% Recall that in the example output of \code{explicate\_control} in
  9786. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9787. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9788. %% block. The first goal of this challenge assignment is to remove those
  9789. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9790. %% \code{explicate\_control} on the left and shows the result of bypassing
  9791. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9792. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9793. %% \code{block55}. The optimized code on the right of
  9794. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9795. %% \code{then} branch jumping directly to \code{block55}. The story is
  9796. %% similar for the \code{else} branch, as well as for the two branches in
  9797. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9798. %% have been optimized in this way, there are no longer any jumps to
  9799. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9800. %% \begin{figure}[tbp]
  9801. %% \begin{tabular}{lll}
  9802. %% \begin{minipage}{0.4\textwidth}
  9803. %% \begin{lstlisting}
  9804. %% block62:
  9805. %% tmp54 = (read);
  9806. %% if (eq? tmp54 2) then
  9807. %% goto block59;
  9808. %% else
  9809. %% goto block60;
  9810. %% block61:
  9811. %% tmp53 = (read);
  9812. %% if (eq? tmp53 0) then
  9813. %% goto block57;
  9814. %% else
  9815. %% goto block58;
  9816. %% block60:
  9817. %% goto block56;
  9818. %% block59:
  9819. %% goto block55;
  9820. %% block58:
  9821. %% goto block56;
  9822. %% block57:
  9823. %% goto block55;
  9824. %% block56:
  9825. %% return (+ 700 77);
  9826. %% block55:
  9827. %% return (+ 10 32);
  9828. %% start:
  9829. %% tmp52 = (read);
  9830. %% if (eq? tmp52 1) then
  9831. %% goto block61;
  9832. %% else
  9833. %% goto block62;
  9834. %% \end{lstlisting}
  9835. %% \end{minipage}
  9836. %% &
  9837. %% $\Rightarrow$
  9838. %% &
  9839. %% \begin{minipage}{0.55\textwidth}
  9840. %% \begin{lstlisting}
  9841. %% block62:
  9842. %% tmp54 = (read);
  9843. %% if (eq? tmp54 2) then
  9844. %% goto block55;
  9845. %% else
  9846. %% goto block56;
  9847. %% block61:
  9848. %% tmp53 = (read);
  9849. %% if (eq? tmp53 0) then
  9850. %% goto block55;
  9851. %% else
  9852. %% goto block56;
  9853. %% block56:
  9854. %% return (+ 700 77);
  9855. %% block55:
  9856. %% return (+ 10 32);
  9857. %% start:
  9858. %% tmp52 = (read);
  9859. %% if (eq? tmp52 1) then
  9860. %% goto block61;
  9861. %% else
  9862. %% goto block62;
  9863. %% \end{lstlisting}
  9864. %% \end{minipage}
  9865. %% \end{tabular}
  9866. %% \caption{Optimize jumps by removing trivial blocks.}
  9867. %% \label{fig:optimize-jumps}
  9868. %% \end{figure}
  9869. %% The name of this pass is \code{optimize-jumps}. We recommend
  9870. %% implementing this pass in two phases. The first phrase builds a hash
  9871. %% table that maps labels to possibly improved labels. The second phase
  9872. %% changes the target of each \code{goto} to use the improved label. If
  9873. %% the label is for a trivial block, then the hash table should map the
  9874. %% label to the first non-trivial block that can be reached from this
  9875. %% label by jumping through trivial blocks. If the label is for a
  9876. %% non-trivial block, then the hash table should map the label to itself;
  9877. %% we do not want to change jumps to non-trivial blocks.
  9878. %% The first phase can be accomplished by constructing an empty hash
  9879. %% table, call it \code{short-cut}, and then iterating over the control
  9880. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9881. %% then update the hash table, mapping the block's source to the target
  9882. %% of the \code{goto}. Also, the hash table may already have mapped some
  9883. %% labels to the block's source, to you must iterate through the hash
  9884. %% table and update all of those so that they instead map to the target
  9885. %% of the \code{goto}.
  9886. %% For the second phase, we recommend iterating through the $\Tail$ of
  9887. %% each block in the program, updating the target of every \code{goto}
  9888. %% according to the mapping in \code{short-cut}.
  9889. \begin{exercise}\normalfont\normalsize
  9890. Implement the improvements to the \code{explicate\_control} pass.
  9891. Check that it removes trivial blocks in a few example programs. Then
  9892. check that your compiler still passes all your tests.
  9893. \end{exercise}
  9894. \subsection{Remove Jumps}
  9895. There is an opportunity for removing jumps that is apparent in the
  9896. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9897. ends with a jump to \code{block\_5}, and there are no other jumps to
  9898. \code{block\_5} in the rest of the program. In this situation we can
  9899. avoid the runtime overhead of this jump by merging \code{block\_5}
  9900. into the preceding block, which in this case is the \code{start} block.
  9901. Figure~\ref{fig:remove-jumps} shows the output of
  9902. \code{allocate\_registers} on the left and the result of this
  9903. optimization on the right.
  9904. \begin{figure}[tbp]
  9905. \begin{tcolorbox}[colback=white]
  9906. {\if\edition\racketEd
  9907. \begin{tabular}{lll}
  9908. \begin{minipage}{0.5\textwidth}
  9909. % cond_test_82.rkt
  9910. \begin{lstlisting}
  9911. start:
  9912. callq read_int
  9913. movq %rax, %rcx
  9914. jmp block_5
  9915. block_5:
  9916. movq %rcx, %rax
  9917. addq $2, %rax
  9918. jmp conclusion
  9919. \end{lstlisting}
  9920. \end{minipage}
  9921. &
  9922. $\Rightarrow\qquad$
  9923. \begin{minipage}{0.4\textwidth}
  9924. \begin{lstlisting}
  9925. start:
  9926. callq read_int
  9927. movq %rax, %rcx
  9928. movq %rcx, %rax
  9929. addq $2, %rax
  9930. jmp conclusion
  9931. \end{lstlisting}
  9932. \end{minipage}
  9933. \end{tabular}
  9934. \fi}
  9935. {\if\edition\pythonEd\pythonColor
  9936. \begin{tabular}{lll}
  9937. \begin{minipage}{0.5\textwidth}
  9938. % cond_test_20.rkt
  9939. \begin{lstlisting}
  9940. start:
  9941. callq read_int
  9942. movq %rax, tmp_0
  9943. cmpq 1, tmp_0
  9944. je block_3
  9945. jmp block_4
  9946. block_3:
  9947. movq 42, tmp_1
  9948. jmp block_2
  9949. block_4:
  9950. movq 0, tmp_1
  9951. jmp block_2
  9952. block_2:
  9953. movq tmp_1, %rdi
  9954. callq print_int
  9955. movq 0, %rax
  9956. jmp conclusion
  9957. \end{lstlisting}
  9958. \end{minipage}
  9959. &
  9960. $\Rightarrow\qquad$
  9961. \begin{minipage}{0.4\textwidth}
  9962. \begin{lstlisting}
  9963. start:
  9964. callq read_int
  9965. movq %rax, tmp_0
  9966. cmpq 1, tmp_0
  9967. je block_3
  9968. movq 0, tmp_1
  9969. jmp block_2
  9970. block_3:
  9971. movq 42, tmp_1
  9972. jmp block_2
  9973. block_2:
  9974. movq tmp_1, %rdi
  9975. callq print_int
  9976. movq 0, %rax
  9977. jmp conclusion
  9978. \end{lstlisting}
  9979. \end{minipage}
  9980. \end{tabular}
  9981. \fi}
  9982. \end{tcolorbox}
  9983. \caption{Merging basic blocks by removing unnecessary jumps.}
  9984. \label{fig:remove-jumps}
  9985. \end{figure}
  9986. \begin{exercise}\normalfont\normalsize
  9987. %
  9988. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9989. into their preceding basic block, when there is only one preceding
  9990. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9991. %
  9992. {\if\edition\racketEd
  9993. In the \code{run-tests.rkt} script, add the following entry to the
  9994. list of \code{passes} between \code{allocate\_registers}
  9995. and \code{patch\_instructions}:
  9996. \begin{lstlisting}
  9997. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9998. \end{lstlisting}
  9999. \fi}
  10000. %
  10001. Run the script to test your compiler.
  10002. %
  10003. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10004. blocks on several test programs.
  10005. \end{exercise}
  10006. \section{Further Reading}
  10007. \label{sec:cond-further-reading}
  10008. The algorithm for the \code{explicate\_control} pass is based on the
  10009. \code{expose-basic-blocks} pass in the course notes of
  10010. \citet{Dybvig:2010aa}.
  10011. %
  10012. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10013. \citet{Appel:2003fk}, and is related to translations into continuation
  10014. passing
  10015. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10016. %
  10017. The treatment of conditionals in the \code{explicate\_control} pass is
  10018. similar to short-cut Boolean
  10019. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10020. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10021. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10022. \chapter{Loops and Dataflow Analysis}
  10023. \label{ch:Lwhile}
  10024. \setcounter{footnote}{0}
  10025. % TODO: define R'_8
  10026. % TODO: multi-graph
  10027. {\if\edition\racketEd
  10028. %
  10029. In this chapter we study two features that are the hallmarks of
  10030. imperative programming languages: loops and assignments to local
  10031. variables. The following example demonstrates these new features by
  10032. computing the sum of the first five positive integers:
  10033. % similar to loop_test_1.rkt
  10034. \begin{lstlisting}
  10035. (let ([sum 0])
  10036. (let ([i 5])
  10037. (begin
  10038. (while (> i 0)
  10039. (begin
  10040. (set! sum (+ sum i))
  10041. (set! i (- i 1))))
  10042. sum)))
  10043. \end{lstlisting}
  10044. The \code{while} loop consists of a condition and a
  10045. body.\footnote{The \code{while} loop is not a built-in
  10046. feature of the Racket language, but Racket includes many looping
  10047. constructs and it is straightforward to define \code{while} as a
  10048. macro.} The body is evaluated repeatedly so long as the condition
  10049. remains true.
  10050. %
  10051. The \code{set!} consists of a variable and a right-hand side
  10052. expression. The \code{set!} updates value of the variable to the
  10053. value of the right-hand side.
  10054. %
  10055. The primary purpose of both the \code{while} loop and \code{set!} is
  10056. to cause side effects, so they do not give a meaningful result
  10057. value. Instead, their result is the \code{\#<void>} value. The
  10058. expression \code{(void)} is an explicit way to create the
  10059. \code{\#<void>} value, and it has type \code{Void}. The
  10060. \code{\#<void>} value can be passed around just like other values
  10061. inside an \LangLoop{} program, and it can be compared for equality with
  10062. another \code{\#<void>} value. However, there are no other operations
  10063. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10064. Racket defines the \code{void?} predicate that returns \code{\#t}
  10065. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10066. %
  10067. \footnote{Racket's \code{Void} type corresponds to what is often
  10068. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10069. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10070. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10071. %
  10072. With the addition of side effect-producing features such as
  10073. \code{while} loop and \code{set!}, it is helpful to include a language
  10074. feature for sequencing side effects: the \code{begin} expression. It
  10075. consists of one or more subexpressions that are evaluated
  10076. left to right.
  10077. %
  10078. \fi}
  10079. {\if\edition\pythonEd\pythonColor
  10080. %
  10081. In this chapter we study loops, one of the hallmarks of imperative
  10082. programming languages. The following example demonstrates the
  10083. \code{while} loop by computing the sum of the first five positive
  10084. integers.
  10085. \begin{lstlisting}
  10086. sum = 0
  10087. i = 5
  10088. while i > 0:
  10089. sum = sum + i
  10090. i = i - 1
  10091. print(sum)
  10092. \end{lstlisting}
  10093. The \code{while} loop consists of a condition expression and a body (a
  10094. sequence of statements). The body is evaluated repeatedly so long as
  10095. the condition remains true.
  10096. %
  10097. \fi}
  10098. \section{The \LangLoop{} Language}
  10099. \newcommand{\LwhileGrammarRacket}{
  10100. \begin{array}{lcl}
  10101. \Type &::=& \key{Void}\\
  10102. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10103. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10104. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10105. \end{array}
  10106. }
  10107. \newcommand{\LwhileASTRacket}{
  10108. \begin{array}{lcl}
  10109. \Type &::=& \key{Void}\\
  10110. \Exp &::=& \SETBANG{\Var}{\Exp}
  10111. \MID \BEGIN{\Exp^{*}}{\Exp}
  10112. \MID \WHILE{\Exp}{\Exp}
  10113. \MID \VOID{}
  10114. \end{array}
  10115. }
  10116. \newcommand{\LwhileGrammarPython}{
  10117. \begin{array}{rcl}
  10118. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10119. \end{array}
  10120. }
  10121. \newcommand{\LwhileASTPython}{
  10122. \begin{array}{lcl}
  10123. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10124. \end{array}
  10125. }
  10126. \begin{figure}[tp]
  10127. \centering
  10128. \begin{tcolorbox}[colback=white]
  10129. \small
  10130. {\if\edition\racketEd
  10131. \[
  10132. \begin{array}{l}
  10133. \gray{\LintGrammarRacket{}} \\ \hline
  10134. \gray{\LvarGrammarRacket{}} \\ \hline
  10135. \gray{\LifGrammarRacket{}} \\ \hline
  10136. \LwhileGrammarRacket \\
  10137. \begin{array}{lcl}
  10138. \LangLoopM{} &::=& \Exp
  10139. \end{array}
  10140. \end{array}
  10141. \]
  10142. \fi}
  10143. {\if\edition\pythonEd\pythonColor
  10144. \[
  10145. \begin{array}{l}
  10146. \gray{\LintGrammarPython} \\ \hline
  10147. \gray{\LvarGrammarPython} \\ \hline
  10148. \gray{\LifGrammarPython} \\ \hline
  10149. \LwhileGrammarPython \\
  10150. \begin{array}{rcl}
  10151. \LangLoopM{} &::=& \Stmt^{*}
  10152. \end{array}
  10153. \end{array}
  10154. \]
  10155. \fi}
  10156. \end{tcolorbox}
  10157. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10158. \label{fig:Lwhile-concrete-syntax}
  10159. \end{figure}
  10160. \begin{figure}[tp]
  10161. \centering
  10162. \begin{tcolorbox}[colback=white]
  10163. \small
  10164. {\if\edition\racketEd
  10165. \[
  10166. \begin{array}{l}
  10167. \gray{\LintOpAST} \\ \hline
  10168. \gray{\LvarASTRacket{}} \\ \hline
  10169. \gray{\LifASTRacket{}} \\ \hline
  10170. \LwhileASTRacket{} \\
  10171. \begin{array}{lcl}
  10172. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10173. \end{array}
  10174. \end{array}
  10175. \]
  10176. \fi}
  10177. {\if\edition\pythonEd\pythonColor
  10178. \[
  10179. \begin{array}{l}
  10180. \gray{\LintASTPython} \\ \hline
  10181. \gray{\LvarASTPython} \\ \hline
  10182. \gray{\LifASTPython} \\ \hline
  10183. \LwhileASTPython \\
  10184. \begin{array}{lcl}
  10185. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10186. \end{array}
  10187. \end{array}
  10188. \]
  10189. \fi}
  10190. \end{tcolorbox}
  10191. \python{
  10192. \index{subject}{While@\texttt{While}}
  10193. }
  10194. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10195. \label{fig:Lwhile-syntax}
  10196. \end{figure}
  10197. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10198. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10199. shows the definition of its abstract syntax.
  10200. %
  10201. The definitional interpreter for \LangLoop{} is shown in
  10202. figure~\ref{fig:interp-Lwhile}.
  10203. %
  10204. {\if\edition\racketEd
  10205. %
  10206. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10207. and \code{Void}, and we make changes to the cases for \code{Var} and
  10208. \code{Let} regarding variables. To support assignment to variables and
  10209. to make their lifetimes indefinite (see the second example in
  10210. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10211. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10212. value.
  10213. %
  10214. Now we discuss the new cases. For \code{SetBang}, we find the
  10215. variable in the environment to obtain a boxed value, and then we change
  10216. it using \code{set-box!} to the result of evaluating the right-hand
  10217. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10218. %
  10219. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10220. if the result is true, (2) evaluate the body.
  10221. The result value of a \code{while} loop is also \code{\#<void>}.
  10222. %
  10223. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10224. subexpressions \itm{es} for their effects and then evaluates
  10225. and returns the result from \itm{body}.
  10226. %
  10227. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10228. %
  10229. \fi}
  10230. {\if\edition\pythonEd\pythonColor
  10231. %
  10232. We add a new case for \code{While} in the \code{interp\_stmts}
  10233. function, in which we repeatedly interpret the \code{body} so long as the
  10234. \code{test} expression remains true.
  10235. %
  10236. \fi}
  10237. \begin{figure}[tbp]
  10238. \begin{tcolorbox}[colback=white]
  10239. {\if\edition\racketEd
  10240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10241. (define interp-Lwhile-class
  10242. (class interp-Lif-class
  10243. (super-new)
  10244. (define/override ((interp-exp env) e)
  10245. (define recur (interp-exp env))
  10246. (match e
  10247. [(Let x e body)
  10248. (define new-env (dict-set env x (box (recur e))))
  10249. ((interp-exp new-env) body)]
  10250. [(Var x) (unbox (dict-ref env x))]
  10251. [(SetBang x rhs)
  10252. (set-box! (dict-ref env x) (recur rhs))]
  10253. [(WhileLoop cnd body)
  10254. (define (loop)
  10255. (cond [(recur cnd) (recur body) (loop)]
  10256. [else (void)]))
  10257. (loop)]
  10258. [(Begin es body)
  10259. (for ([e es]) (recur e))
  10260. (recur body)]
  10261. [(Void) (void)]
  10262. [else ((super interp-exp env) e)]))
  10263. ))
  10264. (define (interp-Lwhile p)
  10265. (send (new interp-Lwhile-class) interp-program p))
  10266. \end{lstlisting}
  10267. \fi}
  10268. {\if\edition\pythonEd\pythonColor
  10269. \begin{lstlisting}
  10270. class InterpLwhile(InterpLif):
  10271. def interp_stmt(self, s, env, cont):
  10272. match s:
  10273. case While(test, body, []):
  10274. if self.interp_exp(test, env):
  10275. self.interp_stmts(body + [s] + cont, env)
  10276. else:
  10277. return self.interp_stmts(cont, env)
  10278. case _:
  10279. return super().interp_stmt(s, env, cont)
  10280. \end{lstlisting}
  10281. \fi}
  10282. \end{tcolorbox}
  10283. \caption{Interpreter for \LangLoop{}.}
  10284. \label{fig:interp-Lwhile}
  10285. \end{figure}
  10286. The definition of the type checker for \LangLoop{} is shown in
  10287. figure~\ref{fig:type-check-Lwhile}.
  10288. %
  10289. {\if\edition\racketEd
  10290. %
  10291. The type checking of the \code{SetBang} expression requires the type
  10292. of the variable and the right-hand side to agree. The result type is
  10293. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10294. and the result type is \code{Void}. For \code{Begin}, the result type
  10295. is the type of its last subexpression.
  10296. %
  10297. \fi}
  10298. %
  10299. {\if\edition\pythonEd\pythonColor
  10300. %
  10301. A \code{while} loop is well typed if the type of the \code{test}
  10302. expression is \code{bool} and the statements in the \code{body} are
  10303. well typed.
  10304. %
  10305. \fi}
  10306. \begin{figure}[tbp]
  10307. \begin{tcolorbox}[colback=white]
  10308. {\if\edition\racketEd
  10309. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10310. (define type-check-Lwhile-class
  10311. (class type-check-Lif-class
  10312. (super-new)
  10313. (inherit check-type-equal?)
  10314. (define/override (type-check-exp env)
  10315. (lambda (e)
  10316. (define recur (type-check-exp env))
  10317. (match e
  10318. [(SetBang x rhs)
  10319. (define-values (rhs^ rhsT) (recur rhs))
  10320. (define varT (dict-ref env x))
  10321. (check-type-equal? rhsT varT e)
  10322. (values (SetBang x rhs^) 'Void)]
  10323. [(WhileLoop cnd body)
  10324. (define-values (cnd^ Tc) (recur cnd))
  10325. (check-type-equal? Tc 'Boolean e)
  10326. (define-values (body^ Tbody) ((type-check-exp env) body))
  10327. (values (WhileLoop cnd^ body^) 'Void)]
  10328. [(Begin es body)
  10329. (define-values (es^ ts)
  10330. (for/lists (l1 l2) ([e es]) (recur e)))
  10331. (define-values (body^ Tbody) (recur body))
  10332. (values (Begin es^ body^) Tbody)]
  10333. [else ((super type-check-exp env) e)])))
  10334. ))
  10335. (define (type-check-Lwhile p)
  10336. (send (new type-check-Lwhile-class) type-check-program p))
  10337. \end{lstlisting}
  10338. \fi}
  10339. {\if\edition\pythonEd\pythonColor
  10340. \begin{lstlisting}
  10341. class TypeCheckLwhile(TypeCheckLif):
  10342. def type_check_stmts(self, ss, env):
  10343. if len(ss) == 0:
  10344. return
  10345. match ss[0]:
  10346. case While(test, body, []):
  10347. test_t = self.type_check_exp(test, env)
  10348. check_type_equal(bool, test_t, test)
  10349. body_t = self.type_check_stmts(body, env)
  10350. return self.type_check_stmts(ss[1:], env)
  10351. case _:
  10352. return super().type_check_stmts(ss, env)
  10353. \end{lstlisting}
  10354. \fi}
  10355. \end{tcolorbox}
  10356. \caption{Type checker for the \LangLoop{} language.}
  10357. \label{fig:type-check-Lwhile}
  10358. \end{figure}
  10359. {\if\edition\racketEd
  10360. %
  10361. At first glance, the translation of these language features to x86
  10362. seems straightforward because the \LangCIf{} intermediate language
  10363. already supports all the ingredients that we need: assignment,
  10364. \code{goto}, conditional branching, and sequencing. However,
  10365. complications arise, which we discuss in the next section. After
  10366. that we introduce the changes necessary to the existing passes.
  10367. %
  10368. \fi}
  10369. {\if\edition\pythonEd\pythonColor
  10370. %
  10371. At first glance, the translation of \code{while} loops to x86 seems
  10372. straightforward because the \LangCIf{} intermediate language already
  10373. supports \code{goto} and conditional branching. However, there are
  10374. complications that arise which we discuss in the next section. After
  10375. that we introduce the changes necessary to the existing passes.
  10376. %
  10377. \fi}
  10378. \section{Cyclic Control Flow and Dataflow Analysis}
  10379. \label{sec:dataflow-analysis}
  10380. Up until this point, the programs generated in
  10381. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10382. \code{while} loop introduces a cycle. Does that matter?
  10383. %
  10384. Indeed, it does. Recall that for register allocation, the compiler
  10385. performs liveness analysis to determine which variables can share the
  10386. same register. To accomplish this, we analyzed the control-flow graph
  10387. in reverse topological order
  10388. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10389. well defined only for acyclic graphs.
  10390. Let us return to the example of computing the sum of the first five
  10391. positive integers. Here is the program after instruction
  10392. selection\index{subject}{instruction selection} but before register
  10393. allocation.
  10394. \begin{center}
  10395. {\if\edition\racketEd
  10396. \begin{minipage}{0.45\textwidth}
  10397. \begin{lstlisting}
  10398. (define (main) : Integer
  10399. mainstart:
  10400. movq $0, sum
  10401. movq $5, i
  10402. jmp block5
  10403. block5:
  10404. movq i, tmp3
  10405. cmpq tmp3, $0
  10406. jl block7
  10407. jmp block8
  10408. \end{lstlisting}
  10409. \end{minipage}
  10410. \begin{minipage}{0.45\textwidth}
  10411. \begin{lstlisting}
  10412. block7:
  10413. addq i, sum
  10414. movq $1, tmp4
  10415. negq tmp4
  10416. addq tmp4, i
  10417. jmp block5
  10418. block8:
  10419. movq $27, %rax
  10420. addq sum, %rax
  10421. jmp mainconclusion)
  10422. \end{lstlisting}
  10423. \end{minipage}
  10424. \fi}
  10425. {\if\edition\pythonEd\pythonColor
  10426. \begin{minipage}{0.45\textwidth}
  10427. \begin{lstlisting}
  10428. mainstart:
  10429. movq $0, sum
  10430. movq $5, i
  10431. jmp block5
  10432. block5:
  10433. cmpq $0, i
  10434. jg block7
  10435. jmp block8
  10436. \end{lstlisting}
  10437. \end{minipage}
  10438. \begin{minipage}{0.45\textwidth}
  10439. \begin{lstlisting}
  10440. block7:
  10441. addq i, sum
  10442. subq $1, i
  10443. jmp block5
  10444. block8:
  10445. movq sum, %rdi
  10446. callq print_int
  10447. movq $0, %rax
  10448. jmp mainconclusion
  10449. \end{lstlisting}
  10450. \end{minipage}
  10451. \fi}
  10452. \end{center}
  10453. Recall that liveness analysis works backward, starting at the end
  10454. of each function. For this example we could start with \code{block8}
  10455. because we know what is live at the beginning of the conclusion:
  10456. only \code{rax} and \code{rsp}. So the live-before set
  10457. for \code{block8} is \code{\{rsp,sum\}}.
  10458. %
  10459. Next we might try to analyze \code{block5} or \code{block7}, but
  10460. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10461. we are stuck.
  10462. The way out of this impasse is to realize that we can compute an
  10463. underapproximation of each live-before set by starting with empty
  10464. live-after sets. By \emph{underapproximation}, we mean that the set
  10465. contains only variables that are live for some execution of the
  10466. program, but the set may be missing some variables that are live.
  10467. Next, the underapproximations for each block can be improved by (1)
  10468. updating the live-after set for each block using the approximate
  10469. live-before sets from the other blocks, and (2) performing liveness
  10470. analysis again on each block. In fact, by iterating this process, the
  10471. underapproximations eventually become the correct solutions!
  10472. %
  10473. This approach of iteratively analyzing a control-flow graph is
  10474. applicable to many static analysis problems and goes by the name
  10475. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10476. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10477. Washington.
  10478. Let us apply this approach to the previously presented example. We use
  10479. the empty set for the initial live-before set for each block. Let
  10480. $m_0$ be the following mapping from label names to sets of locations
  10481. (variables and registers):
  10482. \begin{center}
  10483. \begin{lstlisting}
  10484. mainstart: {}, block5: {}, block7: {}, block8: {}
  10485. \end{lstlisting}
  10486. \end{center}
  10487. Using the above live-before approximations, we determine the
  10488. live-after for each block and then apply liveness analysis to each
  10489. block. This produces our next approximation $m_1$ of the live-before
  10490. sets.
  10491. \begin{center}
  10492. \begin{lstlisting}
  10493. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10494. \end{lstlisting}
  10495. \end{center}
  10496. For the second round, the live-after for \code{mainstart} is the
  10497. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10498. the liveness analysis for \code{mainstart} computes the empty set. The
  10499. live-after for \code{block5} is the union of the live-before sets for
  10500. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10501. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10502. sum\}}. The live-after for \code{block7} is the live-before for
  10503. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10504. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10505. Together these yield the following approximation $m_2$ of
  10506. the live-before sets:
  10507. \begin{center}
  10508. \begin{lstlisting}
  10509. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10510. \end{lstlisting}
  10511. \end{center}
  10512. In the preceding iteration, only \code{block5} changed, so we can
  10513. limit our attention to \code{mainstart} and \code{block7}, the two
  10514. blocks that jump to \code{block5}. As a result, the live-before sets
  10515. for \code{mainstart} and \code{block7} are updated to include
  10516. \code{rsp}, yielding the following approximation $m_3$:
  10517. \begin{center}
  10518. \begin{lstlisting}
  10519. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10520. \end{lstlisting}
  10521. \end{center}
  10522. Because \code{block7} changed, we analyze \code{block5} once more, but
  10523. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10524. our approximations have converged, so $m_3$ is the solution.
  10525. This iteration process is guaranteed to converge to a solution by the
  10526. Kleene fixed-point theorem, a general theorem about functions on
  10527. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10528. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10529. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10530. join operator
  10531. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10532. will be working with join semilattices.} When two elements are
  10533. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10534. as much information as $m_i$, so we can think of $m_j$ as a
  10535. better-than-or-equal-to approximation in relation to $m_i$. The
  10536. bottom element $\bot$ represents the complete lack of information,
  10537. that is, the worst approximation. The join operator takes two lattice
  10538. elements and combines their information; that is, it produces the
  10539. least upper bound of the two.\index{subject}{least upper bound}
  10540. A dataflow analysis typically involves two lattices: one lattice to
  10541. represent abstract states and another lattice that aggregates the
  10542. abstract states of all the blocks in the control-flow graph. For
  10543. liveness analysis, an abstract state is a set of locations. We form
  10544. the lattice $L$ by taking its elements to be sets of locations, the
  10545. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10546. set, and the join operator to be set union.
  10547. %
  10548. We form a second lattice $M$ by taking its elements to be mappings
  10549. from the block labels to sets of locations (elements of $L$). We
  10550. order the mappings point-wise, using the ordering of $L$. So, given any
  10551. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10552. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10553. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10554. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10555. We can think of one iteration of liveness analysis applied to the
  10556. whole program as being a function $f$ on the lattice $M$. It takes a
  10557. mapping as input and computes a new mapping.
  10558. \[
  10559. f(m_i) = m_{i+1}
  10560. \]
  10561. Next let us think for a moment about what a final solution $m_s$
  10562. should look like. If we perform liveness analysis using the solution
  10563. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10564. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10565. \[
  10566. f(m_s) = m_s
  10567. \]
  10568. Furthermore, the solution should include only locations that are
  10569. forced to be there by performing liveness analysis on the program, so
  10570. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10571. The Kleene fixed-point theorem states that if a function $f$ is
  10572. monotone (better inputs produce better outputs), then the least fixed
  10573. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10574. chain} obtained by starting at $\bot$ and iterating $f$, as
  10575. follows:\index{subject}{Kleene fixed-point theorem}
  10576. \[
  10577. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10578. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10579. \]
  10580. When a lattice contains only finitely long ascending chains, then
  10581. every Kleene chain tops out at some fixed point after some number of
  10582. iterations of $f$.
  10583. \[
  10584. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10585. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10586. \]
  10587. The liveness analysis is indeed a monotone function and the lattice
  10588. $M$ has finitely long ascending chains because there are only a
  10589. finite number of variables and blocks in the program. Thus we are
  10590. guaranteed that iteratively applying liveness analysis to all blocks
  10591. in the program will eventually produce the least fixed point solution.
  10592. Next let us consider dataflow analysis in general and discuss the
  10593. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10594. %
  10595. The algorithm has four parameters: the control-flow graph \code{G}, a
  10596. function \code{transfer} that applies the analysis to one block, and the
  10597. \code{bottom} and \code{join} operators for the lattice of abstract
  10598. states. The \code{analyze\_dataflow} function is formulated as a
  10599. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10600. function come from the predecessor nodes in the control-flow
  10601. graph. However, liveness analysis is a \emph{backward} dataflow
  10602. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10603. function with the transpose of the control-flow graph.
  10604. The algorithm begins by creating the bottom mapping, represented by a
  10605. hash table. It then pushes all the nodes in the control-flow graph
  10606. onto the work list (a queue). The algorithm repeats the \code{while}
  10607. loop as long as there are items in the work list. In each iteration, a
  10608. node is popped from the work list and processed. The \code{input} for
  10609. the node is computed by taking the join of the abstract states of all
  10610. the predecessor nodes. The \code{transfer} function is then applied to
  10611. obtain the \code{output} abstract state. If the output differs from
  10612. the previous state for this block, the mapping for this block is
  10613. updated and its successor nodes are pushed onto the work list.
  10614. \begin{figure}[tb]
  10615. \begin{tcolorbox}[colback=white]
  10616. {\if\edition\racketEd
  10617. \begin{lstlisting}
  10618. (define (analyze_dataflow G transfer bottom join)
  10619. (define mapping (make-hash))
  10620. (for ([v (in-vertices G)])
  10621. (dict-set! mapping v bottom))
  10622. (define worklist (make-queue))
  10623. (for ([v (in-vertices G)])
  10624. (enqueue! worklist v))
  10625. (define trans-G (transpose G))
  10626. (while (not (queue-empty? worklist))
  10627. (define node (dequeue! worklist))
  10628. (define input (for/fold ([state bottom])
  10629. ([pred (in-neighbors trans-G node)])
  10630. (join state (dict-ref mapping pred))))
  10631. (define output (transfer node input))
  10632. (cond [(not (equal? output (dict-ref mapping node)))
  10633. (dict-set! mapping node output)
  10634. (for ([v (in-neighbors G node)])
  10635. (enqueue! worklist v))]))
  10636. mapping)
  10637. \end{lstlisting}
  10638. \fi}
  10639. {\if\edition\pythonEd\pythonColor
  10640. \begin{lstlisting}
  10641. def analyze_dataflow(G, transfer, bottom, join):
  10642. trans_G = transpose(G)
  10643. mapping = dict((v, bottom) for v in G.vertices())
  10644. worklist = deque(G.vertices)
  10645. while worklist:
  10646. node = worklist.pop()
  10647. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10648. input = reduce(join, inputs, bottom)
  10649. output = transfer(node, input)
  10650. if output != mapping[node]:
  10651. mapping[node] = output
  10652. worklist.extend(G.adjacent(node))
  10653. \end{lstlisting}
  10654. \fi}
  10655. \end{tcolorbox}
  10656. \caption{Generic work list algorithm for dataflow analysis.}
  10657. \label{fig:generic-dataflow}
  10658. \end{figure}
  10659. {\if\edition\racketEd
  10660. \section{Mutable Variables and Remove Complex Operands}
  10661. There is a subtle interaction between the
  10662. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10663. and the left-to-right order of evaluation of Racket. Consider the
  10664. following example:
  10665. \begin{lstlisting}
  10666. (let ([x 2])
  10667. (+ x (begin (set! x 40) x)))
  10668. \end{lstlisting}
  10669. The result of this program is \code{42} because the first read from
  10670. \code{x} produces \code{2} and the second produces \code{40}. However,
  10671. if we naively apply the \code{remove\_complex\_operands} pass to this
  10672. example we obtain the following program whose result is \code{80}!
  10673. \begin{lstlisting}
  10674. (let ([x 2])
  10675. (let ([tmp (begin (set! x 40) x)])
  10676. (+ x tmp)))
  10677. \end{lstlisting}
  10678. The problem is that with mutable variables, the ordering between
  10679. reads and writes is important, and the
  10680. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10681. before the first read of \code{x}.
  10682. We recommend solving this problem by giving special treatment to reads
  10683. from mutable variables, that is, variables that occur on the left-hand
  10684. side of a \code{set!}. We mark each read from a mutable variable with
  10685. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10686. that the read operation is effectful in that it can produce different
  10687. results at different points in time. Let's apply this idea to the
  10688. following variation that also involves a variable that is not mutated:
  10689. % loop_test_24.rkt
  10690. \begin{lstlisting}
  10691. (let ([x 2])
  10692. (let ([y 0])
  10693. (+ y (+ x (begin (set! x 40) x)))))
  10694. \end{lstlisting}
  10695. We first analyze this program to discover that variable \code{x}
  10696. is mutable but \code{y} is not. We then transform the program as
  10697. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10698. \begin{lstlisting}
  10699. (let ([x 2])
  10700. (let ([y 0])
  10701. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10702. \end{lstlisting}
  10703. Now that we have a clear distinction between reads from mutable and
  10704. immutable variables, we can apply the \code{remove\_complex\_operands}
  10705. pass, where reads from immutable variables are still classified as
  10706. atomic expressions but reads from mutable variables are classified as
  10707. complex. Thus, \code{remove\_complex\_operands} yields the following
  10708. program:\\
  10709. \begin{minipage}{\textwidth}
  10710. \begin{lstlisting}
  10711. (let ([x 2])
  10712. (let ([y 0])
  10713. (let ([t1 x])
  10714. (let ([t2 (begin (set! x 40) x)])
  10715. (let ([t3 (+ t1 t2)])
  10716. (+ y t3))))))
  10717. \end{lstlisting}
  10718. \end{minipage}
  10719. The temporary variable \code{t1} gets the value of \code{x} before the
  10720. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10721. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10722. do not generate a temporary variable for the occurrence of \code{y}
  10723. because it's an immutable variable. We want to avoid such unnecessary
  10724. extra temporaries because they would needlessly increase the number of
  10725. variables, making it more likely for some of them to be spilled. The
  10726. result of this program is \code{42}, the same as the result prior to
  10727. \code{remove\_complex\_operands}.
  10728. The approach that we've sketched requires only a small
  10729. modification to \code{remove\_complex\_operands} to handle
  10730. \code{get!}. However, it requires a new pass, called
  10731. \code{uncover-get!}, that we discuss in
  10732. section~\ref{sec:uncover-get-bang}.
  10733. As an aside, this problematic interaction between \code{set!} and the
  10734. pass \code{remove\_complex\_operands} is particular to Racket and not
  10735. its predecessor, the Scheme language. The key difference is that
  10736. Scheme does not specify an order of evaluation for the arguments of an
  10737. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10738. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10739. would be correct results for the example program. Interestingly,
  10740. Racket is implemented on top of the Chez Scheme
  10741. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10742. presented in this section (using extra \code{let} bindings to control
  10743. the order of evaluation) is used in the translation from Racket to
  10744. Scheme~\citep{Flatt:2019tb}.
  10745. \fi} % racket
  10746. Having discussed the complications that arise from adding support for
  10747. assignment and loops, we turn to discussing the individual compilation
  10748. passes.
  10749. {\if\edition\racketEd
  10750. \section{Uncover \texttt{get!}}
  10751. \label{sec:uncover-get-bang}
  10752. The goal of this pass is to mark uses of mutable variables so that
  10753. \code{remove\_complex\_operands} can treat them as complex expressions
  10754. and thereby preserve their ordering relative to the side effects in
  10755. other operands. So, the first step is to collect all the mutable
  10756. variables. We recommend creating an auxiliary function for this,
  10757. named \code{collect-set!}, that recursively traverses expressions,
  10758. returning the set of all variables that occur on the left-hand side of a
  10759. \code{set!}. Here's an excerpt of its implementation.
  10760. \begin{center}
  10761. \begin{minipage}{\textwidth}
  10762. \begin{lstlisting}
  10763. (define (collect-set! e)
  10764. (match e
  10765. [(Var x) (set)]
  10766. [(Int n) (set)]
  10767. [(Let x rhs body)
  10768. (set-union (collect-set! rhs) (collect-set! body))]
  10769. [(SetBang var rhs)
  10770. (set-union (set var) (collect-set! rhs))]
  10771. ...))
  10772. \end{lstlisting}
  10773. \end{minipage}
  10774. \end{center}
  10775. By placing this pass after \code{uniquify}, we need not worry about
  10776. variable shadowing, and our logic for \code{Let} can remain simple, as
  10777. in this excerpt.
  10778. The second step is to mark the occurrences of the mutable variables
  10779. with the new \code{GetBang} AST node (\code{get!} in concrete
  10780. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10781. function, which takes two parameters: the set of mutable variables
  10782. \code{set!-vars} and the expression \code{e} to be processed. The
  10783. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10784. mutable variable or leaves it alone if not.
  10785. \begin{center}
  10786. \begin{minipage}{\textwidth}
  10787. \begin{lstlisting}
  10788. (define ((uncover-get!-exp set!-vars) e)
  10789. (match e
  10790. [(Var x)
  10791. (if (set-member? set!-vars x)
  10792. (GetBang x)
  10793. (Var x))]
  10794. ...))
  10795. \end{lstlisting}
  10796. \end{minipage}
  10797. \end{center}
  10798. To wrap things up, define the \code{uncover-get!} function for
  10799. processing a whole program, using \code{collect-set!} to obtain the
  10800. set of mutable variables and then \code{uncover-get!-exp} to replace
  10801. their occurrences with \code{GetBang}.
  10802. \fi}
  10803. \section{Remove Complex Operands}
  10804. \label{sec:rco-loop}
  10805. {\if\edition\racketEd
  10806. %
  10807. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10808. \code{while} are all complex expressions. The subexpressions of
  10809. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10810. %
  10811. \fi}
  10812. {\if\edition\pythonEd\pythonColor
  10813. %
  10814. The change needed for this pass is to add a case for the \code{while}
  10815. statement. The condition of a \code{while} loop is allowed to be a
  10816. complex expression, just like the condition of the \code{if}
  10817. statement.
  10818. %
  10819. \fi}
  10820. %
  10821. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10822. \LangLoopANF{} of this pass.
  10823. \newcommand{\LwhileMonadASTRacket}{
  10824. \begin{array}{rcl}
  10825. \Atm &::=& \VOID{} \\
  10826. \Exp &::=& \GETBANG{\Var}
  10827. \MID \SETBANG{\Var}{\Exp}
  10828. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10829. &\MID& \WHILE{\Exp}{\Exp}
  10830. \end{array}
  10831. }
  10832. \newcommand{\LwhileMonadASTPython}{
  10833. \begin{array}{rcl}
  10834. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10835. \end{array}
  10836. }
  10837. \begin{figure}[tp]
  10838. \centering
  10839. \begin{tcolorbox}[colback=white]
  10840. \small
  10841. {\if\edition\racketEd
  10842. \[
  10843. \begin{array}{l}
  10844. \gray{\LvarMonadASTRacket} \\ \hline
  10845. \gray{\LifMonadASTRacket} \\ \hline
  10846. \LwhileMonadASTRacket \\
  10847. \begin{array}{rcl}
  10848. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10849. \end{array}
  10850. \end{array}
  10851. \]
  10852. \fi}
  10853. {\if\edition\pythonEd\pythonColor
  10854. \[
  10855. \begin{array}{l}
  10856. \gray{\LvarMonadASTPython} \\ \hline
  10857. \gray{\LifMonadASTPython} \\ \hline
  10858. \LwhileMonadASTPython \\
  10859. \begin{array}{rcl}
  10860. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10861. \end{array}
  10862. \end{array}
  10863. \]
  10864. \fi}
  10865. \end{tcolorbox}
  10866. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10867. \label{fig:Lwhile-anf-syntax}
  10868. \end{figure}
  10869. {\if\edition\racketEd
  10870. %
  10871. As usual, when a complex expression appears in a grammar position that
  10872. needs to be atomic, such as the argument of a primitive operator, we
  10873. must introduce a temporary variable and bind it to the complex
  10874. expression. This approach applies, unchanged, to handle the new
  10875. language forms. For example, in the following code there are two
  10876. \code{begin} expressions appearing as arguments to the \code{+}
  10877. operator. The output of \code{rco\_exp} is then shown, in which the
  10878. \code{begin} expressions have been bound to temporary
  10879. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10880. allowed to have arbitrary expressions in their right-hand side
  10881. expression, so it is fine to place \code{begin} there.
  10882. %
  10883. \begin{center}
  10884. \begin{tabular}{lcl}
  10885. \begin{minipage}{0.4\textwidth}
  10886. \begin{lstlisting}
  10887. (let ([x2 10])
  10888. (let ([y3 0])
  10889. (+ (+ (begin
  10890. (set! y3 (read))
  10891. (get! x2))
  10892. (begin
  10893. (set! x2 (read))
  10894. (get! y3)))
  10895. (get! x2))))
  10896. \end{lstlisting}
  10897. \end{minipage}
  10898. &
  10899. $\Rightarrow$
  10900. &
  10901. \begin{minipage}{0.4\textwidth}
  10902. \begin{lstlisting}
  10903. (let ([x2 10])
  10904. (let ([y3 0])
  10905. (let ([tmp4 (begin
  10906. (set! y3 (read))
  10907. x2)])
  10908. (let ([tmp5 (begin
  10909. (set! x2 (read))
  10910. y3)])
  10911. (let ([tmp6 (+ tmp4 tmp5)])
  10912. (let ([tmp7 x2])
  10913. (+ tmp6 tmp7)))))))
  10914. \end{lstlisting}
  10915. \end{minipage}
  10916. \end{tabular}
  10917. \end{center}
  10918. \fi}
  10919. \section{Explicate Control \racket{and \LangCLoop{}}}
  10920. \label{sec:explicate-loop}
  10921. \newcommand{\CloopASTRacket}{
  10922. \begin{array}{lcl}
  10923. \Atm &::=& \VOID \\
  10924. \Stmt &::=& \READ{}
  10925. \end{array}
  10926. }
  10927. {\if\edition\racketEd
  10928. Recall that in the \code{explicate\_control} pass we define one helper
  10929. function for each kind of position in the program. For the \LangVar{}
  10930. language of integers and variables, we needed assignment and tail
  10931. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10932. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10933. another kind of position: effect position. Except for the last
  10934. subexpression, the subexpressions inside a \code{begin} are evaluated
  10935. only for their effect. Their result values are discarded. We can
  10936. generate better code by taking this fact into account.
  10937. The output language of \code{explicate\_control} is \LangCLoop{}
  10938. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10939. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10940. and that \code{read} may appear as a statement. The most significant
  10941. difference between the programs generated by \code{explicate\_control}
  10942. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10943. chapter is that the control-flow graphs of the latter may contain
  10944. cycles.
  10945. \begin{figure}[tp]
  10946. \begin{tcolorbox}[colback=white]
  10947. \small
  10948. \[
  10949. \begin{array}{l}
  10950. \gray{\CvarASTRacket} \\ \hline
  10951. \gray{\CifASTRacket} \\ \hline
  10952. \CloopASTRacket \\
  10953. \begin{array}{lcl}
  10954. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10955. \end{array}
  10956. \end{array}
  10957. \]
  10958. \end{tcolorbox}
  10959. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10960. \label{fig:c7-syntax}
  10961. \end{figure}
  10962. The new auxiliary function \code{explicate\_effect} takes an
  10963. expression (in an effect position) and the code for its
  10964. continuation. The function returns a $\Tail$ that includes the
  10965. generated code for the input expression followed by the
  10966. continuation. If the expression is obviously pure, that is, never
  10967. causes side effects, then the expression can be removed, so the result
  10968. is just the continuation.
  10969. %
  10970. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10971. interesting; the generated code is depicted in the following diagram:
  10972. \begin{center}
  10973. \begin{minipage}{0.3\textwidth}
  10974. \xymatrix{
  10975. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10976. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10977. & *+[F]{\txt{\itm{cont}}} \\
  10978. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10979. }
  10980. \end{minipage}
  10981. \end{center}
  10982. We start by creating a fresh label $\itm{loop}$ for the top of the
  10983. loop. Next, recursively process the \itm{body} (in effect position)
  10984. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10985. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10986. \itm{body'} as the \emph{then} branch and the continuation block as the
  10987. \emph{else} branch. The result should be added to the dictionary of
  10988. \code{basic-blocks} with the label \itm{loop}. The result for the
  10989. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10990. The auxiliary functions for tail, assignment, and predicate positions
  10991. need to be updated. The three new language forms, \code{while},
  10992. \code{set!}, and \code{begin}, can appear in assignment and tail
  10993. positions. Only \code{begin} may appear in predicate positions; the
  10994. other two have result type \code{Void}.
  10995. \fi}
  10996. %
  10997. {\if\edition\pythonEd\pythonColor
  10998. %
  10999. The output of this pass is the language \LangCIf{}. No new language
  11000. features are needed in the output, because a \code{while} loop can be
  11001. expressed in terms of \code{goto} and \code{if} statements, which are
  11002. already in \LangCIf{}.
  11003. %
  11004. Add a case for the \code{while} statement to the
  11005. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11006. the condition expression.
  11007. %
  11008. \fi}
  11009. {\if\edition\racketEd
  11010. \section{Select Instructions}
  11011. \label{sec:select-instructions-loop}
  11012. \index{subject}{select instructions}
  11013. Only two small additions are needed in the \code{select\_instructions}
  11014. pass to handle the changes to \LangCLoop{}. First, to handle the
  11015. addition of \VOID{} we simply translate it to \code{0}. Second,
  11016. \code{read} may appear as a stand-alone statement instead of
  11017. appearing only on the right-hand side of an assignment statement. The code
  11018. generation is nearly identical to the one for assignment; just leave
  11019. off the instruction for moving the result into the left-hand side.
  11020. \fi}
  11021. \section{Register Allocation}
  11022. \label{sec:register-allocation-loop}
  11023. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11024. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11025. which complicates the liveness analysis needed for register
  11026. allocation.
  11027. %
  11028. We recommend using the generic \code{analyze\_dataflow} function that
  11029. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11030. perform liveness analysis, replacing the code in
  11031. \code{uncover\_live} that processed the basic blocks in topological
  11032. order (section~\ref{sec:liveness-analysis-Lif}).
  11033. The \code{analyze\_dataflow} function has the following four parameters.
  11034. \begin{enumerate}
  11035. \item The first parameter \code{G} should be passed the transpose
  11036. of the control-flow graph.
  11037. \item The second parameter \code{transfer} should be passed a function
  11038. that applies liveness analysis to a basic block. It takes two
  11039. parameters: the label for the block to analyze and the live-after
  11040. set for that block. The transfer function should return the
  11041. live-before set for the block.
  11042. %
  11043. \racket{Also, as a side effect, it should update the block's
  11044. $\itm{info}$ with the liveness information for each instruction.}
  11045. %
  11046. \python{Also, as a side effect, it should update the live-before and
  11047. live-after sets for each instruction.}
  11048. %
  11049. To implement the \code{transfer} function, you should be able to
  11050. reuse the code you already have for analyzing basic blocks.
  11051. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11052. \code{bottom} and \code{join} for the lattice of abstract states,
  11053. that is, sets of locations. For liveness analysis, the bottom of the
  11054. lattice is the empty set, and the join operator is set union.
  11055. \end{enumerate}
  11056. \begin{figure}[tp]
  11057. \begin{tcolorbox}[colback=white]
  11058. {\if\edition\racketEd
  11059. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11060. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11061. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11062. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11063. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11064. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11065. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11066. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11067. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11068. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11069. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11070. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11071. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11072. \path[->,bend left=15] (Lfun) edge [above] node
  11073. {\ttfamily\footnotesize shrink} (Lfun-2);
  11074. \path[->,bend left=15] (Lfun-2) edge [above] node
  11075. {\ttfamily\footnotesize uniquify} (F1-4);
  11076. \path[->,bend left=15] (F1-4) edge [above] node
  11077. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11078. \path[->,bend left=15] (F1-5) edge [left] node
  11079. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11080. \path[->,bend left=10] (F1-6) edge [above] node
  11081. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11082. \path[->,bend left=15] (C3-2) edge [right] node
  11083. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11084. \path[->,bend right=15] (x86-2) edge [right] node
  11085. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11086. \path[->,bend right=15] (x86-2-1) edge [below] node
  11087. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11088. \path[->,bend right=15] (x86-2-2) edge [right] node
  11089. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11090. \path[->,bend left=15] (x86-3) edge [above] node
  11091. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11092. \path[->,bend left=15] (x86-4) edge [right] node
  11093. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11094. \end{tikzpicture}
  11095. \fi}
  11096. {\if\edition\pythonEd\pythonColor
  11097. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11098. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11099. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11100. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11101. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11102. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11103. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11104. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11105. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11106. \path[->,bend left=15] (Lfun) edge [above] node
  11107. {\ttfamily\footnotesize shrink} (Lfun-2);
  11108. \path[->,bend left=15] (Lfun-2) edge [above] node
  11109. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11110. \path[->,bend left=10] (F1-6) edge [right] node
  11111. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11112. \path[->,bend right=15] (C3-2) edge [right] node
  11113. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11114. \path[->,bend right=15] (x86-2) edge [below] node
  11115. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11116. \path[->,bend left=15] (x86-3) edge [above] node
  11117. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11118. \path[->,bend right=15] (x86-4) edge [below] node
  11119. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11120. \end{tikzpicture}
  11121. \fi}
  11122. \end{tcolorbox}
  11123. \caption{Diagram of the passes for \LangLoop{}.}
  11124. \label{fig:Lwhile-passes}
  11125. \end{figure}
  11126. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11127. for the compilation of \LangLoop{}.
  11128. % Further Reading: dataflow analysis
  11129. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11130. \chapter{Tuples and Garbage Collection}
  11131. \label{ch:Lvec}
  11132. \index{subject}{tuple}
  11133. \index{subject}{vector}
  11134. \setcounter{footnote}{0}
  11135. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11136. %% all the IR grammars are spelled out! \\ --Jeremy}
  11137. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11138. %% the root stack. \\ --Jeremy}
  11139. In this chapter we study the implementation of tuples\racket{, called
  11140. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11141. in which each element may have a different type.
  11142. %
  11143. This language feature is the first to use the computer's
  11144. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11145. indefinite; that is, a tuple lives forever from the programmer's
  11146. viewpoint. Of course, from an implementer's viewpoint, it is important
  11147. to reclaim the space associated with a tuple when it is no longer
  11148. needed, which is why we also study \emph{garbage collection}
  11149. \index{subject}{garbage collection} techniques in this chapter.
  11150. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11151. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11152. language (chapter~\ref{ch:Lwhile}) with tuples.
  11153. %
  11154. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11155. copying live tuples back and forth between two halves of the heap. The
  11156. garbage collector requires coordination with the compiler so that it
  11157. can find all the live tuples.
  11158. %
  11159. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11160. discuss the necessary changes and additions to the compiler passes,
  11161. including a new compiler pass named \code{expose\_allocation}.
  11162. \section{The \LangVec{} Language}
  11163. \label{sec:r3}
  11164. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11165. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11166. the definition of the abstract syntax.
  11167. %
  11168. \racket{The \LangVec{} language includes the forms \code{vector} for
  11169. creating a tuple, \code{vector-ref} for reading an element of a
  11170. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11171. \code{vector-length} for obtaining the number of elements of a
  11172. tuple.}
  11173. %
  11174. \python{The \LangVec{} language adds (1) tuple creation via a
  11175. comma-separated list of expressions; (2) accessing an element of a
  11176. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11177. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11178. comparison operator; and (4) obtaining the number of elements (the
  11179. length) of a tuple. In this chapter, we restrict access indices to
  11180. constant integers.}
  11181. %
  11182. The following program shows an example of the use of tuples. It creates a tuple
  11183. \code{t} containing the elements \code{40},
  11184. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11185. contains just \code{2}. The element at index $1$ of \code{t} is
  11186. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11187. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11188. to which we add \code{2}, the element at index $0$ of the tuple.
  11189. The result of the program is \code{42}.
  11190. %
  11191. {\if\edition\racketEd
  11192. \begin{lstlisting}
  11193. (let ([t (vector 40 #t (vector 2))])
  11194. (if (vector-ref t 1)
  11195. (+ (vector-ref t 0)
  11196. (vector-ref (vector-ref t 2) 0))
  11197. 44))
  11198. \end{lstlisting}
  11199. \fi}
  11200. {\if\edition\pythonEd\pythonColor
  11201. \begin{lstlisting}
  11202. t = 40, True, (2,)
  11203. print(t[0] + t[2][0] if t[1] else 44)
  11204. \end{lstlisting}
  11205. \fi}
  11206. \newcommand{\LtupGrammarRacket}{
  11207. \begin{array}{lcl}
  11208. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11209. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11210. \MID \LP\key{vector-length}\;\Exp\RP \\
  11211. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11212. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11213. \end{array}
  11214. }
  11215. \newcommand{\LtupASTRacket}{
  11216. \begin{array}{lcl}
  11217. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11218. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11219. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11220. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11221. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11222. \end{array}
  11223. }
  11224. \newcommand{\LtupGrammarPython}{
  11225. \begin{array}{rcl}
  11226. \itm{cmp} &::= & \key{is} \\
  11227. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11228. \end{array}
  11229. }
  11230. \newcommand{\LtupASTPython}{
  11231. \begin{array}{lcl}
  11232. \itm{cmp} &::= & \code{Is()} \\
  11233. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11234. &\MID& \LEN{\Exp}
  11235. \end{array}
  11236. }
  11237. \begin{figure}[tbp]
  11238. \centering
  11239. \begin{tcolorbox}[colback=white]
  11240. \small
  11241. {\if\edition\racketEd
  11242. \[
  11243. \begin{array}{l}
  11244. \gray{\LintGrammarRacket{}} \\ \hline
  11245. \gray{\LvarGrammarRacket{}} \\ \hline
  11246. \gray{\LifGrammarRacket{}} \\ \hline
  11247. \gray{\LwhileGrammarRacket} \\ \hline
  11248. \LtupGrammarRacket \\
  11249. \begin{array}{lcl}
  11250. \LangVecM{} &::=& \Exp
  11251. \end{array}
  11252. \end{array}
  11253. \]
  11254. \fi}
  11255. {\if\edition\pythonEd\pythonColor
  11256. \[
  11257. \begin{array}{l}
  11258. \gray{\LintGrammarPython{}} \\ \hline
  11259. \gray{\LvarGrammarPython{}} \\ \hline
  11260. \gray{\LifGrammarPython{}} \\ \hline
  11261. \gray{\LwhileGrammarPython} \\ \hline
  11262. \LtupGrammarPython \\
  11263. \begin{array}{rcl}
  11264. \LangVecM{} &::=& \Stmt^{*}
  11265. \end{array}
  11266. \end{array}
  11267. \]
  11268. \fi}
  11269. \end{tcolorbox}
  11270. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11271. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11272. \label{fig:Lvec-concrete-syntax}
  11273. \end{figure}
  11274. \begin{figure}[tp]
  11275. \centering
  11276. \begin{tcolorbox}[colback=white]
  11277. \small
  11278. {\if\edition\racketEd
  11279. \[
  11280. \begin{array}{l}
  11281. \gray{\LintOpAST} \\ \hline
  11282. \gray{\LvarASTRacket{}} \\ \hline
  11283. \gray{\LifASTRacket{}} \\ \hline
  11284. \gray{\LwhileASTRacket{}} \\ \hline
  11285. \LtupASTRacket{} \\
  11286. \begin{array}{lcl}
  11287. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11288. \end{array}
  11289. \end{array}
  11290. \]
  11291. \fi}
  11292. {\if\edition\pythonEd\pythonColor
  11293. \[
  11294. \begin{array}{l}
  11295. \gray{\LintASTPython} \\ \hline
  11296. \gray{\LvarASTPython} \\ \hline
  11297. \gray{\LifASTPython} \\ \hline
  11298. \gray{\LwhileASTPython} \\ \hline
  11299. \LtupASTPython \\
  11300. \begin{array}{lcl}
  11301. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11302. \end{array}
  11303. \end{array}
  11304. \]
  11305. \fi}
  11306. \end{tcolorbox}
  11307. \caption{The abstract syntax of \LangVec{}.}
  11308. \label{fig:Lvec-syntax}
  11309. \end{figure}
  11310. Tuples raise several interesting new issues. First, variable binding
  11311. performs a shallow copy in dealing with tuples, which means that
  11312. different variables can refer to the same tuple; that is, two
  11313. variables can be \emph{aliases}\index{subject}{alias} for the same
  11314. entity. Consider the following example, in which \code{t1} and
  11315. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11316. different tuple value with equal elements. The result of the
  11317. program is \code{42}.
  11318. \begin{center}
  11319. \begin{minipage}{0.96\textwidth}
  11320. {\if\edition\racketEd
  11321. \begin{lstlisting}
  11322. (let ([t1 (vector 3 7)])
  11323. (let ([t2 t1])
  11324. (let ([t3 (vector 3 7)])
  11325. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11326. 42
  11327. 0))))
  11328. \end{lstlisting}
  11329. \fi}
  11330. {\if\edition\pythonEd\pythonColor
  11331. \begin{lstlisting}
  11332. t1 = 3, 7
  11333. t2 = t1
  11334. t3 = 3, 7
  11335. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11336. \end{lstlisting}
  11337. \fi}
  11338. \end{minipage}
  11339. \end{center}
  11340. {\if\edition\racketEd
  11341. Whether two variables are aliased or not affects what happens
  11342. when the underlying tuple is mutated\index{subject}{mutation}.
  11343. Consider the following example in which \code{t1} and \code{t2}
  11344. again refer to the same tuple value.
  11345. \begin{center}
  11346. \begin{minipage}{0.96\textwidth}
  11347. \begin{lstlisting}
  11348. (let ([t1 (vector 3 7)])
  11349. (let ([t2 t1])
  11350. (let ([_ (vector-set! t2 0 42)])
  11351. (vector-ref t1 0))))
  11352. \end{lstlisting}
  11353. \end{minipage}
  11354. \end{center}
  11355. The mutation through \code{t2} is visible in referencing the tuple
  11356. from \code{t1}, so the result of this program is \code{42}.
  11357. \fi}
  11358. The next issue concerns the lifetime of tuples. When does a tuple's
  11359. lifetime end? Notice that \LangVec{} does not include an operation
  11360. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11361. to any notion of static scoping.
  11362. %
  11363. {\if\edition\racketEd
  11364. %
  11365. For example, the following program returns \code{42} even though the
  11366. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11367. that reads from the vector to which it was bound.
  11368. \begin{center}
  11369. \begin{minipage}{0.96\textwidth}
  11370. \begin{lstlisting}
  11371. (let ([v (vector (vector 44))])
  11372. (let ([x (let ([w (vector 42)])
  11373. (let ([_ (vector-set! v 0 w)])
  11374. 0))])
  11375. (+ x (vector-ref (vector-ref v 0) 0))))
  11376. \end{lstlisting}
  11377. \end{minipage}
  11378. \end{center}
  11379. \fi}
  11380. %
  11381. {\if\edition\pythonEd\pythonColor
  11382. %
  11383. For example, the following program returns \code{42} even though the
  11384. variable \code{x} goes out of scope when the function returns, prior
  11385. to reading the tuple element at index $0$. (We study the compilation
  11386. of functions in chapter~\ref{ch:Lfun}.)
  11387. %
  11388. \begin{center}
  11389. \begin{minipage}{0.96\textwidth}
  11390. \begin{lstlisting}
  11391. def f():
  11392. x = 42, 43
  11393. return x
  11394. t = f()
  11395. print(t[0])
  11396. \end{lstlisting}
  11397. \end{minipage}
  11398. \end{center}
  11399. \fi}
  11400. %
  11401. From the perspective of programmer-observable behavior, tuples live
  11402. forever. However, if they really lived forever then many long-running
  11403. programs would run out of memory. To solve this problem, the
  11404. language's runtime system performs automatic garbage collection.
  11405. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11406. \LangVec{} language.
  11407. %
  11408. \racket{We define the \code{vector}, \code{vector-ref},
  11409. \code{vector-set!}, and \code{vector-length} operations for
  11410. \LangVec{} in terms of the corresponding operations in Racket. One
  11411. subtle point is that the \code{vector-set!} operation returns the
  11412. \code{\#<void>} value.}
  11413. %
  11414. \python{We represent tuples with Python lists in the interpreter
  11415. because we need to write to them
  11416. (section~\ref{sec:expose-allocation}). (Python tuples are
  11417. immutable.) We define element access, the \code{is} operator, and
  11418. the \code{len} operator for \LangVec{} in terms of the corresponding
  11419. operations in Python.}
  11420. \begin{figure}[tbp]
  11421. \begin{tcolorbox}[colback=white]
  11422. {\if\edition\racketEd
  11423. \begin{lstlisting}
  11424. (define interp-Lvec-class
  11425. (class interp-Lwhile-class
  11426. (super-new)
  11427. (define/override (interp-op op)
  11428. (match op
  11429. ['eq? (lambda (v1 v2)
  11430. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11431. (and (boolean? v1) (boolean? v2))
  11432. (and (vector? v1) (vector? v2))
  11433. (and (void? v1) (void? v2)))
  11434. (eq? v1 v2)]))]
  11435. ['vector vector]
  11436. ['vector-length vector-length]
  11437. ['vector-ref vector-ref]
  11438. ['vector-set! vector-set!]
  11439. [else (super interp-op op)]
  11440. ))
  11441. (define/override ((interp-exp env) e)
  11442. (match e
  11443. [(HasType e t) ((interp-exp env) e)]
  11444. [else ((super interp-exp env) e)]
  11445. ))
  11446. ))
  11447. (define (interp-Lvec p)
  11448. (send (new interp-Lvec-class) interp-program p))
  11449. \end{lstlisting}
  11450. \fi}
  11451. %
  11452. {\if\edition\pythonEd\pythonColor
  11453. \begin{lstlisting}
  11454. class InterpLtup(InterpLwhile):
  11455. def interp_cmp(self, cmp):
  11456. match cmp:
  11457. case Is():
  11458. return lambda x, y: x is y
  11459. case _:
  11460. return super().interp_cmp(cmp)
  11461. def interp_exp(self, e, env):
  11462. match e:
  11463. case Tuple(es, Load()):
  11464. return tuple([self.interp_exp(e, env) for e in es])
  11465. case Subscript(tup, index, Load()):
  11466. t = self.interp_exp(tup, env)
  11467. n = self.interp_exp(index, env)
  11468. return t[n]
  11469. case _:
  11470. return super().interp_exp(e, env)
  11471. \end{lstlisting}
  11472. \fi}
  11473. \end{tcolorbox}
  11474. \caption{Interpreter for the \LangVec{} language.}
  11475. \label{fig:interp-Lvec}
  11476. \end{figure}
  11477. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11478. \LangVec{}.
  11479. %
  11480. The type of a tuple is a
  11481. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11482. type for each of its elements.
  11483. %
  11484. \racket{To create the s-expression for the \code{Vector} type, we use the
  11485. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11486. operator} \code{,@} to insert the list \code{t*} without its usual
  11487. start and end parentheses. \index{subject}{unquote-splicing}}
  11488. %
  11489. The type of accessing the ith element of a tuple is the ith element
  11490. type of the tuple's type, if there is one. If not, an error is
  11491. signaled. Note that the index \code{i} is required to be a constant
  11492. integer (and not, for example, a call to
  11493. \racket{\code{read}}\python{input\_int}) so that the type checker
  11494. can determine the element's type given the tuple type.
  11495. %
  11496. \racket{
  11497. Regarding writing an element to a tuple, the element's type must
  11498. be equal to the ith element type of the tuple's type.
  11499. The result type is \code{Void}.}
  11500. %% When allocating a tuple,
  11501. %% we need to know which elements of the tuple are themselves tuples for
  11502. %% the purposes of garbage collection. We can obtain this information
  11503. %% during type checking. The type checker shown in
  11504. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11505. %% expression; it also
  11506. %% %
  11507. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11508. %% where $T$ is the tuple's type.
  11509. %
  11510. %records the type of each tuple expression in a new field named \code{has\_type}.
  11511. \begin{figure}[tp]
  11512. \begin{tcolorbox}[colback=white]
  11513. {\if\edition\racketEd
  11514. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11515. (define type-check-Lvec-class
  11516. (class type-check-Lif-class
  11517. (super-new)
  11518. (inherit check-type-equal?)
  11519. (define/override (type-check-exp env)
  11520. (lambda (e)
  11521. (define recur (type-check-exp env))
  11522. (match e
  11523. [(Prim 'vector es)
  11524. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11525. (define t `(Vector ,@t*))
  11526. (values (Prim 'vector e*) t)]
  11527. [(Prim 'vector-ref (list e1 (Int i)))
  11528. (define-values (e1^ t) (recur e1))
  11529. (match t
  11530. [`(Vector ,ts ...)
  11531. (unless (and (0 . <= . i) (i . < . (length ts)))
  11532. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11533. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11534. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11535. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11536. (define-values (e-vec t-vec) (recur e1))
  11537. (define-values (e-elt^ t-elt) (recur elt))
  11538. (match t-vec
  11539. [`(Vector ,ts ...)
  11540. (unless (and (0 . <= . i) (i . < . (length ts)))
  11541. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11542. (check-type-equal? (list-ref ts i) t-elt e)
  11543. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11544. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11545. [(Prim 'vector-length (list e))
  11546. (define-values (e^ t) (recur e))
  11547. (match t
  11548. [`(Vector ,ts ...)
  11549. (values (Prim 'vector-length (list e^)) 'Integer)]
  11550. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11551. [(Prim 'eq? (list arg1 arg2))
  11552. (define-values (e1 t1) (recur arg1))
  11553. (define-values (e2 t2) (recur arg2))
  11554. (match* (t1 t2)
  11555. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11556. [(other wise) (check-type-equal? t1 t2 e)])
  11557. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11558. [else ((super type-check-exp env) e)]
  11559. )))
  11560. ))
  11561. (define (type-check-Lvec p)
  11562. (send (new type-check-Lvec-class) type-check-program p))
  11563. \end{lstlisting}
  11564. \fi}
  11565. {\if\edition\pythonEd\pythonColor
  11566. \begin{lstlisting}
  11567. class TypeCheckLtup(TypeCheckLwhile):
  11568. def type_check_exp(self, e, env):
  11569. match e:
  11570. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11571. l = self.type_check_exp(left, env)
  11572. r = self.type_check_exp(right, env)
  11573. check_type_equal(l, r, e)
  11574. return bool
  11575. case Tuple(es, Load()):
  11576. ts = [self.type_check_exp(e, env) for e in es]
  11577. e.has_type = TupleType(ts)
  11578. return e.has_type
  11579. case Subscript(tup, Constant(i), Load()):
  11580. tup_ty = self.type_check_exp(tup, env)
  11581. i_ty = self.type_check_exp(Constant(i), env)
  11582. check_type_equal(i_ty, int, i)
  11583. match tup_ty:
  11584. case TupleType(ts):
  11585. return ts[i]
  11586. case _:
  11587. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11588. case _:
  11589. return super().type_check_exp(e, env)
  11590. \end{lstlisting}
  11591. \fi}
  11592. \end{tcolorbox}
  11593. \caption{Type checker for the \LangVec{} language.}
  11594. \label{fig:type-check-Lvec}
  11595. \end{figure}
  11596. \section{Garbage Collection}
  11597. \label{sec:GC}
  11598. Garbage collection is a runtime technique for reclaiming space on the
  11599. heap that will not be used in the future of the running program. We
  11600. use the term \emph{object}\index{subject}{object} to refer to any
  11601. value that is stored in the heap, which for now includes only
  11602. tuples.%
  11603. %
  11604. \footnote{The term \emph{object} as it is used in the context of
  11605. object-oriented programming has a more specific meaning than the
  11606. way in which we use the term here.}
  11607. %
  11608. Unfortunately, it is impossible to know precisely which objects will
  11609. be accessed in the future and which will not. Instead, garbage
  11610. collectors overapproximate the set of objects that will be accessed by
  11611. identifying which objects can possibly be accessed. The running
  11612. program can directly access objects that are in registers and on the
  11613. procedure call stack. It can also transitively access the elements of
  11614. tuples, starting with a tuple whose address is in a register or on the
  11615. procedure call stack. We define the \emph{root
  11616. set}\index{subject}{root set} to be all the tuple addresses that are
  11617. in registers or on the procedure call stack. We define the \emph{live
  11618. objects}\index{subject}{live objects} to be the objects that are
  11619. reachable from the root set. Garbage collectors reclaim the space that
  11620. is allocated to objects that are no longer live. \index{subject}{allocate}
  11621. That means that some objects may not get reclaimed as soon as they could be,
  11622. but at least
  11623. garbage collectors do not reclaim the space dedicated to objects that
  11624. will be accessed in the future! The programmer can influence which
  11625. objects get reclaimed by causing them to become unreachable.
  11626. So the goal of the garbage collector is twofold:
  11627. \begin{enumerate}
  11628. \item to preserve all the live objects, and
  11629. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11630. \end{enumerate}
  11631. \subsection{Two-Space Copying Collector}
  11632. Here we study a relatively simple algorithm for garbage collection
  11633. that is the basis of many state-of-the-art garbage
  11634. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11635. particular, we describe a two-space copying
  11636. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11637. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11638. collector} \index{subject}{two-space copying collector}
  11639. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11640. what happens in a two-space collector, showing two time steps, prior
  11641. to garbage collection (on the top) and after garbage collection (on
  11642. the bottom). In a two-space collector, the heap is divided into two
  11643. parts named the FromSpace\index{subject}{FromSpace} and the
  11644. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11645. FromSpace until there is not enough room for the next allocation
  11646. request. At that point, the garbage collector goes to work to make
  11647. room for the next allocation.
  11648. A copying collector makes more room by copying all the live objects
  11649. from the FromSpace into the ToSpace and then performs a sleight of
  11650. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11651. as the new ToSpace. In the example shown in
  11652. figure~\ref{fig:copying-collector}, the root set consists of three
  11653. pointers, one in a register and two on the stack. All the live
  11654. objects have been copied to the ToSpace (the right-hand side of
  11655. figure~\ref{fig:copying-collector}) in a way that preserves the
  11656. pointer relationships. For example, the pointer in the register still
  11657. points to a tuple that in turn points to two other tuples. There are
  11658. four tuples that are not reachable from the root set and therefore do
  11659. not get copied into the ToSpace.
  11660. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11661. created by a well-typed program in \LangVec{} because it contains a
  11662. cycle. However, creating cycles will be possible once we get to
  11663. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11664. to deal with cycles to begin with, so we will not need to revisit this
  11665. issue.
  11666. \begin{figure}[tbp]
  11667. \centering
  11668. \begin{tcolorbox}[colback=white]
  11669. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11670. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11671. \\[5ex]
  11672. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11673. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11674. \end{tcolorbox}
  11675. \caption{A copying collector in action.}
  11676. \label{fig:copying-collector}
  11677. \end{figure}
  11678. \subsection{Graph Copying via Cheney's Algorithm}
  11679. \label{sec:cheney}
  11680. \index{subject}{Cheney's algorithm}
  11681. Let us take a closer look at the copying of the live objects. The
  11682. allocated\index{subject}{allocate} objects and pointers can be viewed
  11683. as a graph, and we need to copy the part of the graph that is
  11684. reachable from the root set. To make sure that we copy all the
  11685. reachable vertices in the graph, we need an exhaustive graph traversal
  11686. algorithm, such as depth-first search or breadth-first
  11687. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11688. take into account the possibility of cycles by marking which vertices
  11689. have already been visited, so to ensure termination of the
  11690. algorithm. These search algorithms also use a data structure such as a
  11691. stack or queue as a to-do list to keep track of the vertices that need
  11692. to be visited. We use breadth-first search and a trick due to
  11693. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11694. copying tuples into the ToSpace.
  11695. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11696. copy progresses. The queue is represented by a chunk of contiguous
  11697. memory at the beginning of the ToSpace, using two pointers to track
  11698. the front and the back of the queue, called the \emph{free pointer}
  11699. and the \emph{scan pointer}, respectively. The algorithm starts by
  11700. copying all tuples that are immediately reachable from the root set
  11701. into the ToSpace to form the initial queue. When we copy a tuple, we
  11702. mark the old tuple to indicate that it has been visited. We discuss
  11703. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11704. that any pointers inside the copied tuples in the queue still point
  11705. back to the FromSpace. Once the initial queue has been created, the
  11706. algorithm enters a loop in which it repeatedly processes the tuple at
  11707. the front of the queue and pops it off the queue. To process a tuple,
  11708. the algorithm copies all the objects that are directly reachable from it
  11709. to the ToSpace, placing them at the back of the queue. The algorithm
  11710. then updates the pointers in the popped tuple so that they point to the
  11711. newly copied objects.
  11712. \begin{figure}[tbp]
  11713. \centering
  11714. \begin{tcolorbox}[colback=white]
  11715. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11716. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11717. \end{tcolorbox}
  11718. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11719. \label{fig:cheney}
  11720. \end{figure}
  11721. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11722. tuple whose second element is $42$ to the back of the queue. The other
  11723. pointer goes to a tuple that has already been copied, so we do not
  11724. need to copy it again, but we do need to update the pointer to the new
  11725. location. This can be accomplished by storing a \emph{forwarding
  11726. pointer}\index{subject}{forwarding pointer} to the new location in the
  11727. old tuple, when we initially copied the tuple into the
  11728. ToSpace. This completes one step of the algorithm. The algorithm
  11729. continues in this way until the queue is empty; that is, when the scan
  11730. pointer catches up with the free pointer.
  11731. \subsection{Data Representation}
  11732. \label{sec:data-rep-gc}
  11733. The garbage collector places some requirements on the data
  11734. representations used by our compiler. First, the garbage collector
  11735. needs to distinguish between pointers and other kinds of data such as
  11736. integers. The following are several ways to accomplish this:
  11737. \begin{enumerate}
  11738. \item Attach a tag to each object that identifies what type of
  11739. object it is~\citep{McCarthy:1960dz}.
  11740. \item Store different types of objects in different
  11741. regions~\citep{Steele:1977ab}.
  11742. \item Use type information from the program to either (a) generate
  11743. type-specific code for collecting, or (b) generate tables that
  11744. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11745. \end{enumerate}
  11746. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11747. need to tag objects in any case, so option 1 is a natural choice for those
  11748. languages. However, \LangVec{} is a statically typed language, so it
  11749. would be unfortunate to require tags on every object, especially small
  11750. and pervasive objects like integers and Booleans. Option 3 is the
  11751. best-performing choice for statically typed languages, but it comes with
  11752. a relatively high implementation complexity. To keep this chapter
  11753. within a reasonable scope of complexity, we recommend a combination of options
  11754. 1 and 2, using separate strategies for the stack and the heap.
  11755. Regarding the stack, we recommend using a separate stack for pointers,
  11756. which we call the \emph{root stack}\index{subject}{root stack}
  11757. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11758. That is, when a local variable needs to be spilled and is of type
  11759. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11760. root stack instead of putting it on the procedure call
  11761. stack. Furthermore, we always spill tuple-typed variables if they are
  11762. live during a call to the collector, thereby ensuring that no pointers
  11763. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11764. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11765. contrasts it with the data layout using a root stack. The root stack
  11766. contains the two pointers from the regular stack and also the pointer
  11767. in the second register.
  11768. \begin{figure}[tbp]
  11769. \centering
  11770. \begin{tcolorbox}[colback=white]
  11771. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11772. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11773. \end{tcolorbox}
  11774. \caption{Maintaining a root stack to facilitate garbage collection.}
  11775. \label{fig:shadow-stack}
  11776. \end{figure}
  11777. The problem of distinguishing between pointers and other kinds of data
  11778. also arises inside each tuple on the heap. We solve this problem by
  11779. attaching a tag, an extra 64 bits, to each
  11780. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11781. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11782. Note that we have drawn the bits in a big-endian way, from right to left,
  11783. with bit location 0 (the least significant bit) on the far right,
  11784. which corresponds to the direction of the x86 shifting instructions
  11785. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11786. is dedicated to specifying which elements of the tuple are pointers,
  11787. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11788. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11789. data. The pointer mask starts at bit location 7. We limit tuples to a
  11790. maximum size of fifty elements, so we need 50 bits for the pointer
  11791. mask.%
  11792. %
  11793. \footnote{A production-quality compiler would handle
  11794. arbitrarily sized tuples and use a more complex approach.}
  11795. %
  11796. The tag also contains two other pieces of information. The length of
  11797. the tuple (number of elements) is stored in bits at locations 1 through
  11798. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11799. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11800. has not yet been copied. If the bit has value 0, then the entire tag
  11801. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11802. zero in any case, because our tuples are 8-byte aligned.)
  11803. \begin{figure}[tbp]
  11804. \centering
  11805. \begin{tcolorbox}[colback=white]
  11806. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11807. \end{tcolorbox}
  11808. \caption{Representation of tuples in the heap.}
  11809. \label{fig:tuple-rep}
  11810. \end{figure}
  11811. \subsection{Implementation of the Garbage Collector}
  11812. \label{sec:organize-gz}
  11813. \index{subject}{prelude}
  11814. An implementation of the copying collector is provided in the
  11815. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11816. interface to the garbage collector that is used by the compiler. The
  11817. \code{initialize} function creates the FromSpace, ToSpace, and root
  11818. stack and should be called in the prelude of the \code{main}
  11819. function. The arguments of \code{initialize} are the root stack size
  11820. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11821. good choice for both. The \code{initialize} function puts the address
  11822. of the beginning of the FromSpace into the global variable
  11823. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11824. the address that is one past the last element of the FromSpace. We use
  11825. half-open intervals to represent chunks of
  11826. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11827. points to the first element of the root stack.
  11828. As long as there is room left in the FromSpace, your generated code
  11829. can allocate\index{subject}{allocate} tuples simply by moving the
  11830. \code{free\_ptr} forward.
  11831. %
  11832. The amount of room left in the FromSpace is the difference between the
  11833. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11834. function should be called when there is not enough room left in the
  11835. FromSpace for the next allocation. The \code{collect} function takes
  11836. a pointer to the current top of the root stack (one past the last item
  11837. that was pushed) and the number of bytes that need to be
  11838. allocated. The \code{collect} function performs the copying collection
  11839. and leaves the heap in a state such that there is enough room for the
  11840. next allocation.
  11841. \begin{figure}[tbp]
  11842. \begin{tcolorbox}[colback=white]
  11843. \begin{lstlisting}
  11844. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11845. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11846. int64_t* free_ptr;
  11847. int64_t* fromspace_begin;
  11848. int64_t* fromspace_end;
  11849. int64_t** rootstack_begin;
  11850. \end{lstlisting}
  11851. \end{tcolorbox}
  11852. \caption{The compiler's interface to the garbage collector.}
  11853. \label{fig:gc-header}
  11854. \end{figure}
  11855. %% \begin{exercise}
  11856. %% In the file \code{runtime.c} you will find the implementation of
  11857. %% \code{initialize} and a partial implementation of \code{collect}.
  11858. %% The \code{collect} function calls another function, \code{cheney},
  11859. %% to perform the actual copy, and that function is left to the reader
  11860. %% to implement. The following is the prototype for \code{cheney}.
  11861. %% \begin{lstlisting}
  11862. %% static void cheney(int64_t** rootstack_ptr);
  11863. %% \end{lstlisting}
  11864. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11865. %% rootstack (which is an array of pointers). The \code{cheney} function
  11866. %% also communicates with \code{collect} through the global
  11867. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11868. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11869. %% the ToSpace:
  11870. %% \begin{lstlisting}
  11871. %% static int64_t* tospace_begin;
  11872. %% static int64_t* tospace_end;
  11873. %% \end{lstlisting}
  11874. %% The job of the \code{cheney} function is to copy all the live
  11875. %% objects (reachable from the root stack) into the ToSpace, update
  11876. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11877. %% update the root stack so that it points to the objects in the
  11878. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11879. %% and ToSpace.
  11880. %% \end{exercise}
  11881. The introduction of garbage collection has a nontrivial impact on our
  11882. compiler passes. We introduce a new compiler pass named
  11883. \code{expose\_allocation} that elaborates the code for allocating
  11884. tuples. We also make significant changes to
  11885. \code{select\_instructions}, \code{build\_interference},
  11886. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11887. make minor changes in several more passes.
  11888. The following program serves as our running example. It creates
  11889. two tuples, one nested inside the other. Both tuples have length
  11890. one. The program accesses the element in the inner tuple.
  11891. % tests/vectors_test_17.rkt
  11892. {\if\edition\racketEd
  11893. \begin{lstlisting}
  11894. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11895. \end{lstlisting}
  11896. \fi}
  11897. % tests/tuple/get_get.py
  11898. {\if\edition\pythonEd\pythonColor
  11899. \begin{lstlisting}
  11900. v1 = (42,)
  11901. v2 = (v1,)
  11902. print(v2[0][0])
  11903. \end{lstlisting}
  11904. \fi}
  11905. %% {\if\edition\racketEd
  11906. %% \section{Shrink}
  11907. %% \label{sec:shrink-Lvec}
  11908. %% Recall that the \code{shrink} pass translates the primitives operators
  11909. %% into a smaller set of primitives.
  11910. %% %
  11911. %% This pass comes after type checking, and the type checker adds a
  11912. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11913. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11914. %% \fi}
  11915. \section{Expose Allocation}
  11916. \label{sec:expose-allocation}
  11917. The pass \code{expose\_allocation} lowers tuple creation into making a
  11918. conditional call to the collector followed by allocating the
  11919. appropriate amount of memory and initializing it. We choose to place
  11920. the \code{expose\_allocation} pass before
  11921. \code{remove\_complex\_operands} because it generates
  11922. code that contains complex operands.
  11923. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11924. that replaces tuple creation with new lower-level forms that we use in the
  11925. translation of tuple creation.
  11926. %
  11927. {\if\edition\racketEd
  11928. \[
  11929. \begin{array}{lcl}
  11930. \Exp &::=& (\key{collect} \,\itm{int})
  11931. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11932. \MID (\key{global-value} \,\itm{name})
  11933. \end{array}
  11934. \]
  11935. \fi}
  11936. {\if\edition\pythonEd\pythonColor
  11937. \[
  11938. \begin{array}{lcl}
  11939. \Exp &::=& \cdots\\
  11940. &\MID& \key{collect}(\itm{int})
  11941. \MID \key{allocate}(\itm{int},\itm{type})
  11942. \MID \key{global\_value}(\itm{name}) \\
  11943. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11944. \end{array}
  11945. \]
  11946. \fi}
  11947. %
  11948. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11949. make sure that there are $n$ bytes ready to be allocated. During
  11950. instruction selection\index{subject}{instruction selection},
  11951. the \CCOLLECT{$n$} form will become a call to
  11952. the \code{collect} function in \code{runtime.c}.
  11953. %
  11954. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11955. space at the front for the 64-bit tag), but the elements are not
  11956. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11957. of the tuple:
  11958. %
  11959. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11960. %
  11961. where $\Type_i$ is the type of the $i$th element.
  11962. %
  11963. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11964. variable, such as \code{free\_ptr}.
  11965. \racket{
  11966. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11967. can be obtained by running the
  11968. \code{type-check-Lvec-has-type} type checker immediately before the
  11969. \code{expose\_allocation} pass. This version of the type checker
  11970. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11971. around each tuple creation. The concrete syntax
  11972. for \code{HasType} is \code{has-type}.}
  11973. The following shows the transformation of tuple creation into (1) a
  11974. sequence of temporary variable bindings for the initializing
  11975. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11976. \code{allocate}, and (4) the initialization of the tuple. The
  11977. \itm{len} placeholder refers to the length of the tuple, and
  11978. \itm{bytes} is the total number of bytes that need to be allocated for
  11979. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11980. %
  11981. \python{The \itm{type} needed for the second argument of the
  11982. \code{allocate} form can be obtained from the \code{has\_type} field
  11983. of the tuple AST node, which is stored there by running the type
  11984. checker for \LangVec{} immediately before this pass.}
  11985. %
  11986. \begin{center}
  11987. \begin{minipage}{\textwidth}
  11988. {\if\edition\racketEd
  11989. \begin{lstlisting}
  11990. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11991. |$\Longrightarrow$|
  11992. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11993. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11994. (global-value fromspace_end))
  11995. (void)
  11996. (collect |\itm{bytes}|))])
  11997. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11998. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11999. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12000. |$v$|) ... )))) ...)
  12001. \end{lstlisting}
  12002. \fi}
  12003. {\if\edition\pythonEd\pythonColor
  12004. \begin{lstlisting}
  12005. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12006. |$\Longrightarrow$|
  12007. begin:
  12008. |$x_0$| = |$e_0$|
  12009. |$\vdots$|
  12010. |$x_{n-1}$| = |$e_{n-1}$|
  12011. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12012. 0
  12013. else:
  12014. collect(|\itm{bytes}|)
  12015. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12016. |$v$|[0] = |$x_0$|
  12017. |$\vdots$|
  12018. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12019. |$v$|
  12020. \end{lstlisting}
  12021. \fi}
  12022. \end{minipage}
  12023. \end{center}
  12024. %
  12025. \noindent The sequencing of the initializing expressions
  12026. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12027. they may trigger garbage collection and we cannot have an allocated
  12028. but uninitialized tuple on the heap during a collection.
  12029. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12030. \code{expose\_allocation} pass on our running example.
  12031. \begin{figure}[tbp]
  12032. \begin{tcolorbox}[colback=white]
  12033. % tests/s2_17.rkt
  12034. {\if\edition\racketEd
  12035. \begin{lstlisting}
  12036. (vector-ref
  12037. (vector-ref
  12038. (let ([vecinit6
  12039. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12040. (global-value fromspace_end))
  12041. (void)
  12042. (collect 16))])
  12043. (let ([alloc2 (allocate 1 (Vector Integer))])
  12044. (let ([_3 (vector-set! alloc2 0 42)])
  12045. alloc2)))])
  12046. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12047. (global-value fromspace_end))
  12048. (void)
  12049. (collect 16))])
  12050. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12051. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12052. alloc5))))
  12053. 0)
  12054. 0)
  12055. \end{lstlisting}
  12056. \fi}
  12057. {\if\edition\pythonEd\pythonColor
  12058. \begin{lstlisting}
  12059. v1 = begin:
  12060. init.514 = 42
  12061. if (free_ptr + 16) < fromspace_end:
  12062. else:
  12063. collect(16)
  12064. alloc.513 = allocate(1,tuple[int])
  12065. alloc.513[0] = init.514
  12066. alloc.513
  12067. v2 = begin:
  12068. init.516 = v1
  12069. if (free_ptr + 16) < fromspace_end:
  12070. else:
  12071. collect(16)
  12072. alloc.515 = allocate(1,tuple[tuple[int]])
  12073. alloc.515[0] = init.516
  12074. alloc.515
  12075. print(v2[0][0])
  12076. \end{lstlisting}
  12077. \fi}
  12078. \end{tcolorbox}
  12079. \caption{Output of the \code{expose\_allocation} pass.}
  12080. \label{fig:expose-alloc-output}
  12081. \end{figure}
  12082. \section{Remove Complex Operands}
  12083. \label{sec:remove-complex-opera-Lvec}
  12084. {\if\edition\racketEd
  12085. %
  12086. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12087. should be treated as complex operands.
  12088. %
  12089. \fi}
  12090. %
  12091. {\if\edition\pythonEd\pythonColor
  12092. %
  12093. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12094. and tuple access should be treated as complex operands. The
  12095. subexpressions of tuple access must be atomic.
  12096. %
  12097. \fi}
  12098. %% A new case for
  12099. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12100. %% handled carefully to prevent the \code{Prim} node from being separated
  12101. %% from its enclosing \code{HasType}.
  12102. Figure~\ref{fig:Lvec-anf-syntax}
  12103. shows the grammar for the output language \LangAllocANF{} of this
  12104. pass, which is \LangAlloc{} in monadic normal form.
  12105. \newcommand{\LtupMonadASTRacket}{
  12106. \begin{array}{rcl}
  12107. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12108. \MID \GLOBALVALUE{\Var}
  12109. \end{array}
  12110. }
  12111. \newcommand{\LtupMonadASTPython}{
  12112. \begin{array}{rcl}
  12113. \Exp &::=& \GET{\Atm}{\Atm} \\
  12114. &\MID& \LEN{\Atm}\\
  12115. &\MID& \ALLOCATE{\Int}{\Type}
  12116. \MID \GLOBALVALUE{\Var} \\
  12117. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12118. &\MID& \COLLECT{\Int}
  12119. \end{array}
  12120. }
  12121. \begin{figure}[tp]
  12122. \centering
  12123. \begin{tcolorbox}[colback=white]
  12124. \small
  12125. {\if\edition\racketEd
  12126. \[
  12127. \begin{array}{l}
  12128. \gray{\LvarMonadASTRacket} \\ \hline
  12129. \gray{\LifMonadASTRacket} \\ \hline
  12130. \gray{\LwhileMonadASTRacket} \\ \hline
  12131. \LtupMonadASTRacket \\
  12132. \begin{array}{rcl}
  12133. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12134. \end{array}
  12135. \end{array}
  12136. \]
  12137. \fi}
  12138. {\if\edition\pythonEd\pythonColor
  12139. \[
  12140. \begin{array}{l}
  12141. \gray{\LvarMonadASTPython} \\ \hline
  12142. \gray{\LifMonadASTPython} \\ \hline
  12143. \gray{\LwhileMonadASTPython} \\ \hline
  12144. \LtupMonadASTPython \\
  12145. \begin{array}{rcl}
  12146. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12147. \end{array}
  12148. \end{array}
  12149. \]
  12150. \fi}
  12151. \end{tcolorbox}
  12152. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12153. \label{fig:Lvec-anf-syntax}
  12154. \end{figure}
  12155. \section{Explicate Control and the \LangCVec{} Language}
  12156. \label{sec:explicate-control-r3}
  12157. \newcommand{\CtupASTRacket}{
  12158. \begin{array}{lcl}
  12159. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12160. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12161. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12162. &\MID& \VECLEN{\Atm} \\
  12163. &\MID& \GLOBALVALUE{\Var} \\
  12164. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12165. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12166. \end{array}
  12167. }
  12168. \newcommand{\CtupASTPython}{
  12169. \begin{array}{lcl}
  12170. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12171. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12172. \Stmt &::=& \COLLECT{\Int} \\
  12173. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12174. \end{array}
  12175. }
  12176. \begin{figure}[tp]
  12177. \begin{tcolorbox}[colback=white]
  12178. \small
  12179. {\if\edition\racketEd
  12180. \[
  12181. \begin{array}{l}
  12182. \gray{\CvarASTRacket} \\ \hline
  12183. \gray{\CifASTRacket} \\ \hline
  12184. \gray{\CloopASTRacket} \\ \hline
  12185. \CtupASTRacket \\
  12186. \begin{array}{lcl}
  12187. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12188. \end{array}
  12189. \end{array}
  12190. \]
  12191. \fi}
  12192. {\if\edition\pythonEd\pythonColor
  12193. \[
  12194. \begin{array}{l}
  12195. \gray{\CifASTPython} \\ \hline
  12196. \CtupASTPython \\
  12197. \begin{array}{lcl}
  12198. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12199. \end{array}
  12200. \end{array}
  12201. \]
  12202. \fi}
  12203. \end{tcolorbox}
  12204. \caption{The abstract syntax of \LangCVec{}, extending
  12205. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12206. (figure~\ref{fig:c1-syntax})}.}
  12207. \label{fig:c2-syntax}
  12208. \end{figure}
  12209. The output of \code{explicate\_control} is a program in the
  12210. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12211. shows the definition of the abstract syntax.
  12212. %
  12213. %% \racket{(The concrete syntax is defined in
  12214. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12215. %
  12216. The new expressions of \LangCVec{} include \key{allocate},
  12217. %
  12218. \racket{\key{vector-ref}, and \key{vector-set!},}
  12219. %
  12220. \python{accessing tuple elements,}
  12221. %
  12222. and \key{global\_value}.
  12223. %
  12224. \python{\LangCVec{} also includes the \code{collect} statement and
  12225. assignment to a tuple element.}
  12226. %
  12227. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12228. %
  12229. The \code{explicate\_control} pass can treat these new forms much like
  12230. the other forms that we've already encountered. The output of the
  12231. \code{explicate\_control} pass on the running example is shown on the
  12232. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12233. section.
  12234. \section{Select Instructions and the \LangXGlobal{} Language}
  12235. \label{sec:select-instructions-gc}
  12236. \index{subject}{select instructions}
  12237. %% void (rep as zero)
  12238. %% allocate
  12239. %% collect (callq collect)
  12240. %% vector-ref
  12241. %% vector-set!
  12242. %% vector-length
  12243. %% global (postpone)
  12244. In this pass we generate x86 code for most of the new operations that
  12245. are needed to compile tuples, including \code{Allocate},
  12246. \code{Collect}, accessing tuple elements, and the \code{Is}
  12247. comparison.
  12248. %
  12249. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12250. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12251. \ref{fig:x86-2}). \index{subject}{x86}
  12252. The tuple read and write forms translate into \code{movq}
  12253. instructions. (The $+1$ in the offset serves to move past the tag at the
  12254. beginning of the tuple representation.)
  12255. %
  12256. \begin{center}
  12257. \begin{minipage}{\textwidth}
  12258. {\if\edition\racketEd
  12259. \begin{lstlisting}
  12260. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12261. |$\Longrightarrow$|
  12262. movq |$\itm{tup}'$|, %r11
  12263. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12264. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12265. |$\Longrightarrow$|
  12266. movq |$\itm{tup}'$|, %r11
  12267. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12268. movq $0, |$\itm{lhs'}$|
  12269. \end{lstlisting}
  12270. \fi}
  12271. {\if\edition\pythonEd\pythonColor
  12272. \begin{lstlisting}
  12273. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12274. |$\Longrightarrow$|
  12275. movq |$\itm{tup}'$|, %r11
  12276. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12277. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12278. |$\Longrightarrow$|
  12279. movq |$\itm{tup}'$|, %r11
  12280. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12281. \end{lstlisting}
  12282. \fi}
  12283. \end{minipage}
  12284. \end{center}
  12285. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12286. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12287. are obtained by translating from \LangCVec{} to x86.
  12288. %
  12289. The move of $\itm{tup}'$ to
  12290. register \code{r11} ensures that the offset expression
  12291. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12292. removing \code{r11} from consideration by the register allocating.
  12293. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12294. \code{rax}. Then the generated code for tuple assignment would be
  12295. \begin{lstlisting}
  12296. movq |$\itm{tup}'$|, %rax
  12297. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12298. \end{lstlisting}
  12299. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12300. \code{patch\_instructions} would insert a move through \code{rax}
  12301. as follows:
  12302. \begin{lstlisting}
  12303. movq |$\itm{tup}'$|, %rax
  12304. movq |$\itm{rhs}'$|, %rax
  12305. movq %rax, |$8(n+1)$|(%rax)
  12306. \end{lstlisting}
  12307. However, this sequence of instructions does not work because we're
  12308. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12309. $\itm{rhs}'$) at the same time!
  12310. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12311. be translated into a sequence of instructions that read the tag of the
  12312. tuple and extract the 6 bits that represent the tuple length, which
  12313. are the bits starting at index 1 and going up to and including bit 6.
  12314. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12315. (shift right) can be used to accomplish this.
  12316. We compile the \code{allocate} form to operations on the
  12317. \code{free\_ptr}, as shown next. This approach is called
  12318. \emph{inline allocation} because it implements allocation without a
  12319. function call by simply incrementing the allocation pointer. It is much
  12320. more efficient than calling a function for each allocation. The
  12321. address in the \code{free\_ptr} is the next free address in the
  12322. FromSpace, so we copy it into \code{r11} and then move it forward by
  12323. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12324. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12325. the tag. We then initialize the \itm{tag} and finally copy the
  12326. address in \code{r11} to the left-hand side. Refer to
  12327. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12328. %
  12329. \racket{We recommend using the Racket operations
  12330. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12331. during compilation.}
  12332. %
  12333. \python{We recommend using the bitwise-or operator \code{|} and the
  12334. shift-left operator \code{<<} to compute the tag during
  12335. compilation.}
  12336. %
  12337. The type annotation in the \code{allocate} form is used to determine
  12338. the pointer mask region of the tag.
  12339. %
  12340. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12341. address of the \code{free\_ptr} global variable using a special
  12342. instruction-pointer-relative addressing mode of the x86-64 processor.
  12343. In particular, the assembler computes the distance $d$ between the
  12344. address of \code{free\_ptr} and where the \code{rip} would be at that
  12345. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12346. \code{$d$(\%rip)}, which at runtime will compute the address of
  12347. \code{free\_ptr}.
  12348. %
  12349. {\if\edition\racketEd
  12350. \begin{lstlisting}
  12351. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12352. |$\Longrightarrow$|
  12353. movq free_ptr(%rip), %r11
  12354. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12355. movq $|$\itm{tag}$|, 0(%r11)
  12356. movq %r11, |$\itm{lhs}'$|
  12357. \end{lstlisting}
  12358. \fi}
  12359. {\if\edition\pythonEd\pythonColor
  12360. \begin{lstlisting}
  12361. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12362. |$\Longrightarrow$|
  12363. movq free_ptr(%rip), %r11
  12364. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12365. movq $|$\itm{tag}$|, 0(%r11)
  12366. movq %r11, |$\itm{lhs}'$|
  12367. \end{lstlisting}
  12368. \fi}
  12369. %
  12370. The \code{collect} form is compiled to a call to the \code{collect}
  12371. function in the runtime. The arguments to \code{collect} are (1) the
  12372. top of the root stack, and (2) the number of bytes that need to be
  12373. allocated. We use another dedicated register, \code{r15}, to store
  12374. the pointer to the top of the root stack. Therefore \code{r15} is not
  12375. available for use by the register allocator.
  12376. %
  12377. {\if\edition\racketEd
  12378. \begin{lstlisting}
  12379. (collect |$\itm{bytes}$|)
  12380. |$\Longrightarrow$|
  12381. movq %r15, %rdi
  12382. movq $|\itm{bytes}|, %rsi
  12383. callq collect
  12384. \end{lstlisting}
  12385. \fi}
  12386. {\if\edition\pythonEd\pythonColor
  12387. \begin{lstlisting}
  12388. collect(|$\itm{bytes}$|)
  12389. |$\Longrightarrow$|
  12390. movq %r15, %rdi
  12391. movq $|\itm{bytes}|, %rsi
  12392. callq collect
  12393. \end{lstlisting}
  12394. \fi}
  12395. {\if\edition\pythonEd\pythonColor
  12396. The \code{is} comparison is compiled similarly to the other comparison
  12397. operators, using the \code{cmpq} instruction. Because the value of a
  12398. tuple is its address, we can translate \code{is} into a simple check
  12399. for equality using the \code{e} condition code. \\
  12400. \begin{tabular}{lll}
  12401. \begin{minipage}{0.4\textwidth}
  12402. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12403. \end{minipage}
  12404. &
  12405. $\Rightarrow$
  12406. &
  12407. \begin{minipage}{0.4\textwidth}
  12408. \begin{lstlisting}
  12409. cmpq |$\Arg_2$|, |$\Arg_1$|
  12410. sete %al
  12411. movzbq %al, |$\Var$|
  12412. \end{lstlisting}
  12413. \end{minipage}
  12414. \end{tabular}
  12415. \fi}
  12416. \newcommand{\GrammarXGlobal}{
  12417. \begin{array}{lcl}
  12418. \Arg &::=& \itm{label} \key{(\%rip)}
  12419. \end{array}
  12420. }
  12421. \newcommand{\ASTXGlobalRacket}{
  12422. \begin{array}{lcl}
  12423. \Arg &::=& \GLOBAL{\itm{label}}
  12424. \end{array}
  12425. }
  12426. \begin{figure}[tp]
  12427. \begin{tcolorbox}[colback=white]
  12428. \[
  12429. \begin{array}{l}
  12430. \gray{\GrammarXInt} \\ \hline
  12431. \gray{\GrammarXIf} \\ \hline
  12432. \GrammarXGlobal \\
  12433. \begin{array}{lcl}
  12434. \LangXGlobalM{} &::= & \key{.globl main} \\
  12435. & & \key{main:} \; \Instr^{*}
  12436. \end{array}
  12437. \end{array}
  12438. \]
  12439. \end{tcolorbox}
  12440. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12441. \label{fig:x86-2-concrete}
  12442. \end{figure}
  12443. \begin{figure}[tp]
  12444. \begin{tcolorbox}[colback=white]
  12445. \small
  12446. {\if\edition\racketEd
  12447. \[
  12448. \begin{array}{l}
  12449. \gray{\ASTXIntRacket} \\ \hline
  12450. \gray{\ASTXIfRacket} \\ \hline
  12451. \ASTXGlobalRacket \\
  12452. \begin{array}{lcl}
  12453. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12454. \end{array}
  12455. \end{array}
  12456. \]
  12457. \fi}
  12458. {\if\edition\pythonEd\pythonColor
  12459. \[
  12460. \begin{array}{l}
  12461. \gray{\ASTXIntPython} \\ \hline
  12462. \gray{\ASTXIfPython} \\ \hline
  12463. \ASTXGlobalRacket \\
  12464. \begin{array}{lcl}
  12465. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12466. \end{array}
  12467. \end{array}
  12468. \]
  12469. \fi}
  12470. \end{tcolorbox}
  12471. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12472. \label{fig:x86-2}
  12473. \end{figure}
  12474. The definitions of the concrete and abstract syntax of the
  12475. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12476. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12477. of global variables.
  12478. %
  12479. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12480. \code{select\_instructions} pass on the running example.
  12481. \begin{figure}[tbp]
  12482. \centering
  12483. \begin{tcolorbox}[colback=white]
  12484. {\if\edition\racketEd
  12485. % tests/s2_17.rkt
  12486. \begin{tabular}{lll}
  12487. \begin{minipage}{0.5\textwidth}
  12488. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12489. start:
  12490. tmp9 = (global-value free_ptr);
  12491. tmp0 = (+ tmp9 16);
  12492. tmp1 = (global-value fromspace_end);
  12493. if (< tmp0 tmp1)
  12494. goto block0;
  12495. else
  12496. goto block1;
  12497. block0:
  12498. _4 = (void);
  12499. goto block9;
  12500. block1:
  12501. (collect 16)
  12502. goto block9;
  12503. block9:
  12504. alloc2 = (allocate 1 (Vector Integer));
  12505. _3 = (vector-set! alloc2 0 42);
  12506. vecinit6 = alloc2;
  12507. tmp2 = (global-value free_ptr);
  12508. tmp3 = (+ tmp2 16);
  12509. tmp4 = (global-value fromspace_end);
  12510. if (< tmp3 tmp4)
  12511. goto block7;
  12512. else
  12513. goto block8;
  12514. block7:
  12515. _8 = (void);
  12516. goto block6;
  12517. block8:
  12518. (collect 16)
  12519. goto block6;
  12520. block6:
  12521. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12522. _7 = (vector-set! alloc5 0 vecinit6);
  12523. tmp5 = (vector-ref alloc5 0);
  12524. return (vector-ref tmp5 0);
  12525. \end{lstlisting}
  12526. \end{minipage}
  12527. &$\Rightarrow$&
  12528. \begin{minipage}{0.4\textwidth}
  12529. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12530. start:
  12531. movq free_ptr(%rip), tmp9
  12532. movq tmp9, tmp0
  12533. addq $16, tmp0
  12534. movq fromspace_end(%rip), tmp1
  12535. cmpq tmp1, tmp0
  12536. jl block0
  12537. jmp block1
  12538. block0:
  12539. movq $0, _4
  12540. jmp block9
  12541. block1:
  12542. movq %r15, %rdi
  12543. movq $16, %rsi
  12544. callq collect
  12545. jmp block9
  12546. block9:
  12547. movq free_ptr(%rip), %r11
  12548. addq $16, free_ptr(%rip)
  12549. movq $3, 0(%r11)
  12550. movq %r11, alloc2
  12551. movq alloc2, %r11
  12552. movq $42, 8(%r11)
  12553. movq $0, _3
  12554. movq alloc2, vecinit6
  12555. movq free_ptr(%rip), tmp2
  12556. movq tmp2, tmp3
  12557. addq $16, tmp3
  12558. movq fromspace_end(%rip), tmp4
  12559. cmpq tmp4, tmp3
  12560. jl block7
  12561. jmp block8
  12562. block7:
  12563. movq $0, _8
  12564. jmp block6
  12565. block8:
  12566. movq %r15, %rdi
  12567. movq $16, %rsi
  12568. callq collect
  12569. jmp block6
  12570. block6:
  12571. movq free_ptr(%rip), %r11
  12572. addq $16, free_ptr(%rip)
  12573. movq $131, 0(%r11)
  12574. movq %r11, alloc5
  12575. movq alloc5, %r11
  12576. movq vecinit6, 8(%r11)
  12577. movq $0, _7
  12578. movq alloc5, %r11
  12579. movq 8(%r11), tmp5
  12580. movq tmp5, %r11
  12581. movq 8(%r11), %rax
  12582. jmp conclusion
  12583. \end{lstlisting}
  12584. \end{minipage}
  12585. \end{tabular}
  12586. \fi}
  12587. {\if\edition\pythonEd
  12588. % tests/tuple/get_get.py
  12589. \begin{tabular}{lll}
  12590. \begin{minipage}{0.5\textwidth}
  12591. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12592. start:
  12593. init.514 = 42
  12594. tmp.517 = free_ptr
  12595. tmp.518 = (tmp.517 + 16)
  12596. tmp.519 = fromspace_end
  12597. if tmp.518 < tmp.519:
  12598. goto block.529
  12599. else:
  12600. goto block.530
  12601. block.529:
  12602. goto block.528
  12603. block.530:
  12604. collect(16)
  12605. goto block.528
  12606. block.528:
  12607. alloc.513 = allocate(1,tuple[int])
  12608. alloc.513:tuple[int][0] = init.514
  12609. v1 = alloc.513
  12610. init.516 = v1
  12611. tmp.520 = free_ptr
  12612. tmp.521 = (tmp.520 + 16)
  12613. tmp.522 = fromspace_end
  12614. if tmp.521 < tmp.522:
  12615. goto block.526
  12616. else:
  12617. goto block.527
  12618. block.526:
  12619. goto block.525
  12620. block.527:
  12621. collect(16)
  12622. goto block.525
  12623. block.525:
  12624. alloc.515 = allocate(1,tuple[tuple[int]])
  12625. alloc.515:tuple[tuple[int]][0] = init.516
  12626. v2 = alloc.515
  12627. tmp.523 = v2[0]
  12628. tmp.524 = tmp.523[0]
  12629. print(tmp.524)
  12630. return 0
  12631. \end{lstlisting}
  12632. \end{minipage}
  12633. &$\Rightarrow$&
  12634. \begin{minipage}{0.4\textwidth}
  12635. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12636. start:
  12637. movq $42, init.514
  12638. movq free_ptr(%rip), tmp.517
  12639. movq tmp.517, tmp.518
  12640. addq $16, tmp.518
  12641. movq fromspace_end(%rip), tmp.519
  12642. cmpq tmp.519, tmp.518
  12643. jl block.529
  12644. jmp block.530
  12645. block.529:
  12646. jmp block.528
  12647. block.530:
  12648. movq %r15, %rdi
  12649. movq $16, %rsi
  12650. callq collect
  12651. jmp block.528
  12652. block.528:
  12653. movq free_ptr(%rip), %r11
  12654. addq $16, free_ptr(%rip)
  12655. movq $3, 0(%r11)
  12656. movq %r11, alloc.513
  12657. movq alloc.513, %r11
  12658. movq init.514, 8(%r11)
  12659. movq alloc.513, v1
  12660. movq v1, init.516
  12661. movq free_ptr(%rip), tmp.520
  12662. movq tmp.520, tmp.521
  12663. addq $16, tmp.521
  12664. movq fromspace_end(%rip), tmp.522
  12665. cmpq tmp.522, tmp.521
  12666. jl block.526
  12667. jmp block.527
  12668. block.526:
  12669. jmp block.525
  12670. block.527:
  12671. movq %r15, %rdi
  12672. movq $16, %rsi
  12673. callq collect
  12674. jmp block.525
  12675. block.525:
  12676. movq free_ptr(%rip), %r11
  12677. addq $16, free_ptr(%rip)
  12678. movq $131, 0(%r11)
  12679. movq %r11, alloc.515
  12680. movq alloc.515, %r11
  12681. movq init.516, 8(%r11)
  12682. movq alloc.515, v2
  12683. movq v2, %r11
  12684. movq 8(%r11), %r11
  12685. movq %r11, tmp.523
  12686. movq tmp.523, %r11
  12687. movq 8(%r11), %r11
  12688. movq %r11, tmp.524
  12689. movq tmp.524, %rdi
  12690. callq print_int
  12691. movq $0, %rax
  12692. jmp conclusion
  12693. \end{lstlisting}
  12694. \end{minipage}
  12695. \end{tabular}
  12696. \fi}
  12697. \end{tcolorbox}
  12698. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12699. \code{select\_instructions} (\emph{right}) on the running example.}
  12700. \label{fig:select-instr-output-gc}
  12701. \end{figure}
  12702. \clearpage
  12703. \section{Register Allocation}
  12704. \label{sec:reg-alloc-gc}
  12705. \index{subject}{register allocation}
  12706. As discussed previously in this chapter, the garbage collector needs to
  12707. access all the pointers in the root set, that is, all variables that
  12708. are tuples. It will be the responsibility of the register allocator
  12709. to make sure that
  12710. \begin{enumerate}
  12711. \item the root stack is used for spilling tuple-typed variables, and
  12712. \item if a tuple-typed variable is live during a call to the
  12713. collector, it must be spilled to ensure that it is visible to the
  12714. collector.
  12715. \end{enumerate}
  12716. The latter responsibility can be handled during construction of the
  12717. interference graph, by adding interference edges between the call-live
  12718. tuple-typed variables and all the callee-saved registers. (They
  12719. already interfere with the caller-saved registers.)
  12720. %
  12721. \racket{The type information for variables is in the \code{Program}
  12722. form, so we recommend adding another parameter to the
  12723. \code{build\_interference} function to communicate this alist.}
  12724. %
  12725. \python{The type information for variables is generated by the type
  12726. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12727. the \code{CProgram} AST mode. You'll need to propagate that
  12728. information so that it is available in this pass.}
  12729. The spilling of tuple-typed variables to the root stack can be handled
  12730. after graph coloring, in choosing how to assign the colors
  12731. (integers) to registers and stack locations. The
  12732. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12733. changes to also record the number of spills to the root stack.
  12734. % build-interference
  12735. %
  12736. % callq
  12737. % extra parameter for var->type assoc. list
  12738. % update 'program' and 'if'
  12739. % allocate-registers
  12740. % allocate spilled vectors to the rootstack
  12741. % don't change color-graph
  12742. % TODO:
  12743. %\section{Patch Instructions}
  12744. %[mention that global variables are memory references]
  12745. \section{Prelude and Conclusion}
  12746. \label{sec:print-x86-gc}
  12747. \label{sec:prelude-conclusion-x86-gc}
  12748. \index{subject}{prelude}\index{subject}{conclusion}
  12749. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12750. \code{prelude\_and\_conclusion} pass on the running example. In the
  12751. prelude of the \code{main} function, we allocate space
  12752. on the root stack to make room for the spills of tuple-typed
  12753. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12754. taking care that the root stack grows up instead of down. For the
  12755. running example, there was just one spill, so we increment \code{r15}
  12756. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12757. One issue that deserves special care is that there may be a call to
  12758. \code{collect} prior to the initializing assignments for all the
  12759. variables in the root stack. We do not want the garbage collector to
  12760. mistakenly determine that some uninitialized variable is a pointer that
  12761. needs to be followed. Thus, we zero out all locations on the root
  12762. stack in the prelude of \code{main}. In
  12763. figure~\ref{fig:print-x86-output-gc}, the instruction
  12764. %
  12765. \lstinline{movq $0, 0(%r15)}
  12766. %
  12767. is sufficient to accomplish this task because there is only one spill.
  12768. In general, we have to clear as many words as there are spills of
  12769. tuple-typed variables. The garbage collector tests each root to see
  12770. if it is null prior to dereferencing it.
  12771. \begin{figure}[htbp]
  12772. \begin{tcolorbox}[colback=white]
  12773. {\if\edition\racketEd
  12774. \begin{minipage}[t]{0.5\textwidth}
  12775. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12776. .globl main
  12777. main:
  12778. pushq %rbp
  12779. movq %rsp, %rbp
  12780. subq $0, %rsp
  12781. movq $65536, %rdi
  12782. movq $65536, %rsi
  12783. callq initialize
  12784. movq rootstack_begin(%rip), %r15
  12785. movq $0, 0(%r15)
  12786. addq $8, %r15
  12787. jmp start
  12788. conclusion:
  12789. subq $8, %r15
  12790. addq $0, %rsp
  12791. popq %rbp
  12792. retq
  12793. \end{lstlisting}
  12794. \end{minipage}
  12795. \fi}
  12796. {\if\edition\pythonEd
  12797. \begin{minipage}[t]{0.5\textwidth}
  12798. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12799. .globl main
  12800. main:
  12801. pushq %rbp
  12802. movq %rsp, %rbp
  12803. pushq %rbx
  12804. subq $8, %rsp
  12805. movq $65536, %rdi
  12806. movq $16, %rsi
  12807. callq initialize
  12808. movq rootstack_begin(%rip), %r15
  12809. movq $0, 0(%r15)
  12810. addq $8, %r15
  12811. jmp start
  12812. conclusion:
  12813. subq $8, %r15
  12814. addq $8, %rsp
  12815. popq %rbx
  12816. popq %rbp
  12817. retq
  12818. \end{lstlisting}
  12819. \end{minipage}
  12820. \fi}
  12821. \end{tcolorbox}
  12822. \caption{The prelude and conclusion for the running example.}
  12823. \label{fig:print-x86-output-gc}
  12824. \end{figure}
  12825. \begin{figure}[tbp]
  12826. \begin{tcolorbox}[colback=white]
  12827. {\if\edition\racketEd
  12828. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12829. \node (Lvec) at (0,2) {\large \LangVec{}};
  12830. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12831. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12832. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12833. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12834. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12835. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12836. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12837. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12838. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12839. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12840. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12841. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12842. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12843. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12844. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12845. \path[->,bend left=15] (Lvec-4) edge [right] node
  12846. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12847. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12848. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12849. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12850. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12851. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12852. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12853. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12854. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12855. \end{tikzpicture}
  12856. \fi}
  12857. {\if\edition\pythonEd\pythonColor
  12858. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12859. \node (Lvec) at (0,2) {\large \LangVec{}};
  12860. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12861. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12862. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12863. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12864. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12865. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12866. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12867. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12868. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12869. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12870. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12871. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12872. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12873. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12874. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12875. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12876. \end{tikzpicture}
  12877. \fi}
  12878. \end{tcolorbox}
  12879. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12880. \label{fig:Lvec-passes}
  12881. \end{figure}
  12882. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12883. for the compilation of \LangVec{}.
  12884. \clearpage
  12885. {\if\edition\racketEd
  12886. \section{Challenge: Simple Structures}
  12887. \label{sec:simple-structures}
  12888. \index{subject}{struct}
  12889. \index{subject}{structure}
  12890. The language \LangStruct{} extends \LangVec{} with support for simple
  12891. structures. The definition of its concrete syntax is shown in
  12892. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12893. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12894. in Typed Racket is a user-defined data type that contains named fields
  12895. and that is heap allocated\index{subject}{heap allocated},
  12896. similarly to a vector. The following is an
  12897. example of a structure definition, in this case the definition of a
  12898. \code{point} type:
  12899. \begin{lstlisting}
  12900. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12901. \end{lstlisting}
  12902. \newcommand{\LstructGrammarRacket}{
  12903. \begin{array}{lcl}
  12904. \Type &::=& \Var \\
  12905. \Exp &::=& (\Var\;\Exp \ldots)\\
  12906. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12907. \end{array}
  12908. }
  12909. \newcommand{\LstructASTRacket}{
  12910. \begin{array}{lcl}
  12911. \Type &::=& \VAR{\Var} \\
  12912. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12913. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12914. \end{array}
  12915. }
  12916. \begin{figure}[tbp]
  12917. \centering
  12918. \begin{tcolorbox}[colback=white]
  12919. \[
  12920. \begin{array}{l}
  12921. \gray{\LintGrammarRacket{}} \\ \hline
  12922. \gray{\LvarGrammarRacket{}} \\ \hline
  12923. \gray{\LifGrammarRacket{}} \\ \hline
  12924. \gray{\LwhileGrammarRacket} \\ \hline
  12925. \gray{\LtupGrammarRacket} \\ \hline
  12926. \LstructGrammarRacket \\
  12927. \begin{array}{lcl}
  12928. \LangStruct{} &::=& \Def \ldots \; \Exp
  12929. \end{array}
  12930. \end{array}
  12931. \]
  12932. \end{tcolorbox}
  12933. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12934. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12935. \label{fig:Lstruct-concrete-syntax}
  12936. \end{figure}
  12937. \begin{figure}[tbp]
  12938. \centering
  12939. \begin{tcolorbox}[colback=white]
  12940. \small
  12941. \[
  12942. \begin{array}{l}
  12943. \gray{\LintASTRacket{}} \\ \hline
  12944. \gray{\LvarASTRacket{}} \\ \hline
  12945. \gray{\LifASTRacket{}} \\ \hline
  12946. \gray{\LwhileASTRacket} \\ \hline
  12947. \gray{\LtupASTRacket} \\ \hline
  12948. \LstructASTRacket \\
  12949. \begin{array}{lcl}
  12950. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12951. \end{array}
  12952. \end{array}
  12953. \]
  12954. \end{tcolorbox}
  12955. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12956. (figure~\ref{fig:Lvec-syntax}).}
  12957. \label{fig:Lstruct-syntax}
  12958. \end{figure}
  12959. An instance of a structure is created using function-call syntax, with
  12960. the name of the structure in the function position, as follows:
  12961. \begin{lstlisting}
  12962. (point 7 12)
  12963. \end{lstlisting}
  12964. Function-call syntax is also used to read a field of a structure. The
  12965. function name is formed by the structure name, a dash, and the field
  12966. name. The following example uses \code{point-x} and \code{point-y} to
  12967. access the \code{x} and \code{y} fields of two point instances:
  12968. \begin{center}
  12969. \begin{lstlisting}
  12970. (let ([pt1 (point 7 12)])
  12971. (let ([pt2 (point 4 3)])
  12972. (+ (- (point-x pt1) (point-x pt2))
  12973. (- (point-y pt1) (point-y pt2)))))
  12974. \end{lstlisting}
  12975. \end{center}
  12976. Similarly, to write to a field of a structure, use its set function,
  12977. whose name starts with \code{set-}, followed by the structure name,
  12978. then a dash, then the field name, and finally with an exclamation
  12979. mark. The following example uses \code{set-point-x!} to change the
  12980. \code{x} field from \code{7} to \code{42}:
  12981. \begin{center}
  12982. \begin{lstlisting}
  12983. (let ([pt (point 7 12)])
  12984. (let ([_ (set-point-x! pt 42)])
  12985. (point-x pt)))
  12986. \end{lstlisting}
  12987. \end{center}
  12988. \begin{exercise}\normalfont\normalsize
  12989. Create a type checker for \LangStruct{} by extending the type
  12990. checker for \LangVec{}. Extend your compiler with support for simple
  12991. structures, compiling \LangStruct{} to x86 assembly code. Create
  12992. five new test cases that use structures, and test your compiler.
  12993. \end{exercise}
  12994. % TODO: create an interpreter for L_struct
  12995. \clearpage
  12996. \fi}
  12997. \section{Challenge: Arrays}
  12998. \label{sec:arrays}
  12999. % TODO mention trapped-error
  13000. In this chapter we have studied tuples, that is, heterogeneous
  13001. sequences of elements whose length is determined at compile time. This
  13002. challenge is also about sequences, but this time the length is
  13003. determined at runtime and all the elements have the same type (they
  13004. are homogeneous). We use the term \emph{array} for this latter kind of
  13005. sequence.
  13006. %
  13007. \racket{
  13008. The Racket language does not distinguish between tuples and arrays;
  13009. they are both represented by vectors. However, Typed Racket
  13010. distinguishes between tuples and arrays: the \code{Vector} type is for
  13011. tuples, and the \code{Vectorof} type is for arrays.}%
  13012. \python{Arrays correspond to the \code{list} type in the Python language.}
  13013. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13014. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13015. presents the definition of the abstract syntax, extending \LangVec{}
  13016. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13017. \racket{\code{make-vector} primitive operator for creating an array,
  13018. whose arguments are the length of the array and an initial value for
  13019. all the elements in the array.}%
  13020. \python{bracket notation for creating an array literal.}
  13021. \racket{The \code{vector-length},
  13022. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13023. for tuples become overloaded for use with arrays.}
  13024. \python{
  13025. The subscript operator becomes overloaded for use with arrays and tuples
  13026. and now may appear on the left-hand side of an assignment.
  13027. Note that the index of the subscript, when applied to an array, may be an
  13028. arbitrary expression and not exclusively a constant integer.
  13029. The \code{len} function is also applicable to arrays.
  13030. }
  13031. %
  13032. We include integer multiplication in \LangArray{} because it is
  13033. useful in many examples involving arrays such as computing the
  13034. inner product of two arrays (figure~\ref{fig:inner_product}).
  13035. \newcommand{\LarrayGrammarRacket}{
  13036. \begin{array}{lcl}
  13037. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13038. \Exp &::=& \CMUL{\Exp}{\Exp}
  13039. \MID \CMAKEVEC{\Exp}{\Exp}
  13040. \end{array}
  13041. }
  13042. \newcommand{\LarrayASTRacket}{
  13043. \begin{array}{lcl}
  13044. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13045. \Exp &::=& \MUL{\Exp}{\Exp}
  13046. \MID \MAKEVEC{\Exp}{\Exp}
  13047. \end{array}
  13048. }
  13049. \newcommand{\LarrayGrammarPython}{
  13050. \begin{array}{lcl}
  13051. \Type &::=& \key{list}\LS\Type\RS \\
  13052. \Exp &::=& \CMUL{\Exp}{\Exp}
  13053. \MID \CGET{\Exp}{\Exp}
  13054. \MID \LS \Exp \code{,} \ldots \RS \\
  13055. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13056. \end{array}
  13057. }
  13058. \newcommand{\LarrayASTPython}{
  13059. \begin{array}{lcl}
  13060. \Type &::=& \key{ListType}\LP\Type\RP \\
  13061. \Exp &::=& \MUL{\Exp}{\Exp}
  13062. \MID \GET{\Exp}{\Exp} \\
  13063. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13064. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13065. \end{array}
  13066. }
  13067. \begin{figure}[tp]
  13068. \centering
  13069. \begin{tcolorbox}[colback=white]
  13070. \small
  13071. {\if\edition\racketEd
  13072. \[
  13073. \begin{array}{l}
  13074. \gray{\LintGrammarRacket{}} \\ \hline
  13075. \gray{\LvarGrammarRacket{}} \\ \hline
  13076. \gray{\LifGrammarRacket{}} \\ \hline
  13077. \gray{\LwhileGrammarRacket} \\ \hline
  13078. \gray{\LtupGrammarRacket} \\ \hline
  13079. \LarrayGrammarRacket \\
  13080. \begin{array}{lcl}
  13081. \LangArray{} &::=& \Exp
  13082. \end{array}
  13083. \end{array}
  13084. \]
  13085. \fi}
  13086. {\if\edition\pythonEd\pythonColor
  13087. \[
  13088. \begin{array}{l}
  13089. \gray{\LintGrammarPython{}} \\ \hline
  13090. \gray{\LvarGrammarPython{}} \\ \hline
  13091. \gray{\LifGrammarPython{}} \\ \hline
  13092. \gray{\LwhileGrammarPython} \\ \hline
  13093. \gray{\LtupGrammarPython} \\ \hline
  13094. \LarrayGrammarPython \\
  13095. \begin{array}{rcl}
  13096. \LangArrayM{} &::=& \Stmt^{*}
  13097. \end{array}
  13098. \end{array}
  13099. \]
  13100. \fi}
  13101. \end{tcolorbox}
  13102. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13103. \label{fig:Lvecof-concrete-syntax}
  13104. \end{figure}
  13105. \begin{figure}[tp]
  13106. \centering
  13107. \begin{tcolorbox}[colback=white]
  13108. \small
  13109. {\if\edition\racketEd
  13110. \[
  13111. \begin{array}{l}
  13112. \gray{\LintASTRacket{}} \\ \hline
  13113. \gray{\LvarASTRacket{}} \\ \hline
  13114. \gray{\LifASTRacket{}} \\ \hline
  13115. \gray{\LwhileASTRacket} \\ \hline
  13116. \gray{\LtupASTRacket} \\ \hline
  13117. \LarrayASTRacket \\
  13118. \begin{array}{lcl}
  13119. \LangArray{} &::=& \Exp
  13120. \end{array}
  13121. \end{array}
  13122. \]
  13123. \fi}
  13124. {\if\edition\pythonEd\pythonColor
  13125. \[
  13126. \begin{array}{l}
  13127. \gray{\LintASTPython{}} \\ \hline
  13128. \gray{\LvarASTPython{}} \\ \hline
  13129. \gray{\LifASTPython{}} \\ \hline
  13130. \gray{\LwhileASTPython} \\ \hline
  13131. \gray{\LtupASTPython} \\ \hline
  13132. \LarrayASTPython \\
  13133. \begin{array}{rcl}
  13134. \LangArrayM{} &::=& \Stmt^{*}
  13135. \end{array}
  13136. \end{array}
  13137. \]
  13138. \fi}
  13139. \end{tcolorbox}
  13140. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13141. \label{fig:Lvecof-syntax}
  13142. \end{figure}
  13143. \begin{figure}[tp]
  13144. \begin{tcolorbox}[colback=white]
  13145. {\if\edition\racketEd
  13146. % TODO: remove the function from the following example, like the python version -Jeremy
  13147. \begin{lstlisting}
  13148. (let ([A (make-vector 2 2)])
  13149. (let ([B (make-vector 2 3)])
  13150. (let ([i 0])
  13151. (let ([prod 0])
  13152. (begin
  13153. (while (< i n)
  13154. (begin
  13155. (set! prod (+ prod (* (vector-ref A i)
  13156. (vector-ref B i))))
  13157. (set! i (+ i 1))))
  13158. prod)))))
  13159. \end{lstlisting}
  13160. \fi}
  13161. {\if\edition\pythonEd\pythonColor
  13162. \begin{lstlisting}
  13163. A = [2, 2]
  13164. B = [3, 3]
  13165. i = 0
  13166. prod = 0
  13167. while i != len(A):
  13168. prod = prod + A[i] * B[i]
  13169. i = i + 1
  13170. print(prod)
  13171. \end{lstlisting}
  13172. \fi}
  13173. \end{tcolorbox}
  13174. \caption{Example program that computes the inner product.}
  13175. \label{fig:inner_product}
  13176. \end{figure}
  13177. {\if\edition\racketEd
  13178. %
  13179. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13180. checker for \LangArray{}. The result type of
  13181. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13182. of the initializing expression. The length expression is required to
  13183. have type \code{Integer}. The type checking of the operators
  13184. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13185. updated to handle the situation in which the vector has type
  13186. \code{Vectorof}. In these cases we translate the operators to their
  13187. \code{vectorof} form so that later passes can easily distinguish
  13188. between operations on tuples versus arrays. We override the
  13189. \code{operator-types} method to provide the type signature for
  13190. multiplication: it takes two integers and returns an integer. \fi}
  13191. {\if\edition\pythonEd\pythonColor
  13192. %
  13193. The type checker for \LangArray{} is defined in
  13194. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  13195. is \code{list[T]}, where \code{T} is the type of the initializing
  13196. expressions. The type checking of the \code{len} function and the
  13197. subscript operator are updated to handle lists. The type checker now
  13198. also handles a subscript on the left-hand side of an assignment.
  13199. Regarding multiplication, it takes two integers and returns an
  13200. integer.
  13201. %
  13202. \fi}
  13203. \begin{figure}[tbp]
  13204. \begin{tcolorbox}[colback=white]
  13205. {\if\edition\racketEd
  13206. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13207. (define type-check-Lvecof-class
  13208. (class type-check-Lvec-class
  13209. (super-new)
  13210. (inherit check-type-equal?)
  13211. (define/override (operator-types)
  13212. (append '((* . ((Integer Integer) . Integer)))
  13213. (super operator-types)))
  13214. (define/override (type-check-exp env)
  13215. (lambda (e)
  13216. (define recur (type-check-exp env))
  13217. (match e
  13218. [(Prim 'make-vector (list e1 e2))
  13219. (define-values (e1^ t1) (recur e1))
  13220. (define-values (e2^ elt-type) (recur e2))
  13221. (define vec-type `(Vectorof ,elt-type))
  13222. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13223. [(Prim 'vector-ref (list e1 e2))
  13224. (define-values (e1^ t1) (recur e1))
  13225. (define-values (e2^ t2) (recur e2))
  13226. (match* (t1 t2)
  13227. [(`(Vectorof ,elt-type) 'Integer)
  13228. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13229. [(other wise) ((super type-check-exp env) e)])]
  13230. [(Prim 'vector-set! (list e1 e2 e3) )
  13231. (define-values (e-vec t-vec) (recur e1))
  13232. (define-values (e2^ t2) (recur e2))
  13233. (define-values (e-arg^ t-arg) (recur e3))
  13234. (match t-vec
  13235. [`(Vectorof ,elt-type)
  13236. (check-type-equal? elt-type t-arg e)
  13237. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13238. [else ((super type-check-exp env) e)])]
  13239. [(Prim 'vector-length (list e1))
  13240. (define-values (e1^ t1) (recur e1))
  13241. (match t1
  13242. [`(Vectorof ,t)
  13243. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13244. [else ((super type-check-exp env) e)])]
  13245. [else ((super type-check-exp env) e)])))
  13246. ))
  13247. (define (type-check-Lvecof p)
  13248. (send (new type-check-Lvecof-class) type-check-program p))
  13249. \end{lstlisting}
  13250. \fi}
  13251. {\if\edition\pythonEd\pythonColor
  13252. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13253. class TypeCheckLarray(TypeCheckLtup):
  13254. def type_check_exp(self, e, env):
  13255. match e:
  13256. case ast.List(es, Load()):
  13257. ts = [self.type_check_exp(e, env) for e in es]
  13258. elt_ty = ts[0]
  13259. for (ty, elt) in zip(ts, es):
  13260. self.check_type_equal(elt_ty, ty, elt)
  13261. e.has_type = ListType(elt_ty)
  13262. return e.has_type
  13263. case Call(Name('len'), [tup]):
  13264. tup_t = self.type_check_exp(tup, env)
  13265. tup.has_type = tup_t
  13266. match tup_t:
  13267. case TupleType(ts):
  13268. return IntType()
  13269. case ListType(ty):
  13270. return IntType()
  13271. case _:
  13272. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13273. case Subscript(tup, index, Load()):
  13274. tup_ty = self.type_check_exp(tup, env)
  13275. index_ty = self.type_check_exp(index, env)
  13276. self.check_type_equal(index_ty, IntType(), index)
  13277. match tup_ty:
  13278. case TupleType(ts):
  13279. match index:
  13280. case Constant(i):
  13281. return ts[i]
  13282. case _:
  13283. raise Exception('subscript required constant integer index')
  13284. case ListType(ty):
  13285. return ty
  13286. case _:
  13287. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13288. case BinOp(left, Mult(), right):
  13289. l = self.type_check_exp(left, env)
  13290. self.check_type_equal(l, IntType(), left)
  13291. r = self.type_check_exp(right, env)
  13292. self.check_type_equal(r, IntType(), right)
  13293. return IntType()
  13294. case _:
  13295. return super().type_check_exp(e, env)
  13296. \end{lstlisting}
  13297. \fi}
  13298. \end{tcolorbox}
  13299. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13300. \label{fig:type-check-Lvecof}
  13301. \end{figure}
  13302. {\if\edition\pythonEd
  13303. \begin{figure}[tbp]
  13304. \begin{tcolorbox}[colback=white]
  13305. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13306. def type_check_stmts(self, ss, env):
  13307. if len(ss) == 0:
  13308. return VoidType()
  13309. match ss[0]:
  13310. case Assign([Subscript(tup, index, Store())], value):
  13311. tup_t = self.type_check_exp(tup, env)
  13312. value_t = self.type_check_exp(value, env)
  13313. index_ty = self.type_check_exp(index, env)
  13314. self.check_type_equal(index_ty, IntType(), index)
  13315. match tup_t:
  13316. case ListType(ty):
  13317. self.check_type_equal(ty, value_t, ss[0])
  13318. case TupleType(ts):
  13319. return self.type_check_stmts(ss, env)
  13320. case _:
  13321. raise Exception('type_check_stmts: '
  13322. 'expected tuple or list, not ' + repr(tup_t))
  13323. return self.type_check_stmts(ss[1:], env)
  13324. case _:
  13325. return super().type_check_stmts(ss, env)
  13326. \end{lstlisting}
  13327. \end{tcolorbox}
  13328. \caption{Type checker for the \LangArray{} language, part 2.}
  13329. \label{fig:type-check-Lvecof-part2}
  13330. \end{figure}
  13331. \fi}
  13332. The definition of the interpreter for \LangArray{} is shown in
  13333. \racket{figure~\ref{fig:interp-Lvecof}}
  13334. \python{figures~\ref{fig:interp-Lvecof} and \ref{fig:type-check-Lvecof-part2}}.
  13335. \racket{The \code{make-vector} operator is
  13336. interpreted using Racket's \code{make-vector} function,
  13337. and multiplication is interpreted using \code{fx*},
  13338. which is multiplication for \code{fixnum} integers.
  13339. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13340. we translate array access operations
  13341. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13342. which we interpret using \code{vector} operations with additional
  13343. bounds checks that signal a \code{trapped-error}.
  13344. }
  13345. %
  13346. \python{We implement list creation with a Python list comprehension,
  13347. and multiplication is implemented with 64-bit multiplication. We
  13348. add a case to handle a subscript on the left-hand side of
  13349. assignment. Other uses of subscript can be handled by the existing
  13350. code for tuples.}
  13351. \begin{figure}[tbp]
  13352. \begin{tcolorbox}[colback=white]
  13353. {\if\edition\racketEd
  13354. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13355. (define interp-Lvecof-class
  13356. (class interp-Lvec-class
  13357. (super-new)
  13358. (define/override (interp-op op)
  13359. (match op
  13360. ['make-vector make-vector]
  13361. ['vectorof-length vector-length]
  13362. ['vectorof-ref
  13363. (lambda (v i)
  13364. (if (< i (vector-length v))
  13365. (vector-ref v i)
  13366. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13367. ['vectorof-set!
  13368. (lambda (v i e)
  13369. (if (< i (vector-length v))
  13370. (vector-set! v i e)
  13371. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13372. [else (super interp-op op)]))
  13373. ))
  13374. (define (interp-Lvecof p)
  13375. (send (new interp-Lvecof-class) interp-program p))
  13376. \end{lstlisting}
  13377. \fi}
  13378. {\if\edition\pythonEd\pythonColor
  13379. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13380. class InterpLarray(InterpLtup):
  13381. def interp_exp(self, e, env):
  13382. match e:
  13383. case ast.List(es, Load()):
  13384. return [self.interp_exp(e, env) for e in es]
  13385. case BinOp(left, Mult(), right):
  13386. l = self.interp_exp(left, env)
  13387. r = self.interp_exp(right, env)
  13388. return mul64(l, r)
  13389. case Subscript(tup, index, Load()):
  13390. t = self.interp_exp(tup, env)
  13391. n = self.interp_exp(index, env)
  13392. if n < len(t):
  13393. return t[n]
  13394. else:
  13395. raise TrappedError('array index out of bounds')
  13396. case _:
  13397. return super().interp_exp(e, env)
  13398. def interp_stmt(self, s, env, cont):
  13399. match s:
  13400. case Assign([Subscript(tup, index)], value):
  13401. t = self.interp_exp(tup, env)
  13402. n = self.interp_exp(index, env)
  13403. if n < len(t):
  13404. t[n] = self.interp_exp(value, env)
  13405. else:
  13406. raise TrappedError('array index out of bounds')
  13407. return self.interp_stmts(cont, env)
  13408. case _:
  13409. return super().interp_stmt(s, env, cont)
  13410. \end{lstlisting}
  13411. \fi}
  13412. \end{tcolorbox}
  13413. \caption{Interpreter for \LangArray{}.}
  13414. \label{fig:interp-Lvecof}
  13415. \end{figure}
  13416. \subsection{Data Representation}
  13417. \label{sec:array-rep}
  13418. Just as with tuples, we store arrays on the heap, which means that the
  13419. garbage collector will need to inspect arrays. An immediate thought is
  13420. to use the same representation for arrays that we use for tuples.
  13421. However, we limit tuples to a length of fifty so that their length and
  13422. pointer mask can fit into the 64-bit tag at the beginning of each
  13423. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13424. millions of elements, so we need more bits to store the length.
  13425. However, because arrays are homogeneous, we need only 1 bit for the
  13426. pointer mask instead of 1 bit per array element. Finally, the
  13427. garbage collector must be able to distinguish between tuples
  13428. and arrays, so we need to reserve one bit for that purpose. We
  13429. arrive at the following layout for the 64-bit tag at the beginning of
  13430. an array:
  13431. \begin{itemize}
  13432. \item The right-most bit is the forwarding bit, just as in a tuple.
  13433. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13434. that it is not.
  13435. \item The next bit to the left is the pointer mask. A $0$ indicates
  13436. that none of the elements are pointers to the heap, and a $1$
  13437. indicates that all the elements are pointers.
  13438. \item The next $60$ bits store the length of the array.
  13439. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13440. and an array ($1$).
  13441. \item The left-most bit is reserved as explained in
  13442. chapter~\ref{ch:Lgrad}.
  13443. \end{itemize}
  13444. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13445. %% differentiate the kinds of values that have been injected into the
  13446. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13447. %% to indicate that the value is an array.
  13448. In the following subsections we provide hints regarding how to update
  13449. the passes to handle arrays.
  13450. \subsection{Overload Resolution}
  13451. \label{sec:array-resolution}
  13452. As noted previously, with the addition of arrays, several operators
  13453. have become \emph{overloaded}; that is, they can be applied to values
  13454. of more than one type. In this case, the element access and length
  13455. operators can be applied to both tuples and arrays. This kind of
  13456. overloading is quite common in programming languages, so many
  13457. compilers perform \emph{overload resolution}\index{subject}{overload
  13458. resolution} to handle it. The idea is to translate each overloaded
  13459. operator into different operators for the different types.
  13460. Implement a new pass named \code{resolve}.
  13461. Translate the reading of an array element
  13462. into a call to
  13463. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13464. and the writing of an array element to
  13465. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13466. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13467. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13468. When these operators are applied to tuples, leave them as is.
  13469. %
  13470. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13471. field, which can be inspected to determine whether the operator
  13472. is applied to a tuple or an array.}
  13473. \subsection{Bounds Checking}
  13474. Recall that the interpreter for \LangArray{} signals a
  13475. \code{trapped-error} when there is an array access that is out of
  13476. bounds. Therefore your compiler is obliged to also catch these errors
  13477. during execution and halt, signaling an error. We recommend inserting
  13478. a new pass named \code{check\_bounds} that inserts code around each
  13479. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13480. \python{subscript} operation to ensure that the index is greater than
  13481. or equal to zero and less than the array's length. If not, the program
  13482. should halt, for which we recommend using a new primitive operation
  13483. named \code{exit}.
  13484. %% \subsection{Reveal Casts}
  13485. %% The array-access operators \code{vectorof-ref} and
  13486. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13487. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13488. %% that the type checker cannot tell whether the index will be in bounds,
  13489. %% so the bounds check must be performed at run time. Recall that the
  13490. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13491. %% an \code{If} around a vector reference for update to check whether
  13492. %% the index is less than the length. You should do the same for
  13493. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13494. %% In addition, the handling of the \code{any-vector} operators in
  13495. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13496. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13497. %% generated code should test whether the tag is for tuples (\code{010})
  13498. %% or arrays (\code{110}) and then dispatch to either
  13499. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13500. %% we add a case in \code{select\_instructions} to generate the
  13501. %% appropriate instructions for accessing the array length from the
  13502. %% header of an array.
  13503. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13504. %% the generated code needs to check that the index is less than the
  13505. %% vector length, so like the code for \code{any-vector-length}, check
  13506. %% the tag to determine whether to use \code{any-vector-length} or
  13507. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13508. %% is complete, the generated code can use \code{any-vector-ref} and
  13509. %% \code{any-vector-set!} for both tuples and arrays because the
  13510. %% instructions used for those operators do not look at the tag at the
  13511. %% front of the tuple or array.
  13512. \subsection{Expose Allocation}
  13513. This pass should translate array creation into lower-level
  13514. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13515. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13516. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13517. array. The \code{AllocateArray} AST node allocates an array of the
  13518. length specified by the $\Exp$ (of type \INTTY), but does not
  13519. initialize the elements of the array. Generate code in this pass to
  13520. initialize the elements analogous to the case for tuples.
  13521. {\if\edition\racketEd
  13522. \subsection{Uncover \texttt{get!}}
  13523. \label{sec:uncover-get-bang-vecof}
  13524. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13525. \code{uncover-get!-exp}.
  13526. \fi}
  13527. \subsection{Remove Complex Operands}
  13528. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13529. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13530. complex, and its subexpression must be atomic.
  13531. \subsection{Explicate Control}
  13532. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13533. \code{explicate\_assign}.
  13534. \subsection{Select Instructions}
  13535. \index{subject}{select instructions}
  13536. Generate instructions for \code{AllocateArray} similar to those for
  13537. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13538. except that the tag at the front of the array should instead use the
  13539. representation discussed in section~\ref{sec:array-rep}.
  13540. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13541. extract the length from the tag.
  13542. The instructions generated for accessing an element of an array differ
  13543. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13544. that the index is not a constant so you need to generate instructions
  13545. that compute the offset at runtime.
  13546. Compile the \code{exit} primitive into a call to the \code{exit}
  13547. function of the C standard library, with an argument of $255$.
  13548. %% Also, note that assignment to an array element may appear in
  13549. %% as a stand-alone statement, so make sure to handle that situation in
  13550. %% this pass.
  13551. %% Finally, the instructions for \code{any-vectorof-length} should be
  13552. %% similar to those for \code{vectorof-length}, except that one must
  13553. %% first project the array by writing zeroes into the $3$-bit tag
  13554. \begin{exercise}\normalfont\normalsize
  13555. Implement a compiler for the \LangArray{} language by extending your
  13556. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13557. programs, including the one shown in figure~\ref{fig:inner_product}
  13558. and also a program that multiplies two matrices. Note that although
  13559. matrices are two-dimensional arrays, they can be encoded into
  13560. one-dimensional arrays by laying out each row in the array, one after
  13561. the next.
  13562. \end{exercise}
  13563. {\if\edition\racketEd
  13564. \section{Challenge: Generational Collection}
  13565. The copying collector described in section~\ref{sec:GC} can incur
  13566. significant runtime overhead because the call to \code{collect} takes
  13567. time proportional to all the live data. One way to reduce this
  13568. overhead is to reduce how much data is inspected in each call to
  13569. \code{collect}. In particular, researchers have observed that recently
  13570. allocated data is more likely to become garbage then data that has
  13571. survived one or more previous calls to \code{collect}. This insight
  13572. motivated the creation of \emph{generational garbage collectors}
  13573. \index{subject}{generational garbage collector} that
  13574. (1) segregate data according to its age into two or more generations;
  13575. (2) allocate less space for younger generations, so collecting them is
  13576. faster, and more space for the older generations; and (3) perform
  13577. collection on the younger generations more frequently than on older
  13578. generations~\citep{Wilson:1992fk}.
  13579. For this challenge assignment, the goal is to adapt the copying
  13580. collector implemented in \code{runtime.c} to use two generations, one
  13581. for young data and one for old data. Each generation consists of a
  13582. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13583. \code{collect} function to use the two generations:
  13584. \begin{enumerate}
  13585. \item Copy the young generation's FromSpace to its ToSpace and then
  13586. switch the role of the ToSpace and FromSpace.
  13587. \item If there is enough space for the requested number of bytes in
  13588. the young FromSpace, then return from \code{collect}.
  13589. \item If there is not enough space in the young FromSpace for the
  13590. requested bytes, then move the data from the young generation to the
  13591. old one with the following steps:
  13592. \begin{enumerate}
  13593. \item[a.] If there is enough room in the old FromSpace, copy the young
  13594. FromSpace to the old FromSpace and then return.
  13595. \item[b.] If there is not enough room in the old FromSpace, then collect
  13596. the old generation by copying the old FromSpace to the old ToSpace
  13597. and swap the roles of the old FromSpace and ToSpace.
  13598. \item[c.] If there is enough room now, copy the young FromSpace to the
  13599. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13600. and ToSpace for the old generation. Copy the young FromSpace and
  13601. the old FromSpace into the larger FromSpace for the old
  13602. generation and then return.
  13603. \end{enumerate}
  13604. \end{enumerate}
  13605. We recommend that you generalize the \code{cheney} function so that it
  13606. can be used for all the copies mentioned: between the young FromSpace
  13607. and ToSpace, between the old FromSpace and ToSpace, and between the
  13608. young FromSpace and old FromSpace. This can be accomplished by adding
  13609. parameters to \code{cheney} that replace its use of the global
  13610. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13611. \code{tospace\_begin}, and \code{tospace\_end}.
  13612. Note that the collection of the young generation does not traverse the
  13613. old generation. This introduces a potential problem: there may be
  13614. young data that is reachable only through pointers in the old
  13615. generation. If these pointers are not taken into account, the
  13616. collector could throw away young data that is live! One solution,
  13617. called \emph{pointer recording}, is to maintain a set of all the
  13618. pointers from the old generation into the new generation and consider
  13619. this set as part of the root set. To maintain this set, the compiler
  13620. must insert extra instructions around every \code{vector-set!}. If the
  13621. vector being modified is in the old generation, and if the value being
  13622. written is a pointer into the new generation, then that pointer must
  13623. be added to the set. Also, if the value being overwritten was a
  13624. pointer into the new generation, then that pointer should be removed
  13625. from the set.
  13626. \begin{exercise}\normalfont\normalsize
  13627. Adapt the \code{collect} function in \code{runtime.c} to implement
  13628. generational garbage collection, as outlined in this section.
  13629. Update the code generation for \code{vector-set!} to implement
  13630. pointer recording. Make sure that your new compiler and runtime
  13631. execute without error on your test suite.
  13632. \end{exercise}
  13633. \fi}
  13634. \section{Further Reading}
  13635. \citet{Appel90} describes many data representation approaches
  13636. including the ones used in the compilation of Standard ML.
  13637. There are many alternatives to copying collectors (and their bigger
  13638. siblings, the generational collectors) with regard to garbage
  13639. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13640. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13641. collectors are that allocation is fast (just a comparison and pointer
  13642. increment), there is no fragmentation, cyclic garbage is collected,
  13643. and the time complexity of collection depends only on the amount of
  13644. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13645. main disadvantages of a two-space copying collector is that it uses a
  13646. lot of extra space and takes a long time to perform the copy, though
  13647. these problems are ameliorated in generational collectors.
  13648. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13649. small objects and generate a lot of garbage, so copying and
  13650. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13651. Garbage collection is an active research topic, especially concurrent
  13652. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13653. developing new techniques and revisiting old
  13654. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13655. meet every year at the International Symposium on Memory Management to
  13656. present these findings.
  13657. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13658. \chapter{Functions}
  13659. \label{ch:Lfun}
  13660. \index{subject}{function}
  13661. \setcounter{footnote}{0}
  13662. This chapter studies the compilation of a subset of \racket{Typed
  13663. Racket}\python{Python} in which only top-level function definitions
  13664. are allowed. This kind of function appears in the C programming
  13665. language, and it serves as an important stepping-stone to implementing
  13666. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13667. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13668. \section{The \LangFun{} Language}
  13669. The concrete syntax and abstract syntax for function definitions and
  13670. function application are shown in
  13671. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13672. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13673. with zero or more function definitions. The function names from these
  13674. definitions are in scope for the entire program, including all the
  13675. function definitions, and therefore the ordering of function
  13676. definitions does not matter.
  13677. %
  13678. \python{The abstract syntax for function parameters in
  13679. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13680. consists of a parameter name and its type. This design differs from
  13681. Python's \code{ast} module, which has a more complex structure for
  13682. function parameters to handle keyword parameters,
  13683. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13684. complex Python abstract syntax into the simpler syntax shown in
  13685. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13686. \code{FunctionDef} constructor are for decorators and a type
  13687. comment, neither of which are used by our compiler. We recommend
  13688. replacing them with \code{None} in the \code{shrink} pass.
  13689. }
  13690. %
  13691. The concrete syntax for function application
  13692. \index{subject}{function application}
  13693. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13694. where the first expression
  13695. must evaluate to a function and the remaining expressions are the arguments. The
  13696. abstract syntax for function application is
  13697. $\APPLY{\Exp}{\Exp^*}$.
  13698. %% The syntax for function application does not include an explicit
  13699. %% keyword, which is error prone when using \code{match}. To alleviate
  13700. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13701. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13702. Functions are first-class in the sense that a function pointer
  13703. \index{subject}{function pointer} is data and can be stored in memory or passed
  13704. as a parameter to another function. Thus, there is a function
  13705. type, written
  13706. {\if\edition\racketEd
  13707. \begin{lstlisting}
  13708. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13709. \end{lstlisting}
  13710. \fi}
  13711. {\if\edition\pythonEd\pythonColor
  13712. \begin{lstlisting}
  13713. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13714. \end{lstlisting}
  13715. \fi}
  13716. %
  13717. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13718. through $\Type_n$ and whose return type is $\Type_R$. The main
  13719. limitation of these functions (with respect to
  13720. \racket{Racket}\python{Python} functions) is that they are not
  13721. lexically scoped. That is, the only external entities that can be
  13722. referenced from inside a function body are other globally defined
  13723. functions. The syntax of \LangFun{} prevents function definitions from
  13724. being nested inside each other.
  13725. \newcommand{\LfunGrammarRacket}{
  13726. \begin{array}{lcl}
  13727. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13728. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13729. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13730. \end{array}
  13731. }
  13732. \newcommand{\LfunASTRacket}{
  13733. \begin{array}{lcl}
  13734. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13735. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13736. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13737. \end{array}
  13738. }
  13739. \newcommand{\LfunGrammarPython}{
  13740. \begin{array}{lcl}
  13741. \Type &::=& \key{int}
  13742. \MID \key{bool} \MID \key{void}
  13743. \MID \key{tuple}\LS \Type^+ \RS
  13744. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13745. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13746. \Stmt &::=& \CRETURN{\Exp} \\
  13747. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13748. \end{array}
  13749. }
  13750. \newcommand{\LfunASTPython}{
  13751. \begin{array}{lcl}
  13752. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13753. \MID \key{TupleType}\LS\Type^+\RS\\
  13754. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13755. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13756. \Stmt &::=& \RETURN{\Exp} \\
  13757. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13758. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13759. \end{array}
  13760. }
  13761. \begin{figure}[tp]
  13762. \centering
  13763. \begin{tcolorbox}[colback=white]
  13764. \small
  13765. {\if\edition\racketEd
  13766. \[
  13767. \begin{array}{l}
  13768. \gray{\LintGrammarRacket{}} \\ \hline
  13769. \gray{\LvarGrammarRacket{}} \\ \hline
  13770. \gray{\LifGrammarRacket{}} \\ \hline
  13771. \gray{\LwhileGrammarRacket} \\ \hline
  13772. \gray{\LtupGrammarRacket} \\ \hline
  13773. \LfunGrammarRacket \\
  13774. \begin{array}{lcl}
  13775. \LangFunM{} &::=& \Def \ldots \; \Exp
  13776. \end{array}
  13777. \end{array}
  13778. \]
  13779. \fi}
  13780. {\if\edition\pythonEd\pythonColor
  13781. \[
  13782. \begin{array}{l}
  13783. \gray{\LintGrammarPython{}} \\ \hline
  13784. \gray{\LvarGrammarPython{}} \\ \hline
  13785. \gray{\LifGrammarPython{}} \\ \hline
  13786. \gray{\LwhileGrammarPython} \\ \hline
  13787. \gray{\LtupGrammarPython} \\ \hline
  13788. \LfunGrammarPython \\
  13789. \begin{array}{rcl}
  13790. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13791. \end{array}
  13792. \end{array}
  13793. \]
  13794. \fi}
  13795. \end{tcolorbox}
  13796. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13797. \label{fig:Lfun-concrete-syntax}
  13798. \end{figure}
  13799. \begin{figure}[tp]
  13800. \centering
  13801. \begin{tcolorbox}[colback=white]
  13802. \small
  13803. {\if\edition\racketEd
  13804. \[
  13805. \begin{array}{l}
  13806. \gray{\LintOpAST} \\ \hline
  13807. \gray{\LvarASTRacket{}} \\ \hline
  13808. \gray{\LifASTRacket{}} \\ \hline
  13809. \gray{\LwhileASTRacket{}} \\ \hline
  13810. \gray{\LtupASTRacket{}} \\ \hline
  13811. \LfunASTRacket \\
  13812. \begin{array}{lcl}
  13813. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13814. \end{array}
  13815. \end{array}
  13816. \]
  13817. \fi}
  13818. {\if\edition\pythonEd\pythonColor
  13819. \[
  13820. \begin{array}{l}
  13821. \gray{\LintASTPython{}} \\ \hline
  13822. \gray{\LvarASTPython{}} \\ \hline
  13823. \gray{\LifASTPython{}} \\ \hline
  13824. \gray{\LwhileASTPython} \\ \hline
  13825. \gray{\LtupASTPython} \\ \hline
  13826. \LfunASTPython \\
  13827. \begin{array}{rcl}
  13828. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13829. \end{array}
  13830. \end{array}
  13831. \]
  13832. \fi}
  13833. \end{tcolorbox}
  13834. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13835. \label{fig:Lfun-syntax}
  13836. \end{figure}
  13837. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13838. representative example of defining and using functions in \LangFun{}.
  13839. We define a function \code{map} that applies some other function
  13840. \code{f} to both elements of a tuple and returns a new tuple
  13841. containing the results. We also define a function \code{inc}. The
  13842. program applies \code{map} to \code{inc} and
  13843. %
  13844. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13845. %
  13846. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13847. %
  13848. from which we return \code{42}.
  13849. \begin{figure}[tbp]
  13850. \begin{tcolorbox}[colback=white]
  13851. {\if\edition\racketEd
  13852. \begin{lstlisting}
  13853. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13854. : (Vector Integer Integer)
  13855. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13856. (define (inc [x : Integer]) : Integer
  13857. (+ x 1))
  13858. (vector-ref (map inc (vector 0 41)) 1)
  13859. \end{lstlisting}
  13860. \fi}
  13861. {\if\edition\pythonEd\pythonColor
  13862. \begin{lstlisting}
  13863. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13864. return f(v[0]), f(v[1])
  13865. def inc(x : int) -> int:
  13866. return x + 1
  13867. print(map(inc, (0, 41))[1])
  13868. \end{lstlisting}
  13869. \fi}
  13870. \end{tcolorbox}
  13871. \caption{Example of using functions in \LangFun{}.}
  13872. \label{fig:Lfun-function-example}
  13873. \end{figure}
  13874. The definitional interpreter for \LangFun{} is shown in
  13875. figure~\ref{fig:interp-Lfun}. The case for the
  13876. %
  13877. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13878. %
  13879. AST is responsible for setting up the mutual recursion between the
  13880. top-level function definitions.
  13881. %
  13882. \racket{We use the classic back-patching
  13883. \index{subject}{back-patching} approach that uses mutable variables
  13884. and makes two passes over the function
  13885. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13886. top-level environment using a mutable cons cell for each function
  13887. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13888. for each function is incomplete; it does not yet include the environment.
  13889. Once the top-level environment has been constructed, we iterate over it and
  13890. update the \code{lambda} values to use the top-level environment.}
  13891. %
  13892. \python{We create a dictionary named \code{env} and fill it in
  13893. by mapping each function name to a new \code{Function} value,
  13894. each of which stores a reference to the \code{env}.
  13895. (We define the class \code{Function} for this purpose.)}
  13896. %
  13897. To interpret a function \racket{application}\python{call}, we match
  13898. the result of the function expression to obtain a function value. We
  13899. then extend the function's environment with the mapping of parameters to
  13900. argument values. Finally, we interpret the body of the function in
  13901. this extended environment.
  13902. \begin{figure}[tp]
  13903. \begin{tcolorbox}[colback=white]
  13904. {\if\edition\racketEd
  13905. \begin{lstlisting}
  13906. (define interp-Lfun-class
  13907. (class interp-Lvec-class
  13908. (super-new)
  13909. (define/override ((interp-exp env) e)
  13910. (define recur (interp-exp env))
  13911. (match e
  13912. [(Apply fun args)
  13913. (define fun-val (recur fun))
  13914. (define arg-vals (for/list ([e args]) (recur e)))
  13915. (match fun-val
  13916. [`(function (,xs ...) ,body ,fun-env)
  13917. (define params-args (for/list ([x xs] [arg arg-vals])
  13918. (cons x (box arg))))
  13919. (define new-env (append params-args fun-env))
  13920. ((interp-exp new-env) body)]
  13921. [else
  13922. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13923. [else ((super interp-exp env) e)]
  13924. ))
  13925. (define/public (interp-def d)
  13926. (match d
  13927. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13928. (cons f (box `(function ,xs ,body ())))]))
  13929. (define/override (interp-program p)
  13930. (match p
  13931. [(ProgramDefsExp info ds body)
  13932. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13933. (for/list ([f (in-dict-values top-level)])
  13934. (set-box! f (match (unbox f)
  13935. [`(function ,xs ,body ())
  13936. `(function ,xs ,body ,top-level)])))
  13937. ((interp-exp top-level) body))]))
  13938. ))
  13939. (define (interp-Lfun p)
  13940. (send (new interp-Lfun-class) interp-program p))
  13941. \end{lstlisting}
  13942. \fi}
  13943. {\if\edition\pythonEd\pythonColor
  13944. \begin{lstlisting}
  13945. class InterpLfun(InterpLtup):
  13946. def apply_fun(self, fun, args, e):
  13947. match fun:
  13948. case Function(name, xs, body, env):
  13949. new_env = env.copy().update(zip(xs, args))
  13950. return self.interp_stmts(body, new_env)
  13951. case _:
  13952. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13953. def interp_exp(self, e, env):
  13954. match e:
  13955. case Call(Name('input_int'), []):
  13956. return super().interp_exp(e, env)
  13957. case Call(func, args):
  13958. f = self.interp_exp(func, env)
  13959. vs = [self.interp_exp(arg, env) for arg in args]
  13960. return self.apply_fun(f, vs, e)
  13961. case _:
  13962. return super().interp_exp(e, env)
  13963. def interp_stmt(self, s, env, cont):
  13964. match s:
  13965. case Return(value):
  13966. return self.interp_exp(value, env)
  13967. case FunctionDef(name, params, bod, dl, returns, comment):
  13968. if isinstance(params, ast.arguments):
  13969. ps = [p.arg for p in params.args]
  13970. else:
  13971. ps = [x for (x,t) in params]
  13972. env[name] = Function(name, ps, bod, env)
  13973. return self.interp_stmts(cont, env)
  13974. case _:
  13975. return super().interp_stmt(s, env, cont)
  13976. def interp(self, p):
  13977. match p:
  13978. case Module(ss):
  13979. env = {}
  13980. self.interp_stmts(ss, env)
  13981. if 'main' in env.keys():
  13982. self.apply_fun(env['main'], [], None)
  13983. case _:
  13984. raise Exception('interp: unexpected ' + repr(p))
  13985. \end{lstlisting}
  13986. \fi}
  13987. \end{tcolorbox}
  13988. \caption{Interpreter for the \LangFun{} language.}
  13989. \label{fig:interp-Lfun}
  13990. \end{figure}
  13991. %\margincomment{TODO: explain type checker}
  13992. The type checker for \LangFun{} is shown in
  13993. figure~\ref{fig:type-check-Lfun}.
  13994. %
  13995. \python{(We omit the code that parses function parameters into the
  13996. simpler abstract syntax.)}
  13997. %
  13998. Similarly to the interpreter, the case for the
  13999. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14000. %
  14001. AST is responsible for setting up the mutual recursion between the
  14002. top-level function definitions. We begin by create a mapping
  14003. \code{env} from every function name to its type. We then type check
  14004. the program using this mapping.
  14005. %
  14006. In the case for function \racket{application}\python{call}, we match
  14007. the type of the function expression to a function type and check that
  14008. the types of the argument expressions are equal to the function's
  14009. parameter types. The type of the \racket{application}\python{call} as
  14010. a whole is the return type from the function type.
  14011. \begin{figure}[tp]
  14012. \begin{tcolorbox}[colback=white]
  14013. {\if\edition\racketEd
  14014. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14015. (define type-check-Lfun-class
  14016. (class type-check-Lvec-class
  14017. (super-new)
  14018. (inherit check-type-equal?)
  14019. (define/public (type-check-apply env e es)
  14020. (define-values (e^ ty) ((type-check-exp env) e))
  14021. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14022. ((type-check-exp env) e)))
  14023. (match ty
  14024. [`(,ty^* ... -> ,rt)
  14025. (for ([arg-ty ty*] [param-ty ty^*])
  14026. (check-type-equal? arg-ty param-ty (Apply e es)))
  14027. (values e^ e* rt)]))
  14028. (define/override (type-check-exp env)
  14029. (lambda (e)
  14030. (match e
  14031. [(FunRef f n)
  14032. (values (FunRef f n) (dict-ref env f))]
  14033. [(Apply e es)
  14034. (define-values (e^ es^ rt) (type-check-apply env e es))
  14035. (values (Apply e^ es^) rt)]
  14036. [(Call e es)
  14037. (define-values (e^ es^ rt) (type-check-apply env e es))
  14038. (values (Call e^ es^) rt)]
  14039. [else ((super type-check-exp env) e)])))
  14040. (define/public (type-check-def env)
  14041. (lambda (e)
  14042. (match e
  14043. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14044. (define new-env (append (map cons xs ps) env))
  14045. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14046. (check-type-equal? ty^ rt body)
  14047. (Def f p:t* rt info body^)])))
  14048. (define/public (fun-def-type d)
  14049. (match d
  14050. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14051. (define/override (type-check-program e)
  14052. (match e
  14053. [(ProgramDefsExp info ds body)
  14054. (define env (for/list ([d ds])
  14055. (cons (Def-name d) (fun-def-type d))))
  14056. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14057. (define-values (body^ ty) ((type-check-exp env) body))
  14058. (check-type-equal? ty 'Integer body)
  14059. (ProgramDefsExp info ds^ body^)]))))
  14060. (define (type-check-Lfun p)
  14061. (send (new type-check-Lfun-class) type-check-program p))
  14062. \end{lstlisting}
  14063. \fi}
  14064. {\if\edition\pythonEd\pythonColor
  14065. \begin{lstlisting}
  14066. class TypeCheckLfun(TypeCheckLtup):
  14067. def type_check_exp(self, e, env):
  14068. match e:
  14069. case Call(Name('input_int'), []):
  14070. return super().type_check_exp(e, env)
  14071. case Call(func, args):
  14072. func_t = self.type_check_exp(func, env)
  14073. args_t = [self.type_check_exp(arg, env) for arg in args]
  14074. match func_t:
  14075. case FunctionType(params_t, return_t):
  14076. for (arg_t, param_t) in zip(args_t, params_t):
  14077. check_type_equal(param_t, arg_t, e)
  14078. return return_t
  14079. case _:
  14080. raise Exception('type_check_exp: in call, unexpected ' +
  14081. repr(func_t))
  14082. case _:
  14083. return super().type_check_exp(e, env)
  14084. def type_check_stmts(self, ss, env):
  14085. if len(ss) == 0:
  14086. return
  14087. match ss[0]:
  14088. case FunctionDef(name, params, body, dl, returns, comment):
  14089. new_env = env.copy().update(params)
  14090. rt = self.type_check_stmts(body, new_env)
  14091. check_type_equal(returns, rt, ss[0])
  14092. return self.type_check_stmts(ss[1:], env)
  14093. case Return(value):
  14094. return self.type_check_exp(value, env)
  14095. case _:
  14096. return super().type_check_stmts(ss, env)
  14097. def type_check(self, p):
  14098. match p:
  14099. case Module(body):
  14100. env = {}
  14101. for s in body:
  14102. match s:
  14103. case FunctionDef(name, params, bod, dl, returns, comment):
  14104. if name in env:
  14105. raise Exception('type_check: function ' +
  14106. repr(name) + ' defined twice')
  14107. params_t = [t for (x,t) in params]
  14108. env[name] = FunctionType(params_t, returns)
  14109. self.type_check_stmts(body, env)
  14110. case _:
  14111. raise Exception('type_check: unexpected ' + repr(p))
  14112. \end{lstlisting}
  14113. \fi}
  14114. \end{tcolorbox}
  14115. \caption{Type checker for the \LangFun{} language.}
  14116. \label{fig:type-check-Lfun}
  14117. \end{figure}
  14118. \clearpage
  14119. \section{Functions in x86}
  14120. \label{sec:fun-x86}
  14121. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14122. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14123. %% \margincomment{\tiny Talk about the return address on the
  14124. %% stack and what callq and retq does.\\ --Jeremy }
  14125. The x86 architecture provides a few features to support the
  14126. implementation of functions. We have already seen that there are
  14127. labels in x86 so that one can refer to the location of an instruction,
  14128. as is needed for jump instructions. Labels can also be used to mark
  14129. the beginning of the instructions for a function. Going further, we
  14130. can obtain the address of a label by using the \key{leaq}
  14131. instruction. For example, the following puts the address of the
  14132. \code{inc} label into the \code{rbx} register:
  14133. \begin{lstlisting}
  14134. leaq inc(%rip), %rbx
  14135. \end{lstlisting}
  14136. Recall from section~\ref{sec:select-instructions-gc} that
  14137. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14138. addressing.
  14139. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14140. to functions whose locations were given by a label, such as
  14141. \code{read\_int}. To support function calls in this chapter we instead
  14142. jump to functions whose location are given by an address in
  14143. a register; that is, we use \emph{indirect function calls}. The
  14144. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14145. before the register name.\index{subject}{indirect function call}
  14146. \begin{lstlisting}
  14147. callq *%rbx
  14148. \end{lstlisting}
  14149. \subsection{Calling Conventions}
  14150. \label{sec:calling-conventions-fun}
  14151. \index{subject}{calling conventions}
  14152. The \code{callq} instruction provides partial support for implementing
  14153. functions: it pushes the return address on the stack and it jumps to
  14154. the target. However, \code{callq} does not handle
  14155. \begin{enumerate}
  14156. \item parameter passing,
  14157. \item pushing frames on the procedure call stack and popping them off,
  14158. or
  14159. \item determining how registers are shared by different functions.
  14160. \end{enumerate}
  14161. Regarding parameter passing, recall that the x86-64 calling
  14162. convention for Unix-based systems uses the following six registers to
  14163. pass arguments to a function, in the given order:
  14164. \begin{lstlisting}
  14165. rdi rsi rdx rcx r8 r9
  14166. \end{lstlisting}
  14167. If there are more than six arguments, then the calling convention
  14168. mandates using space on the frame of the caller for the rest of the
  14169. arguments. However, to ease the implementation of efficient tail calls
  14170. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14171. arguments.
  14172. %
  14173. The return value of the function is stored in register \code{rax}.
  14174. Regarding frames \index{subject}{frame} and the procedure call stack,
  14175. \index{subject}{procedure call stack} recall from
  14176. section~\ref{sec:x86} that the stack grows down and each function call
  14177. uses a chunk of space on the stack called a frame. The caller sets the
  14178. stack pointer, register \code{rsp}, to the last data item in its
  14179. frame. The callee must not change anything in the caller's frame, that
  14180. is, anything that is at or above the stack pointer. The callee is free
  14181. to use locations that are below the stack pointer.
  14182. Recall that we store variables of tuple type on the root stack. So,
  14183. the prelude\index{subject}{prelude} of a function needs to move the
  14184. root stack pointer \code{r15} up according to the number of variables
  14185. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14186. move the root stack pointer back down. Also, the prelude must
  14187. initialize to \code{0} this frame's slots in the root stack to signal
  14188. to the garbage collector that those slots do not yet contain a valid
  14189. pointer. Otherwise the garbage collector will interpret the garbage
  14190. bits in those slots as memory addresses and try to traverse them,
  14191. causing serious mayhem!
  14192. Regarding the sharing of registers between different functions, recall
  14193. from section~\ref{sec:calling-conventions} that the registers are
  14194. divided into two groups, the caller-saved registers and the
  14195. callee-saved registers. The caller should assume that all the
  14196. caller-saved registers are overwritten with arbitrary values by the
  14197. callee. For that reason we recommend in
  14198. section~\ref{sec:calling-conventions} that variables that are live
  14199. during a function call should not be assigned to caller-saved
  14200. registers.
  14201. On the flip side, if the callee wants to use a callee-saved register,
  14202. the callee must save the contents of those registers on their stack
  14203. frame and then put them back prior to returning to the caller. For
  14204. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14205. the register allocator assigns a variable to a callee-saved register,
  14206. then the prelude of the \code{main} function must save that register
  14207. to the stack and the conclusion of \code{main} must restore it. This
  14208. recommendation now generalizes to all functions.
  14209. Recall that the base pointer, register \code{rbp}, is used as a
  14210. point of reference within a frame, so that each local variable can be
  14211. accessed at a fixed offset from the base pointer
  14212. (section~\ref{sec:x86}).
  14213. %
  14214. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14215. frames.
  14216. \begin{figure}[tbp]
  14217. \centering
  14218. \begin{tcolorbox}[colback=white]
  14219. \begin{tabular}{r|r|l|l} \hline
  14220. Caller View & Callee View & Contents & Frame \\ \hline
  14221. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14222. 0(\key{\%rbp}) & & old \key{rbp} \\
  14223. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14224. \ldots & & \ldots \\
  14225. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14226. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14227. \ldots & & \ldots \\
  14228. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14229. %% & & \\
  14230. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14231. %% & \ldots & \ldots \\
  14232. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14233. \hline
  14234. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14235. & 0(\key{\%rbp}) & old \key{rbp} \\
  14236. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14237. & \ldots & \ldots \\
  14238. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14239. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14240. & \ldots & \ldots \\
  14241. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14242. \end{tabular}
  14243. \end{tcolorbox}
  14244. \caption{Memory layout of caller and callee frames.}
  14245. \label{fig:call-frames}
  14246. \end{figure}
  14247. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14248. %% local variables and for storing the values of callee-saved registers
  14249. %% (we shall refer to all of these collectively as ``locals''), and that
  14250. %% at the beginning of a function we move the stack pointer \code{rsp}
  14251. %% down to make room for them.
  14252. %% We recommend storing the local variables
  14253. %% first and then the callee-saved registers, so that the local variables
  14254. %% can be accessed using \code{rbp} the same as before the addition of
  14255. %% functions.
  14256. %% To make additional room for passing arguments, we shall
  14257. %% move the stack pointer even further down. We count how many stack
  14258. %% arguments are needed for each function call that occurs inside the
  14259. %% body of the function and find their maximum. Adding this number to the
  14260. %% number of locals gives us how much the \code{rsp} should be moved at
  14261. %% the beginning of the function. In preparation for a function call, we
  14262. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14263. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14264. %% so on.
  14265. %% Upon calling the function, the stack arguments are retrieved by the
  14266. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14267. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14268. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14269. %% the layout of the caller and callee frames. Notice how important it is
  14270. %% that we correctly compute the maximum number of arguments needed for
  14271. %% function calls; if that number is too small then the arguments and
  14272. %% local variables will smash into each other!
  14273. \subsection{Efficient Tail Calls}
  14274. \label{sec:tail-call}
  14275. In general, the amount of stack space used by a program is determined
  14276. by the longest chain of nested function calls. That is, if function
  14277. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14278. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14279. large if functions are recursive. However, in some cases we can
  14280. arrange to use only a constant amount of space for a long chain of
  14281. nested function calls.
  14282. A \emph{tail call}\index{subject}{tail call} is a function call that
  14283. happens as the last action in a function body. For example, in the
  14284. following program, the recursive call to \code{tail\_sum} is a tail
  14285. call:
  14286. \begin{center}
  14287. {\if\edition\racketEd
  14288. \begin{lstlisting}
  14289. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14290. (if (eq? n 0)
  14291. r
  14292. (tail_sum (- n 1) (+ n r))))
  14293. (+ (tail_sum 3 0) 36)
  14294. \end{lstlisting}
  14295. \fi}
  14296. {\if\edition\pythonEd\pythonColor
  14297. \begin{lstlisting}
  14298. def tail_sum(n : int, r : int) -> int:
  14299. if n == 0:
  14300. return r
  14301. else:
  14302. return tail_sum(n - 1, n + r)
  14303. print(tail_sum(3, 0) + 36)
  14304. \end{lstlisting}
  14305. \fi}
  14306. \end{center}
  14307. At a tail call, the frame of the caller is no longer needed, so we can
  14308. pop the caller's frame before making the tail call. With this
  14309. approach, a recursive function that makes only tail calls ends up
  14310. using a constant amount of stack space. Functional languages like
  14311. Racket rely heavily on recursive functions, so the definition of
  14312. Racket \emph{requires} that all tail calls be optimized in this way.
  14313. \index{subject}{frame}
  14314. Some care is needed with regard to argument passing in tail calls. As
  14315. mentioned, for arguments beyond the sixth, the convention is to use
  14316. space in the caller's frame for passing arguments. However, for a
  14317. tail call we pop the caller's frame and can no longer use it. An
  14318. alternative is to use space in the callee's frame for passing
  14319. arguments. However, this option is also problematic because the caller
  14320. and callee's frames overlap in memory. As we begin to copy the
  14321. arguments from their sources in the caller's frame, the target
  14322. locations in the callee's frame might collide with the sources for
  14323. later arguments! We solve this problem by using the heap instead of
  14324. the stack for passing more than six arguments
  14325. (section~\ref{sec:limit-functions-r4}).
  14326. As mentioned, for a tail call we pop the caller's frame prior to
  14327. making the tail call. The instructions for popping a frame are the
  14328. instructions that we usually place in the conclusion of a
  14329. function. Thus, we also need to place such code immediately before
  14330. each tail call. These instructions include restoring the callee-saved
  14331. registers, so it is fortunate that the argument passing registers are
  14332. all caller-saved registers.
  14333. One note remains regarding which instruction to use to make the tail
  14334. call. When the callee is finished, it should not return to the current
  14335. function but instead return to the function that called the current
  14336. one. Thus, the return address that is already on the stack is the
  14337. right one, and we should not use \key{callq} to make the tail call
  14338. because that would overwrite the return address. Instead we simply use
  14339. the \key{jmp} instruction. As with the indirect function call, we write
  14340. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14341. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14342. jump target because the conclusion can overwrite just about everything
  14343. else.
  14344. \begin{lstlisting}
  14345. jmp *%rax
  14346. \end{lstlisting}
  14347. \section{Shrink \LangFun{}}
  14348. \label{sec:shrink-r4}
  14349. The \code{shrink} pass performs a minor modification to ease the
  14350. later passes. This pass introduces an explicit \code{main} function
  14351. that gobbles up all the top-level statements of the module.
  14352. %
  14353. \racket{It also changes the top \code{ProgramDefsExp} form to
  14354. \code{ProgramDefs}.}
  14355. {\if\edition\racketEd
  14356. \begin{lstlisting}
  14357. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14358. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14359. \end{lstlisting}
  14360. where $\itm{mainDef}$ is
  14361. \begin{lstlisting}
  14362. (Def 'main '() 'Integer '() |$\Exp'$|)
  14363. \end{lstlisting}
  14364. \fi}
  14365. {\if\edition\pythonEd\pythonColor
  14366. \begin{lstlisting}
  14367. Module(|$\Def\ldots\Stmt\ldots$|)
  14368. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14369. \end{lstlisting}
  14370. where $\itm{mainDef}$ is
  14371. \begin{lstlisting}
  14372. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14373. \end{lstlisting}
  14374. \fi}
  14375. \section{Reveal Functions and the \LangFunRef{} Language}
  14376. \label{sec:reveal-functions-r4}
  14377. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14378. in that it conflates the use of function names and local
  14379. variables. This is a problem because we need to compile the use of a
  14380. function name differently from the use of a local variable. In
  14381. particular, we use \code{leaq} to convert the function name (a label
  14382. in x86) to an address in a register. Thus, we create a new pass that
  14383. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14384. $n$ is the arity of the function.\python{\footnote{The arity is not
  14385. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14386. This pass is named \code{reveal\_functions} and the output language
  14387. is \LangFunRef{}.
  14388. %is defined in figure~\ref{fig:f1-syntax}.
  14389. %% The concrete syntax for a
  14390. %% function reference is $\CFUNREF{f}$.
  14391. %% \begin{figure}[tp]
  14392. %% \centering
  14393. %% \fbox{
  14394. %% \begin{minipage}{0.96\textwidth}
  14395. %% {\if\edition\racketEd
  14396. %% \[
  14397. %% \begin{array}{lcl}
  14398. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14399. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14400. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14401. %% \end{array}
  14402. %% \]
  14403. %% \fi}
  14404. %% {\if\edition\pythonEd\pythonColor
  14405. %% \[
  14406. %% \begin{array}{lcl}
  14407. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14408. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14409. %% \end{array}
  14410. %% \]
  14411. %% \fi}
  14412. %% \end{minipage}
  14413. %% }
  14414. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14415. %% (figure~\ref{fig:Lfun-syntax}).}
  14416. %% \label{fig:f1-syntax}
  14417. %% \end{figure}
  14418. %% Distinguishing between calls in tail position and non-tail position
  14419. %% requires the pass to have some notion of context. We recommend using
  14420. %% two mutually recursive functions, one for processing expressions in
  14421. %% tail position and another for the rest.
  14422. \racket{Placing this pass after \code{uniquify} will make sure that
  14423. there are no local variables and functions that share the same
  14424. name.}
  14425. %
  14426. The \code{reveal\_functions} pass should come before the
  14427. \code{remove\_complex\_operands} pass because function references
  14428. should be categorized as complex expressions.
  14429. \section{Limit Functions}
  14430. \label{sec:limit-functions-r4}
  14431. Recall that we wish to limit the number of function parameters to six
  14432. so that we do not need to use the stack for argument passing, which
  14433. makes it easier to implement efficient tail calls. However, because
  14434. the input language \LangFun{} supports arbitrary numbers of function
  14435. arguments, we have some work to do! The \code{limit\_functions} pass
  14436. transforms functions and function calls that involve more than six
  14437. arguments to pass the first five arguments as usual, but it packs the
  14438. rest of the arguments into a tuple and passes it as the sixth
  14439. argument.\footnote{The implementation this pass can be postponed to
  14440. last because you can test the rest of the passes on functions with
  14441. six or fewer parameters.}
  14442. Each function definition with seven or more parameters is transformed as
  14443. follows:
  14444. {\if\edition\racketEd
  14445. \begin{lstlisting}
  14446. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14447. |$\Rightarrow$|
  14448. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14449. \end{lstlisting}
  14450. \fi}
  14451. {\if\edition\pythonEd\pythonColor
  14452. \begin{lstlisting}
  14453. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14454. |$\Rightarrow$|
  14455. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14456. |$T_r$|, None, |$\itm{body}'$|, None)
  14457. \end{lstlisting}
  14458. \fi}
  14459. %
  14460. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14461. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14462. the $k$th element of the tuple, where $k = i - 6$.
  14463. %
  14464. {\if\edition\racketEd
  14465. \begin{lstlisting}
  14466. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14467. \end{lstlisting}
  14468. \fi}
  14469. {\if\edition\pythonEd\pythonColor
  14470. \begin{lstlisting}
  14471. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14472. \end{lstlisting}
  14473. \fi}
  14474. For function calls with too many arguments, the \code{limit\_functions}
  14475. pass transforms them in the following way:
  14476. \begin{tabular}{lll}
  14477. \begin{minipage}{0.3\textwidth}
  14478. {\if\edition\racketEd
  14479. \begin{lstlisting}
  14480. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14481. \end{lstlisting}
  14482. \fi}
  14483. {\if\edition\pythonEd\pythonColor
  14484. \begin{lstlisting}
  14485. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14486. \end{lstlisting}
  14487. \fi}
  14488. \end{minipage}
  14489. &
  14490. $\Rightarrow$
  14491. &
  14492. \begin{minipage}{0.5\textwidth}
  14493. {\if\edition\racketEd
  14494. \begin{lstlisting}
  14495. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14496. \end{lstlisting}
  14497. \fi}
  14498. {\if\edition\pythonEd\pythonColor
  14499. \begin{lstlisting}
  14500. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14501. \end{lstlisting}
  14502. \fi}
  14503. \end{minipage}
  14504. \end{tabular}
  14505. \section{Remove Complex Operands}
  14506. \label{sec:rco-r4}
  14507. The primary decisions to make for this pass are whether to classify
  14508. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14509. atomic or complex expressions. Recall that an atomic expression
  14510. ends up as an immediate argument of an x86 instruction. Function
  14511. application translates to a sequence of instructions, so
  14512. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14513. a complex expression. On the other hand, the arguments of
  14514. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14515. expressions.
  14516. %
  14517. Regarding \code{FunRef}, as discussed previously, the function label
  14518. needs to be converted to an address using the \code{leaq}
  14519. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14520. needs to be classified as a complex expression so that we generate an
  14521. assignment statement with a left-hand side that can serve as the
  14522. target of the \code{leaq}.
  14523. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14524. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14525. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14526. and augments programs to include a list of function definitions.
  14527. %
  14528. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14529. \newcommand{\LfunMonadASTRacket}{
  14530. \begin{array}{lcl}
  14531. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14532. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14533. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14534. \end{array}
  14535. }
  14536. \newcommand{\LfunMonadASTPython}{
  14537. \begin{array}{lcl}
  14538. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14539. \MID \key{TupleType}\LS\Type^+\RS\\
  14540. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14541. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14542. \Stmt &::=& \RETURN{\Exp} \\
  14543. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14544. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14545. \end{array}
  14546. }
  14547. \begin{figure}[tp]
  14548. \centering
  14549. \begin{tcolorbox}[colback=white]
  14550. \small
  14551. {\if\edition\racketEd
  14552. \[
  14553. \begin{array}{l}
  14554. \gray{\LvarMonadASTRacket} \\ \hline
  14555. \gray{\LifMonadASTRacket} \\ \hline
  14556. \gray{\LwhileMonadASTRacket} \\ \hline
  14557. \gray{\LtupMonadASTRacket} \\ \hline
  14558. \LfunMonadASTRacket \\
  14559. \begin{array}{rcl}
  14560. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14561. \end{array}
  14562. \end{array}
  14563. \]
  14564. \fi}
  14565. {\if\edition\pythonEd\pythonColor
  14566. \[
  14567. \begin{array}{l}
  14568. \gray{\LvarMonadASTPython} \\ \hline
  14569. \gray{\LifMonadASTPython} \\ \hline
  14570. \gray{\LwhileMonadASTPython} \\ \hline
  14571. \gray{\LtupMonadASTPython} \\ \hline
  14572. \LfunMonadASTPython \\
  14573. \begin{array}{rcl}
  14574. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14575. \end{array}
  14576. \end{array}
  14577. \]
  14578. \fi}
  14579. \end{tcolorbox}
  14580. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14581. \label{fig:Lfun-anf-syntax}
  14582. \end{figure}
  14583. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14584. %% \LangFunANF{} of this pass.
  14585. %% \begin{figure}[tp]
  14586. %% \centering
  14587. %% \fbox{
  14588. %% \begin{minipage}{0.96\textwidth}
  14589. %% \small
  14590. %% \[
  14591. %% \begin{array}{rcl}
  14592. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14593. %% \MID \VOID{} } \\
  14594. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14595. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14596. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14597. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14598. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14599. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14600. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14601. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14602. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14603. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14604. %% \end{array}
  14605. %% \]
  14606. %% \end{minipage}
  14607. %% }
  14608. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14609. %% \label{fig:Lfun-anf-syntax}
  14610. %% \end{figure}
  14611. \section{Explicate Control and the \LangCFun{} Language}
  14612. \label{sec:explicate-control-r4}
  14613. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14614. output of \code{explicate\_control}.
  14615. %
  14616. %% \racket{(The concrete syntax is given in
  14617. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14618. %
  14619. The auxiliary functions for assignment\racket{ and tail contexts} should
  14620. be updated with cases for
  14621. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14622. function for predicate context should be updated for
  14623. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14624. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14625. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14626. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14627. auxiliary function for processing function definitions. This code is
  14628. similar to the case for \code{Program} in \LangVec{}. The top-level
  14629. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14630. form of \LangFun{} can then apply this new function to all the
  14631. function definitions.
  14632. {\if\edition\pythonEd\pythonColor
  14633. The translation of \code{Return} statements requires a new auxiliary
  14634. function to handle expressions in tail context, called
  14635. \code{explicate\_tail}. The function should take an expression and the
  14636. dictionary of basic blocks and produce a list of statements in the
  14637. \LangCFun{} language. The \code{explicate\_tail} function should
  14638. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14639. and a default case for other kinds of expressions. The default case
  14640. should produce a \code{Return} statement. The case for \code{Call}
  14641. should change it into \code{TailCall}. The other cases should
  14642. recursively process their subexpressions and statements, choosing the
  14643. appropriate explicate functions for the various contexts.
  14644. \fi}
  14645. \newcommand{\CfunASTRacket}{
  14646. \begin{array}{lcl}
  14647. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14648. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14649. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14650. \end{array}
  14651. }
  14652. \newcommand{\CfunASTPython}{
  14653. \begin{array}{lcl}
  14654. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14655. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14656. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14657. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14658. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14659. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14660. \end{array}
  14661. }
  14662. \begin{figure}[tp]
  14663. \begin{tcolorbox}[colback=white]
  14664. \small
  14665. {\if\edition\racketEd
  14666. \[
  14667. \begin{array}{l}
  14668. \gray{\CvarASTRacket} \\ \hline
  14669. \gray{\CifASTRacket} \\ \hline
  14670. \gray{\CloopASTRacket} \\ \hline
  14671. \gray{\CtupASTRacket} \\ \hline
  14672. \CfunASTRacket \\
  14673. \begin{array}{lcl}
  14674. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14675. \end{array}
  14676. \end{array}
  14677. \]
  14678. \fi}
  14679. {\if\edition\pythonEd\pythonColor
  14680. \[
  14681. \begin{array}{l}
  14682. \gray{\CifASTPython} \\ \hline
  14683. \gray{\CtupASTPython} \\ \hline
  14684. \CfunASTPython \\
  14685. \begin{array}{lcl}
  14686. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14687. \end{array}
  14688. \end{array}
  14689. \]
  14690. \fi}
  14691. \end{tcolorbox}
  14692. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14693. \label{fig:c3-syntax}
  14694. \end{figure}
  14695. \clearpage
  14696. \section{Select Instructions and the \LangXIndCall{} Language}
  14697. \label{sec:select-r4}
  14698. \index{subject}{select instructions}
  14699. The output of select instructions is a program in the \LangXIndCall{}
  14700. language; the definition of its concrete syntax is shown in
  14701. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14702. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14703. directive on the labels of function definitions to make sure the
  14704. bottom three bits are zero, which we put to use in
  14705. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14706. this section. \index{subject}{x86}
  14707. \newcommand{\GrammarXIndCall}{
  14708. \begin{array}{lcl}
  14709. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14710. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14711. \Block &::= & \Instr^{+} \\
  14712. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14713. \end{array}
  14714. }
  14715. \newcommand{\ASTXIndCallRacket}{
  14716. \begin{array}{lcl}
  14717. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14718. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14719. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14720. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14721. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14722. \end{array}
  14723. }
  14724. \begin{figure}[tp]
  14725. \begin{tcolorbox}[colback=white]
  14726. \small
  14727. \[
  14728. \begin{array}{l}
  14729. \gray{\GrammarXInt} \\ \hline
  14730. \gray{\GrammarXIf} \\ \hline
  14731. \gray{\GrammarXGlobal} \\ \hline
  14732. \GrammarXIndCall \\
  14733. \begin{array}{lcl}
  14734. \LangXIndCallM{} &::= & \Def^{*}
  14735. \end{array}
  14736. \end{array}
  14737. \]
  14738. \end{tcolorbox}
  14739. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14740. \label{fig:x86-3-concrete}
  14741. \end{figure}
  14742. \begin{figure}[tp]
  14743. \begin{tcolorbox}[colback=white]
  14744. \small
  14745. {\if\edition\racketEd
  14746. \[\arraycolsep=3pt
  14747. \begin{array}{l}
  14748. \gray{\ASTXIntRacket} \\ \hline
  14749. \gray{\ASTXIfRacket} \\ \hline
  14750. \gray{\ASTXGlobalRacket} \\ \hline
  14751. \ASTXIndCallRacket \\
  14752. \begin{array}{lcl}
  14753. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14754. \end{array}
  14755. \end{array}
  14756. \]
  14757. \fi}
  14758. {\if\edition\pythonEd\pythonColor
  14759. \[
  14760. \begin{array}{lcl}
  14761. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14762. \MID \BYTEREG{\Reg} } \\
  14763. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14764. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14765. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14766. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14767. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14768. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14769. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14770. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14771. \end{array}
  14772. \]
  14773. \fi}
  14774. \end{tcolorbox}
  14775. \caption{The abstract syntax of \LangXIndCall{} (extends
  14776. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14777. \label{fig:x86-3}
  14778. \end{figure}
  14779. An assignment of a function reference to a variable becomes a
  14780. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14781. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14782. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14783. node, whose concrete syntax is instruction-pointer-relative
  14784. addressing.
  14785. \begin{center}
  14786. \begin{tabular}{lcl}
  14787. \begin{minipage}{0.35\textwidth}
  14788. {\if\edition\racketEd
  14789. \begin{lstlisting}
  14790. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14791. \end{lstlisting}
  14792. \fi}
  14793. {\if\edition\pythonEd\pythonColor
  14794. \begin{lstlisting}
  14795. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14796. \end{lstlisting}
  14797. \fi}
  14798. \end{minipage}
  14799. &
  14800. $\Rightarrow$\qquad\qquad
  14801. &
  14802. \begin{minipage}{0.3\textwidth}
  14803. \begin{lstlisting}
  14804. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14805. \end{lstlisting}
  14806. \end{minipage}
  14807. \end{tabular}
  14808. \end{center}
  14809. Regarding function definitions, we need to remove the parameters and
  14810. instead perform parameter passing using the conventions discussed in
  14811. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14812. registers. We recommend turning the parameters into local variables
  14813. and generating instructions at the beginning of the function to move
  14814. from the argument-passing registers
  14815. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14816. {\if\edition\racketEd
  14817. \begin{lstlisting}
  14818. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14819. |$\Rightarrow$|
  14820. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14821. \end{lstlisting}
  14822. \fi}
  14823. {\if\edition\pythonEd\pythonColor
  14824. \begin{lstlisting}
  14825. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14826. |$\Rightarrow$|
  14827. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14828. \end{lstlisting}
  14829. \fi}
  14830. The basic blocks $B'$ are the same as $B$ except that the
  14831. \code{start} block is modified to add the instructions for moving from
  14832. the argument registers to the parameter variables. So the \code{start}
  14833. block of $B$ shown on the left of the following is changed to the code
  14834. on the right:
  14835. \begin{center}
  14836. \begin{minipage}{0.3\textwidth}
  14837. \begin{lstlisting}
  14838. start:
  14839. |$\itm{instr}_1$|
  14840. |$\cdots$|
  14841. |$\itm{instr}_n$|
  14842. \end{lstlisting}
  14843. \end{minipage}
  14844. $\Rightarrow$
  14845. \begin{minipage}{0.3\textwidth}
  14846. \begin{lstlisting}
  14847. |$f$|start:
  14848. movq %rdi, |$x_1$|
  14849. movq %rsi, |$x_2$|
  14850. |$\cdots$|
  14851. |$\itm{instr}_1$|
  14852. |$\cdots$|
  14853. |$\itm{instr}_n$|
  14854. \end{lstlisting}
  14855. \end{minipage}
  14856. \end{center}
  14857. Recall that we use the label \code{start} for the initial block of a
  14858. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14859. the conclusion of the program with \code{conclusion}, so that
  14860. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14861. by a jump to \code{conclusion}. With the addition of function
  14862. definitions, there is a start block and conclusion for each function,
  14863. but their labels need to be unique. We recommend prepending the
  14864. function's name to \code{start} and \code{conclusion}, respectively,
  14865. to obtain unique labels.
  14866. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14867. number of parameters the function expects, but the parameters are no
  14868. longer in the syntax of function definitions. Instead, add an entry
  14869. to $\itm{info}$ that maps \code{num-params} to the number of
  14870. parameters to construct $\itm{info}'$.}
  14871. By changing the parameters to local variables, we are giving the
  14872. register allocator control over which registers or stack locations to
  14873. use for them. If you implement the move-biasing challenge
  14874. (section~\ref{sec:move-biasing}), the register allocator will try to
  14875. assign the parameter variables to the corresponding argument register,
  14876. in which case the \code{patch\_instructions} pass will remove the
  14877. \code{movq} instruction. This happens in the example translation given
  14878. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14879. the \code{add} function.
  14880. %
  14881. Also, note that the register allocator will perform liveness analysis
  14882. on this sequence of move instructions and build the interference
  14883. graph. So, for example, $x_1$ will be marked as interfering with
  14884. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14885. which is good because otherwise the first \code{movq} would overwrite
  14886. the argument in \code{rsi} that is needed for $x_2$.
  14887. Next, consider the compilation of function calls. In the mirror image
  14888. of the handling of parameters in function definitions, the arguments
  14889. are moved to the argument-passing registers. Note that the function
  14890. is not given as a label, but its address is produced by the argument
  14891. $\itm{arg}_0$. So, we translate the call into an indirect function
  14892. call. The return value from the function is stored in \code{rax}, so
  14893. it needs to be moved into the \itm{lhs}.
  14894. \begin{lstlisting}
  14895. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14896. |$\Rightarrow$|
  14897. movq |$\itm{arg}_1$|, %rdi
  14898. movq |$\itm{arg}_2$|, %rsi
  14899. |$\vdots$|
  14900. callq *|$\itm{arg}_0$|
  14901. movq %rax, |$\itm{lhs}$|
  14902. \end{lstlisting}
  14903. The \code{IndirectCallq} AST node includes an integer for the arity of
  14904. the function, that is, the number of parameters. That information is
  14905. useful in the \code{uncover\_live} pass for determining which
  14906. argument-passing registers are potentially read during the call.
  14907. For tail calls, the parameter passing is the same as non-tail calls:
  14908. generate instructions to move the arguments into the argument-passing
  14909. registers. After that we need to pop the frame from the procedure
  14910. call stack. However, we do not yet know how big the frame is; that
  14911. gets determined during register allocation. So, instead of generating
  14912. those instructions here, we invent a new instruction that means ``pop
  14913. the frame and then do an indirect jump,'' which we name
  14914. \code{TailJmp}. The abstract syntax for this instruction includes an
  14915. argument that specifies where to jump and an integer that represents
  14916. the arity of the function being called.
  14917. \section{Register Allocation}
  14918. \label{sec:register-allocation-r4}
  14919. The addition of functions requires some changes to all three aspects
  14920. of register allocation, which we discuss in the following subsections.
  14921. \subsection{Liveness Analysis}
  14922. \label{sec:liveness-analysis-r4}
  14923. \index{subject}{liveness analysis}
  14924. %% The rest of the passes need only minor modifications to handle the new
  14925. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14926. %% \code{leaq}.
  14927. The \code{IndirectCallq} instruction should be treated like
  14928. \code{Callq} regarding its written locations $W$, in that they should
  14929. include all the caller-saved registers. Recall that the reason for
  14930. that is to force variables that are live across a function call to be assigned to callee-saved
  14931. registers or to be spilled to the stack.
  14932. Regarding the set of read locations $R$, the arity fields of
  14933. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14934. argument-passing registers should be considered as read by those
  14935. instructions. Also, the target field of \code{TailJmp} and
  14936. \code{IndirectCallq} should be included in the set of read locations
  14937. $R$.
  14938. \subsection{Build Interference Graph}
  14939. \label{sec:build-interference-r4}
  14940. With the addition of function definitions, we compute a separate interference
  14941. graph for each function (not just one for the whole program).
  14942. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14943. spill tuple-typed variables that are live during a call to
  14944. \code{collect}, the garbage collector. With the addition of functions
  14945. to our language, we need to revisit this issue. Functions that perform
  14946. allocation contain calls to the collector. Thus, we should not only
  14947. spill a tuple-typed variable when it is live during a call to
  14948. \code{collect}, but we should spill the variable if it is live during
  14949. a call to any user-defined function. Thus, in the
  14950. \code{build\_interference} pass, we recommend adding interference
  14951. edges between call-live tuple-typed variables and the callee-saved
  14952. registers (in addition to creating edges between
  14953. call-live variables and the caller-saved registers).
  14954. \subsection{Allocate Registers}
  14955. The primary change to the \code{allocate\_registers} pass is adding an
  14956. auxiliary function for handling definitions (the \Def{} nonterminal
  14957. shown in figure~\ref{fig:x86-3}) with one case for function
  14958. definitions. The logic is the same as described in
  14959. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14960. allocation is performed many times, once for each function definition,
  14961. instead of just once for the whole program.
  14962. \section{Patch Instructions}
  14963. In \code{patch\_instructions}, you should deal with the x86
  14964. idiosyncrasy that the destination argument of \code{leaq} must be a
  14965. register. Additionally, you should ensure that the argument of
  14966. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14967. trample many other registers before the tail call, as explained in the
  14968. next section.
  14969. \section{Prelude and Conclusion}
  14970. Now that register allocation is complete, we can translate the
  14971. \code{TailJmp} into a sequence of instructions. A naive translation of
  14972. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14973. before the jump we need to pop the current frame to achieve efficient
  14974. tail calls. This sequence of instructions is the same as the code for
  14975. the conclusion of a function, except that the \code{retq} is replaced with
  14976. \code{jmp *$\itm{arg}$}.
  14977. Regarding function definitions, we generate a prelude and conclusion
  14978. for each one. This code is similar to the prelude and conclusion
  14979. generated for the \code{main} function presented in
  14980. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14981. carry out the following steps:
  14982. % TODO: .align the functions!
  14983. \begin{enumerate}
  14984. %% \item Start with \code{.global} and \code{.align} directives followed
  14985. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14986. %% example.)
  14987. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14988. pointer.
  14989. \item Push to the stack all the callee-saved registers that were
  14990. used for register allocation.
  14991. \item Move the stack pointer \code{rsp} down to make room for the
  14992. regular spills (aligned to 16 bytes).
  14993. \item Move the root stack pointer \code{r15} up by the size of the
  14994. root-stack frame for this function, which depends on the number of
  14995. spilled tuple-typed variables. \label{root-stack-init}
  14996. \item Initialize to zero all new entries in the root-stack frame.
  14997. \item Jump to the start block.
  14998. \end{enumerate}
  14999. The prelude of the \code{main} function has an additional task: call
  15000. the \code{initialize} function to set up the garbage collector, and
  15001. then move the value of the global \code{rootstack\_begin} in
  15002. \code{r15}. This initialization should happen before step
  15003. \ref{root-stack-init}, which depends on \code{r15}.
  15004. The conclusion of every function should do the following:
  15005. \begin{enumerate}
  15006. \item Move the stack pointer back up past the regular spills.
  15007. \item Restore the callee-saved registers by popping them from the
  15008. stack.
  15009. \item Move the root stack pointer back down by the size of the
  15010. root-stack frame for this function.
  15011. \item Restore \code{rbp} by popping it from the stack.
  15012. \item Return to the caller with the \code{retq} instruction.
  15013. \end{enumerate}
  15014. The output of this pass is \LangXIndCallFlat{}, which differs from
  15015. \LangXIndCall{} in that there is no longer an AST node for function
  15016. definitions. Instead, a program is just an association list of basic
  15017. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15018. \[
  15019. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15020. \]
  15021. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15022. compiling \LangFun{} to x86.
  15023. \begin{exercise}\normalfont\normalsize
  15024. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15025. Create eight new programs that use functions including examples that
  15026. pass functions and return functions from other functions, recursive
  15027. functions, functions that create vectors, and functions that make tail
  15028. calls. Test your compiler on these new programs and all your
  15029. previously created test programs.
  15030. \end{exercise}
  15031. \begin{figure}[tbp]
  15032. \begin{tcolorbox}[colback=white]
  15033. {\if\edition\racketEd
  15034. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15035. \node (Lfun) at (0,2) {\large \LangFun{}};
  15036. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15037. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15038. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15039. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15040. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15041. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15042. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15043. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15044. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15045. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15046. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15047. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15048. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15049. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15050. \path[->,bend left=15] (Lfun) edge [above] node
  15051. {\ttfamily\footnotesize shrink} (Lfun-1);
  15052. \path[->,bend left=15] (Lfun-1) edge [above] node
  15053. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15054. \path[->,bend left=15] (Lfun-2) edge [above] node
  15055. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15056. \path[->,bend left=15] (F1-1) edge [left] node
  15057. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15058. \path[->,bend left=15] (F1-2) edge [below] node
  15059. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15060. \path[->,bend left=15] (F1-3) edge [below] node
  15061. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15062. \path[->,bend right=15] (F1-4) edge [above] node
  15063. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15064. \path[->,bend right=15] (F1-5) edge [right] node
  15065. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15066. \path[->,bend right=15] (C3-2) edge [right] node
  15067. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15068. \path[->,bend left=15] (x86-2) edge [right] node
  15069. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15070. \path[->,bend right=15] (x86-2-1) edge [below] node
  15071. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15072. \path[->,bend right=15] (x86-2-2) edge [right] node
  15073. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15074. \path[->,bend left=15] (x86-3) edge [above] node
  15075. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15076. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15077. \end{tikzpicture}
  15078. \fi}
  15079. {\if\edition\pythonEd\pythonColor
  15080. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15081. \node (Lfun) at (0,2) {\large \LangFun{}};
  15082. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15083. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15084. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15085. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15086. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15087. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15088. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15089. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15090. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15091. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15092. \path[->,bend left=15] (Lfun) edge [above] node
  15093. {\ttfamily\footnotesize shrink} (Lfun-2);
  15094. \path[->,bend left=15] (Lfun-2) edge [above] node
  15095. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15096. \path[->,bend left=15] (F1-1) edge [above] node
  15097. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15098. \path[->,bend left=15] (F1-2) edge [right] node
  15099. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15100. \path[->,bend right=15] (F1-4) edge [above] node
  15101. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15102. \path[->,bend right=15] (F1-5) edge [right] node
  15103. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15104. \path[->,bend left=15] (C3-2) edge [right] node
  15105. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15106. \path[->,bend right=15] (x86-2) edge [below] node
  15107. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15108. \path[->,bend left=15] (x86-3) edge [above] node
  15109. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15110. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15111. \end{tikzpicture}
  15112. \fi}
  15113. \end{tcolorbox}
  15114. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15115. \label{fig:Lfun-passes}
  15116. \end{figure}
  15117. \section{An Example Translation}
  15118. \label{sec:functions-example}
  15119. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15120. function in \LangFun{} to x86. The figure includes the results of
  15121. \code{explicate\_control} and \code{select\_instructions}.
  15122. \begin{figure}[hbtp]
  15123. \begin{tcolorbox}[colback=white]
  15124. \begin{tabular}{ll}
  15125. \begin{minipage}{0.4\textwidth}
  15126. % s3_2.rkt
  15127. {\if\edition\racketEd
  15128. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15129. (define (add [x : Integer]
  15130. [y : Integer])
  15131. : Integer
  15132. (+ x y))
  15133. (add 40 2)
  15134. \end{lstlisting}
  15135. \fi}
  15136. {\if\edition\pythonEd\pythonColor
  15137. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15138. def add(x:int, y:int) -> int:
  15139. return x + y
  15140. print(add(40, 2))
  15141. \end{lstlisting}
  15142. \fi}
  15143. $\Downarrow$
  15144. {\if\edition\racketEd
  15145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15146. (define (add86 [x87 : Integer]
  15147. [y88 : Integer])
  15148. : Integer
  15149. add86start:
  15150. return (+ x87 y88);
  15151. )
  15152. (define (main) : Integer ()
  15153. mainstart:
  15154. tmp89 = (fun-ref add86 2);
  15155. (tail-call tmp89 40 2)
  15156. )
  15157. \end{lstlisting}
  15158. \fi}
  15159. {\if\edition\pythonEd\pythonColor
  15160. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15161. def add(x:int, y:int) -> int:
  15162. addstart:
  15163. return x + y
  15164. def main() -> int:
  15165. mainstart:
  15166. fun.0 = add
  15167. tmp.1 = fun.0(40, 2)
  15168. print(tmp.1)
  15169. return 0
  15170. \end{lstlisting}
  15171. \fi}
  15172. \end{minipage}
  15173. &
  15174. $\Rightarrow$
  15175. \begin{minipage}{0.5\textwidth}
  15176. {\if\edition\racketEd
  15177. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15178. (define (add86) : Integer
  15179. add86start:
  15180. movq %rdi, x87
  15181. movq %rsi, y88
  15182. movq x87, %rax
  15183. addq y88, %rax
  15184. jmp inc1389conclusion
  15185. )
  15186. (define (main) : Integer
  15187. mainstart:
  15188. leaq (fun-ref add86 2), tmp89
  15189. movq $40, %rdi
  15190. movq $2, %rsi
  15191. tail-jmp tmp89
  15192. )
  15193. \end{lstlisting}
  15194. \fi}
  15195. {\if\edition\pythonEd\pythonColor
  15196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15197. def add() -> int:
  15198. addstart:
  15199. movq %rdi, x
  15200. movq %rsi, y
  15201. movq x, %rax
  15202. addq y, %rax
  15203. jmp addconclusion
  15204. def main() -> int:
  15205. mainstart:
  15206. leaq add, fun.0
  15207. movq $40, %rdi
  15208. movq $2, %rsi
  15209. callq *fun.0
  15210. movq %rax, tmp.1
  15211. movq tmp.1, %rdi
  15212. callq print_int
  15213. movq $0, %rax
  15214. jmp mainconclusion
  15215. \end{lstlisting}
  15216. \fi}
  15217. $\Downarrow$
  15218. \end{minipage}
  15219. \end{tabular}
  15220. \begin{tabular}{ll}
  15221. \begin{minipage}{0.3\textwidth}
  15222. {\if\edition\racketEd
  15223. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15224. .globl add86
  15225. .align 8
  15226. add86:
  15227. pushq %rbp
  15228. movq %rsp, %rbp
  15229. jmp add86start
  15230. add86start:
  15231. movq %rdi, %rax
  15232. addq %rsi, %rax
  15233. jmp add86conclusion
  15234. add86conclusion:
  15235. popq %rbp
  15236. retq
  15237. \end{lstlisting}
  15238. \fi}
  15239. {\if\edition\pythonEd\pythonColor
  15240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15241. .align 8
  15242. add:
  15243. pushq %rbp
  15244. movq %rsp, %rbp
  15245. subq $0, %rsp
  15246. jmp addstart
  15247. addstart:
  15248. movq %rdi, %rdx
  15249. movq %rsi, %rcx
  15250. movq %rdx, %rax
  15251. addq %rcx, %rax
  15252. jmp addconclusion
  15253. addconclusion:
  15254. subq $0, %r15
  15255. addq $0, %rsp
  15256. popq %rbp
  15257. retq
  15258. \end{lstlisting}
  15259. \fi}
  15260. \end{minipage}
  15261. &
  15262. \begin{minipage}{0.5\textwidth}
  15263. {\if\edition\racketEd
  15264. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15265. .globl main
  15266. .align 8
  15267. main:
  15268. pushq %rbp
  15269. movq %rsp, %rbp
  15270. movq $16384, %rdi
  15271. movq $16384, %rsi
  15272. callq initialize
  15273. movq rootstack_begin(%rip), %r15
  15274. jmp mainstart
  15275. mainstart:
  15276. leaq add86(%rip), %rcx
  15277. movq $40, %rdi
  15278. movq $2, %rsi
  15279. movq %rcx, %rax
  15280. popq %rbp
  15281. jmp *%rax
  15282. mainconclusion:
  15283. popq %rbp
  15284. retq
  15285. \end{lstlisting}
  15286. \fi}
  15287. {\if\edition\pythonEd\pythonColor
  15288. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15289. .globl main
  15290. .align 8
  15291. main:
  15292. pushq %rbp
  15293. movq %rsp, %rbp
  15294. subq $0, %rsp
  15295. movq $65536, %rdi
  15296. movq $65536, %rsi
  15297. callq initialize
  15298. movq rootstack_begin(%rip), %r15
  15299. jmp mainstart
  15300. mainstart:
  15301. leaq add(%rip), %rcx
  15302. movq $40, %rdi
  15303. movq $2, %rsi
  15304. callq *%rcx
  15305. movq %rax, %rcx
  15306. movq %rcx, %rdi
  15307. callq print_int
  15308. movq $0, %rax
  15309. jmp mainconclusion
  15310. mainconclusion:
  15311. subq $0, %r15
  15312. addq $0, %rsp
  15313. popq %rbp
  15314. retq
  15315. \end{lstlisting}
  15316. \fi}
  15317. \end{minipage}
  15318. \end{tabular}
  15319. \end{tcolorbox}
  15320. \caption{Example compilation of a simple function to x86.}
  15321. \label{fig:add-fun}
  15322. \end{figure}
  15323. % Challenge idea: inlining! (simple version)
  15324. % Further Reading
  15325. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15326. \chapter{Lexically Scoped Functions}
  15327. \label{ch:Llambda}
  15328. \setcounter{footnote}{0}
  15329. This chapter studies lexically scoped functions. Lexical
  15330. scoping\index{subject}{lexical scoping} means that a function's body
  15331. may refer to variables whose binding site is outside of the function,
  15332. in an enclosing scope.
  15333. %
  15334. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15335. in \LangLam{}, which extends \LangFun{} with the
  15336. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15337. functions. The body of the \key{lambda} refers to three variables:
  15338. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15339. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15340. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15341. function \code{f}}, and \code{x} is a parameter of function
  15342. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15343. result value. The main expression of the program includes two calls to
  15344. \code{f} with different arguments for \code{x}: first \code{5} and
  15345. then \code{3}. The functions returned from \code{f} are bound to
  15346. variables \code{g} and \code{h}. Even though these two functions were
  15347. created by the same \code{lambda}, they are really different functions
  15348. because they use different values for \code{x}. Applying \code{g} to
  15349. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15350. produces \code{22}, so the result of the program is \code{42}.
  15351. \begin{figure}[btp]
  15352. \begin{tcolorbox}[colback=white]
  15353. {\if\edition\racketEd
  15354. % lambda_test_21.rkt
  15355. \begin{lstlisting}
  15356. (define (f [x : Integer]) : (Integer -> Integer)
  15357. (let ([y 4])
  15358. (lambda: ([z : Integer]) : Integer
  15359. (+ x (+ y z)))))
  15360. (let ([g (f 5)])
  15361. (let ([h (f 3)])
  15362. (+ (g 11) (h 15))))
  15363. \end{lstlisting}
  15364. \fi}
  15365. {\if\edition\pythonEd\pythonColor
  15366. \begin{lstlisting}
  15367. def f(x : int) -> Callable[[int], int]:
  15368. y = 4
  15369. return lambda z: x + y + z
  15370. g = f(5)
  15371. h = f(3)
  15372. print(g(11) + h(15))
  15373. \end{lstlisting}
  15374. \fi}
  15375. \end{tcolorbox}
  15376. \caption{Example of a lexically scoped function.}
  15377. \label{fig:lexical-scoping}
  15378. \end{figure}
  15379. The approach that we take for implementing lexically scoped functions
  15380. is to compile them into top-level function definitions, translating
  15381. from \LangLam{} into \LangFun{}. However, the compiler must give
  15382. special treatment to variable occurrences such as \code{x} and
  15383. \code{y} in the body of the \code{lambda} shown in
  15384. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15385. may not refer to variables defined outside of it. To identify such
  15386. variable occurrences, we review the standard notion of free variable.
  15387. \begin{definition}\normalfont
  15388. A variable is \emph{free in expression} $e$ if the variable occurs
  15389. inside $e$ but does not have an enclosing definition that is also in
  15390. $e$.\index{subject}{free variable}
  15391. \end{definition}
  15392. For example, in the expression
  15393. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15394. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15395. only \code{x} and \code{y} are free in the following expression,
  15396. because \code{z} is defined by the \code{lambda}
  15397. {\if\edition\racketEd
  15398. \begin{lstlisting}
  15399. (lambda: ([z : Integer]) : Integer
  15400. (+ x (+ y z)))
  15401. \end{lstlisting}
  15402. \fi}
  15403. {\if\edition\pythonEd\pythonColor
  15404. \begin{lstlisting}
  15405. lambda z: x + y + z
  15406. \end{lstlisting}
  15407. \fi}
  15408. %
  15409. \noindent Thus the free variables of a \code{lambda} are the ones that
  15410. need special treatment. We need to transport at runtime the values
  15411. of those variables from the point where the \code{lambda} was created
  15412. to the point where the \code{lambda} is applied. An efficient solution
  15413. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15414. values of the free variables together with a function pointer into a
  15415. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15416. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15417. closure}
  15418. %
  15419. By design, we have all the ingredients to make closures:
  15420. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15421. function pointers. The function pointer resides at index $0$, and the
  15422. values for the free variables fill in the rest of the tuple.
  15423. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15424. to see how closures work. It is a three-step dance. The program calls
  15425. function \code{f}, which creates a closure for the \code{lambda}. The
  15426. closure is a tuple whose first element is a pointer to the top-level
  15427. function that we will generate for the \code{lambda}; the second
  15428. element is the value of \code{x}, which is \code{5}; and the third
  15429. element is \code{4}, the value of \code{y}. The closure does not
  15430. contain an element for \code{z} because \code{z} is not a free
  15431. variable of the \code{lambda}. Creating the closure is step 1 of the
  15432. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15433. shown in figure~\ref{fig:closures}.
  15434. %
  15435. The second call to \code{f} creates another closure, this time with
  15436. \code{3} in the second slot (for \code{x}). This closure is also
  15437. returned from \code{f} but bound to \code{h}, which is also shown in
  15438. figure~\ref{fig:closures}.
  15439. \begin{figure}[tbp]
  15440. \centering
  15441. \begin{minipage}{0.65\textwidth}
  15442. \begin{tcolorbox}[colback=white]
  15443. \includegraphics[width=\textwidth]{figs/closures}
  15444. \end{tcolorbox}
  15445. \end{minipage}
  15446. \caption{Flat closure representations for the two functions
  15447. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15448. \label{fig:closures}
  15449. \end{figure}
  15450. Continuing with the example, consider the application of \code{g} to
  15451. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15452. closure, we obtain the function pointer from the first element of the
  15453. closure and call it, passing in the closure itself and then the
  15454. regular arguments, in this case \code{11}. This technique for applying
  15455. a closure is step 2 of the dance.
  15456. %
  15457. But doesn't this \code{lambda} take only one argument, for parameter
  15458. \code{z}? The third and final step of the dance is generating a
  15459. top-level function for a \code{lambda}. We add an additional
  15460. parameter for the closure and insert an initialization at the beginning
  15461. of the function for each free variable, to bind those variables to the
  15462. appropriate elements from the closure parameter.
  15463. %
  15464. This three-step dance is known as \emph{closure
  15465. conversion}\index{subject}{closure conversion}. We discuss the
  15466. details of closure conversion in section~\ref{sec:closure-conversion}
  15467. and show the code generated from the example in
  15468. section~\ref{sec:example-lambda}. First, we define the syntax and
  15469. semantics of \LangLam{} in section~\ref{sec:r5}.
  15470. \section{The \LangLam{} Language}
  15471. \label{sec:r5}
  15472. The definitions of the concrete syntax and abstract syntax for
  15473. \LangLam{}, a language with anonymous functions and lexical scoping,
  15474. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15475. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15476. for \LangFun{}, which already has syntax for function application.
  15477. %
  15478. \python{The syntax also includes an assignment statement that includes
  15479. a type annotation for the variable on the left-hand side, which
  15480. facilitates the type checking of \code{lambda} expressions that we
  15481. discuss later in this section.}
  15482. %
  15483. \racket{The \code{procedure-arity} operation returns the number of parameters
  15484. of a given function, an operation that we need for the translation
  15485. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15486. %
  15487. \python{The \code{arity} operation returns the number of parameters of
  15488. a given function, an operation that we need for the translation
  15489. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15490. The \code{arity} operation is not in Python, but the same functionality
  15491. is available in a more complex form. We include \code{arity} in the
  15492. \LangLam{} source language to enable testing.}
  15493. \newcommand{\LlambdaGrammarRacket}{
  15494. \begin{array}{lcl}
  15495. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15496. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15497. \end{array}
  15498. }
  15499. \newcommand{\LlambdaASTRacket}{
  15500. \begin{array}{lcl}
  15501. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15502. \itm{op} &::=& \code{procedure-arity}
  15503. \end{array}
  15504. }
  15505. \newcommand{\LlambdaGrammarPython}{
  15506. \begin{array}{lcl}
  15507. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15508. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15509. \end{array}
  15510. }
  15511. \newcommand{\LlambdaASTPython}{
  15512. \begin{array}{lcl}
  15513. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15514. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15515. \end{array}
  15516. }
  15517. % include AnnAssign in ASTPython
  15518. \begin{figure}[tp]
  15519. \centering
  15520. \begin{tcolorbox}[colback=white]
  15521. \small
  15522. {\if\edition\racketEd
  15523. \[
  15524. \begin{array}{l}
  15525. \gray{\LintGrammarRacket{}} \\ \hline
  15526. \gray{\LvarGrammarRacket{}} \\ \hline
  15527. \gray{\LifGrammarRacket{}} \\ \hline
  15528. \gray{\LwhileGrammarRacket} \\ \hline
  15529. \gray{\LtupGrammarRacket} \\ \hline
  15530. \gray{\LfunGrammarRacket} \\ \hline
  15531. \LlambdaGrammarRacket \\
  15532. \begin{array}{lcl}
  15533. \LangLamM{} &::=& \Def\ldots \; \Exp
  15534. \end{array}
  15535. \end{array}
  15536. \]
  15537. \fi}
  15538. {\if\edition\pythonEd\pythonColor
  15539. \[
  15540. \begin{array}{l}
  15541. \gray{\LintGrammarPython{}} \\ \hline
  15542. \gray{\LvarGrammarPython{}} \\ \hline
  15543. \gray{\LifGrammarPython{}} \\ \hline
  15544. \gray{\LwhileGrammarPython} \\ \hline
  15545. \gray{\LtupGrammarPython} \\ \hline
  15546. \gray{\LfunGrammarPython} \\ \hline
  15547. \LlambdaGrammarPython \\
  15548. \begin{array}{lcl}
  15549. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15550. \end{array}
  15551. \end{array}
  15552. \]
  15553. \fi}
  15554. \end{tcolorbox}
  15555. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15556. with \key{lambda}.}
  15557. \label{fig:Llam-concrete-syntax}
  15558. \end{figure}
  15559. \begin{figure}[tp]
  15560. \centering
  15561. \begin{tcolorbox}[colback=white]
  15562. \small
  15563. {\if\edition\racketEd
  15564. \[\arraycolsep=3pt
  15565. \begin{array}{l}
  15566. \gray{\LintOpAST} \\ \hline
  15567. \gray{\LvarASTRacket{}} \\ \hline
  15568. \gray{\LifASTRacket{}} \\ \hline
  15569. \gray{\LwhileASTRacket{}} \\ \hline
  15570. \gray{\LtupASTRacket{}} \\ \hline
  15571. \gray{\LfunASTRacket} \\ \hline
  15572. \LlambdaASTRacket \\
  15573. \begin{array}{lcl}
  15574. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15575. \end{array}
  15576. \end{array}
  15577. \]
  15578. \fi}
  15579. {\if\edition\pythonEd\pythonColor
  15580. \[
  15581. \begin{array}{l}
  15582. \gray{\LintASTPython} \\ \hline
  15583. \gray{\LvarASTPython{}} \\ \hline
  15584. \gray{\LifASTPython{}} \\ \hline
  15585. \gray{\LwhileASTPython{}} \\ \hline
  15586. \gray{\LtupASTPython{}} \\ \hline
  15587. \gray{\LfunASTPython} \\ \hline
  15588. \LlambdaASTPython \\
  15589. \begin{array}{lcl}
  15590. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15591. \end{array}
  15592. \end{array}
  15593. \]
  15594. \fi}
  15595. \end{tcolorbox}
  15596. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15597. \label{fig:Llam-syntax}
  15598. \end{figure}
  15599. Figure~\ref{fig:interp-Llambda} shows the definitional
  15600. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15601. \key{Lambda} saves the current environment inside the returned
  15602. function value. Recall that during function application, the
  15603. environment stored in the function value, extended with the mapping of
  15604. parameters to argument values, is used to interpret the body of the
  15605. function.
  15606. \begin{figure}[tbp]
  15607. \begin{tcolorbox}[colback=white]
  15608. {\if\edition\racketEd
  15609. \begin{lstlisting}
  15610. (define interp-Llambda-class
  15611. (class interp-Lfun-class
  15612. (super-new)
  15613. (define/override (interp-op op)
  15614. (match op
  15615. ['procedure-arity
  15616. (lambda (v)
  15617. (match v
  15618. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15619. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15620. [else (super interp-op op)]))
  15621. (define/override ((interp-exp env) e)
  15622. (define recur (interp-exp env))
  15623. (match e
  15624. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15625. `(function ,xs ,body ,env)]
  15626. [else ((super interp-exp env) e)]))
  15627. ))
  15628. (define (interp-Llambda p)
  15629. (send (new interp-Llambda-class) interp-program p))
  15630. \end{lstlisting}
  15631. \fi}
  15632. {\if\edition\pythonEd\pythonColor
  15633. \begin{lstlisting}
  15634. class InterpLlambda(InterpLfun):
  15635. def arity(self, v):
  15636. match v:
  15637. case Function(name, params, body, env):
  15638. return len(params)
  15639. case _:
  15640. raise Exception('Llambda arity unexpected ' + repr(v))
  15641. def interp_exp(self, e, env):
  15642. match e:
  15643. case Call(Name('arity'), [fun]):
  15644. f = self.interp_exp(fun, env)
  15645. return self.arity(f)
  15646. case Lambda(params, body):
  15647. return Function('lambda', params, [Return(body)], env)
  15648. case _:
  15649. return super().interp_exp(e, env)
  15650. def interp_stmt(self, s, env, cont):
  15651. match s:
  15652. case AnnAssign(lhs, typ, value, simple):
  15653. env[lhs.id] = self.interp_exp(value, env)
  15654. return self.interp_stmts(cont, env)
  15655. case Pass():
  15656. return self.interp_stmts(cont, env)
  15657. case _:
  15658. return super().interp_stmt(s, env, cont)
  15659. \end{lstlisting}
  15660. \fi}
  15661. \end{tcolorbox}
  15662. \caption{Interpreter for \LangLam{}.}
  15663. \label{fig:interp-Llambda}
  15664. \end{figure}
  15665. {\if\edition\racketEd
  15666. %
  15667. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15668. \key{lambda} form. The body of the \key{lambda} is checked in an
  15669. environment that includes the current environment (because it is
  15670. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15671. require the body's type to match the declared return type.
  15672. %
  15673. \fi}
  15674. {\if\edition\pythonEd\pythonColor
  15675. %
  15676. Figures~\ref{fig:type-check-Llambda} and
  15677. \ref{fig:type-check-Llambda-part2} define the type checker for
  15678. \LangLam{}, which is more complex than one might expect. The reason
  15679. for the added complexity is that the syntax of \key{lambda} does not
  15680. include type annotations for the parameters or return type. Instead
  15681. they must be inferred. There are many approaches to type inference
  15682. from which to choose, of varying degrees of complexity. We choose one
  15683. of the simpler approaches, bidirectional type
  15684. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15685. book is compilation, not type inference.
  15686. The main idea of bidirectional type inference is to add an auxiliary
  15687. function, here named \code{check\_exp}, that takes an expected type
  15688. and checks whether the given expression is of that type. Thus, in
  15689. \code{check\_exp}, type information flows in a top-down manner with
  15690. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15691. function, where type information flows in a primarily bottom-up
  15692. manner.
  15693. %
  15694. The idea then is to use \code{check\_exp} in all the places where we
  15695. already know what the type of an expression should be, such as in the
  15696. \code{return} statement of a top-level function definition or on the
  15697. right-hand side of an annotated assignment statement.
  15698. With regard to \code{lambda}, it is straightforward to check a
  15699. \code{lambda} inside \code{check\_exp} because the expected type
  15700. provides the parameter types and the return type. On the other hand,
  15701. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15702. that we do not allow \code{lambda} in contexts in which we don't already
  15703. know its type. This restriction does not incur a loss of
  15704. expressiveness for \LangLam{} because it is straightforward to modify
  15705. a program to sidestep the restriction, for example, by using an
  15706. annotated assignment statement to assign the \code{lambda} to a
  15707. temporary variable.
  15708. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15709. checker records their type in a \code{has\_type} field. This type
  15710. information is used further on in this chapter.
  15711. %
  15712. \fi}
  15713. \begin{figure}[tbp]
  15714. \begin{tcolorbox}[colback=white]
  15715. {\if\edition\racketEd
  15716. \begin{lstlisting}
  15717. (define (type-check-Llambda env)
  15718. (lambda (e)
  15719. (match e
  15720. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15721. (define-values (new-body bodyT)
  15722. ((type-check-exp (append (map cons xs Ts) env)) body))
  15723. (define ty `(,@Ts -> ,rT))
  15724. (cond
  15725. [(equal? rT bodyT)
  15726. (values (HasType (Lambda params rT new-body) ty) ty)]
  15727. [else
  15728. (error "mismatch in return type" bodyT rT)])]
  15729. ...
  15730. )))
  15731. \end{lstlisting}
  15732. \fi}
  15733. {\if\edition\pythonEd\pythonColor
  15734. \begin{lstlisting}
  15735. class TypeCheckLlambda(TypeCheckLfun):
  15736. def type_check_exp(self, e, env):
  15737. match e:
  15738. case Name(id):
  15739. e.has_type = env[id]
  15740. return env[id]
  15741. case Lambda(params, body):
  15742. raise Exception('cannot synthesize a type for a lambda')
  15743. case Call(Name('arity'), [func]):
  15744. func_t = self.type_check_exp(func, env)
  15745. match func_t:
  15746. case FunctionType(params_t, return_t):
  15747. return IntType()
  15748. case _:
  15749. raise Exception('in arity, unexpected ' + repr(func_t))
  15750. case _:
  15751. return super().type_check_exp(e, env)
  15752. def check_exp(self, e, ty, env):
  15753. match e:
  15754. case Lambda(params, body):
  15755. e.has_type = ty
  15756. match ty:
  15757. case FunctionType(params_t, return_t):
  15758. new_env = env.copy().update(zip(params, params_t))
  15759. self.check_exp(body, return_t, new_env)
  15760. case _:
  15761. raise Exception('lambda does not have type ' + str(ty))
  15762. case Call(func, args):
  15763. func_t = self.type_check_exp(func, env)
  15764. match func_t:
  15765. case FunctionType(params_t, return_t):
  15766. for (arg, param_t) in zip(args, params_t):
  15767. self.check_exp(arg, param_t, env)
  15768. self.check_type_equal(return_t, ty, e)
  15769. case _:
  15770. raise Exception('type_check_exp: in call, unexpected ' + \
  15771. repr(func_t))
  15772. case _:
  15773. t = self.type_check_exp(e, env)
  15774. self.check_type_equal(t, ty, e)
  15775. \end{lstlisting}
  15776. \fi}
  15777. \end{tcolorbox}
  15778. \caption{Type checking \LangLam{}\python{, part 1}.}
  15779. \label{fig:type-check-Llambda}
  15780. \end{figure}
  15781. {\if\edition\pythonEd\pythonColor
  15782. \begin{figure}[tbp]
  15783. \begin{tcolorbox}[colback=white]
  15784. \begin{lstlisting}
  15785. def check_stmts(self, ss, return_ty, env):
  15786. if len(ss) == 0:
  15787. return
  15788. match ss[0]:
  15789. case FunctionDef(name, params, body, dl, returns, comment):
  15790. new_env = env.copy().update(params)
  15791. rt = self.check_stmts(body, returns, new_env)
  15792. self.check_stmts(ss[1:], return_ty, env)
  15793. case Return(value):
  15794. self.check_exp(value, return_ty, env)
  15795. case Assign([Name(id)], value):
  15796. if id in env:
  15797. self.check_exp(value, env[id], env)
  15798. else:
  15799. env[id] = self.type_check_exp(value, env)
  15800. self.check_stmts(ss[1:], return_ty, env)
  15801. case Assign([Subscript(tup, Constant(index), Store())], value):
  15802. tup_t = self.type_check_exp(tup, env)
  15803. match tup_t:
  15804. case TupleType(ts):
  15805. self.check_exp(value, ts[index], env)
  15806. case _:
  15807. raise Exception('expected a tuple, not ' + repr(tup_t))
  15808. self.check_stmts(ss[1:], return_ty, env)
  15809. case AnnAssign(Name(id), ty_annot, value, simple):
  15810. ss[0].annotation = ty_annot
  15811. if id in env:
  15812. self.check_type_equal(env[id], ty_annot)
  15813. else:
  15814. env[id] = ty_annot
  15815. self.check_exp(value, ty_annot, env)
  15816. self.check_stmts(ss[1:], return_ty, env)
  15817. case _:
  15818. self.type_check_stmts(ss, env)
  15819. def type_check(self, p):
  15820. match p:
  15821. case Module(body):
  15822. env = {}
  15823. for s in body:
  15824. match s:
  15825. case FunctionDef(name, params, bod, dl, returns, comment):
  15826. params_t = [t for (x,t) in params]
  15827. env[name] = FunctionType(params_t, returns)
  15828. self.check_stmts(body, int, env)
  15829. \end{lstlisting}
  15830. \end{tcolorbox}
  15831. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15832. \label{fig:type-check-Llambda-part2}
  15833. \end{figure}
  15834. \fi}
  15835. \clearpage
  15836. \section{Assignment and Lexically Scoped Functions}
  15837. \label{sec:assignment-scoping}
  15838. The combination of lexically scoped functions and assignment to
  15839. variables raises a challenge with the flat-closure approach to
  15840. implementing lexically scoped functions. Consider the following
  15841. example in which function \code{f} has a free variable \code{x} that
  15842. is changed after \code{f} is created but before the call to \code{f}.
  15843. % loop_test_11.rkt
  15844. {\if\edition\racketEd
  15845. \begin{lstlisting}
  15846. (let ([x 0])
  15847. (let ([y 0])
  15848. (let ([z 20])
  15849. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15850. (begin
  15851. (set! x 10)
  15852. (set! y 12)
  15853. (f y))))))
  15854. \end{lstlisting}
  15855. \fi}
  15856. {\if\edition\pythonEd\pythonColor
  15857. % box_free_assign.py
  15858. \begin{lstlisting}
  15859. def g(z : int) -> int:
  15860. x = 0
  15861. y = 0
  15862. f : Callable[[int],int] = lambda a: a + x + z
  15863. x = 10
  15864. y = 12
  15865. return f(y)
  15866. print(g(20))
  15867. \end{lstlisting}
  15868. \fi} The correct output for this example is \code{42} because the call
  15869. to \code{f} is required to use the current value of \code{x} (which is
  15870. \code{10}). Unfortunately, the closure conversion pass
  15871. (section~\ref{sec:closure-conversion}) generates code for the
  15872. \code{lambda} that copies the old value of \code{x} into a
  15873. closure. Thus, if we naively applied closure conversion, the output of
  15874. this program would be \code{32}.
  15875. A first attempt at solving this problem would be to save a pointer to
  15876. \code{x} in the closure and change the occurrences of \code{x} inside
  15877. the lambda to dereference the pointer. Of course, this would require
  15878. assigning \code{x} to the stack and not to a register. However, the
  15879. problem goes a bit deeper.
  15880. Consider the following example that returns a function that refers to
  15881. a local variable of the enclosing function:
  15882. \begin{center}
  15883. \begin{minipage}{\textwidth}
  15884. {\if\edition\racketEd
  15885. \begin{lstlisting}
  15886. (define (f) : ( -> Integer)
  15887. (let ([x 0])
  15888. (let ([g (lambda: () : Integer x)])
  15889. (begin
  15890. (set! x 42)
  15891. g))))
  15892. ((f))
  15893. \end{lstlisting}
  15894. \fi}
  15895. {\if\edition\pythonEd\pythonColor
  15896. % counter.py
  15897. \begin{lstlisting}
  15898. def f():
  15899. x = 0
  15900. g = lambda: x
  15901. x = 42
  15902. return g
  15903. print(f()())
  15904. \end{lstlisting}
  15905. \fi}
  15906. \end{minipage}
  15907. \end{center}
  15908. In this example, the lifetime of \code{x} extends beyond the lifetime
  15909. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15910. stack frame for the call to \code{f}, it would be gone by the time we
  15911. called \code{g}, leaving us with dangling pointers for
  15912. \code{x}. This example demonstrates that when a variable occurs free
  15913. inside a function, its lifetime becomes indefinite. Thus, the value of
  15914. the variable needs to live on the heap. The verb
  15915. \emph{box}\index{subject}{box} is often used for allocating a single
  15916. value on the heap, producing a pointer, and
  15917. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15918. %
  15919. We introduce a new pass named \code{convert\_assignments} to address
  15920. this challenge.
  15921. %
  15922. \python{But before diving into that, we have one more
  15923. problem to discuss.}
  15924. {\if\edition\pythonEd\pythonColor
  15925. \section{Uniquify Variables}
  15926. \label{sec:uniquify-lambda}
  15927. With the addition of \code{lambda} we have a complication to deal
  15928. with: name shadowing. Consider the following program with a function
  15929. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15930. \code{lambda} expressions. The first \code{lambda} has a parameter
  15931. that is also named \code{x}.
  15932. \begin{lstlisting}
  15933. def f(x:int, y:int) -> Callable[[int], int]:
  15934. g : Callable[[int],int] = (lambda x: x + y)
  15935. h : Callable[[int],int] = (lambda y: x + y)
  15936. x = input_int()
  15937. return g
  15938. print(f(0, 10)(32))
  15939. \end{lstlisting}
  15940. Many of our compiler passes rely on being able to connect variable
  15941. uses with their definitions using just the name of the
  15942. variable. However, in the example above the name of the variable does
  15943. not uniquely determine its definition. To solve this problem we
  15944. recommend implementing a pass named \code{uniquify} that renames every
  15945. variable in the program to make sure that they are all unique.
  15946. The following shows the result of \code{uniquify} for the example
  15947. above. The \code{x} parameter of function \code{f} is renamed to
  15948. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15949. renamed to \code{x\_4}.
  15950. \begin{lstlisting}
  15951. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15952. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15953. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15954. x_0 = input_int()
  15955. return g_2
  15956. def main() -> int :
  15957. print(f(0, 10)(32))
  15958. return 0
  15959. \end{lstlisting}
  15960. \fi} % pythonEd
  15961. %% \section{Reveal Functions}
  15962. %% \label{sec:reveal-functions-r5}
  15963. %% \racket{To support the \code{procedure-arity} operator we need to
  15964. %% communicate the arity of a function to the point of closure
  15965. %% creation.}
  15966. %% %
  15967. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15968. %% function at runtime. Thus, we need to communicate the arity of a
  15969. %% function to the point of closure creation.}
  15970. %% %
  15971. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15972. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15973. %% \[
  15974. %% \begin{array}{lcl}
  15975. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15976. %% \end{array}
  15977. %% \]
  15978. \section{Assignment Conversion}
  15979. \label{sec:convert-assignments}
  15980. The purpose of the \code{convert\_assignments} pass is to address the
  15981. challenge regarding the interaction between variable assignments and
  15982. closure conversion. First we identify which variables need to be
  15983. boxed, and then we transform the program to box those variables. In
  15984. general, boxing introduces runtime overhead that we would like to
  15985. avoid, so we should box as few variables as possible. We recommend
  15986. boxing the variables in the intersection of the following two sets of
  15987. variables:
  15988. \begin{enumerate}
  15989. \item The variables that are free in a \code{lambda}.
  15990. \item The variables that appear on the left-hand side of an
  15991. assignment.
  15992. \end{enumerate}
  15993. The first condition is a must but the second condition is
  15994. conservative. It is possible to develop a more liberal condition using
  15995. static program analysis.
  15996. Consider again the first example from
  15997. section~\ref{sec:assignment-scoping}:
  15998. %
  15999. {\if\edition\racketEd
  16000. \begin{lstlisting}
  16001. (let ([x 0])
  16002. (let ([y 0])
  16003. (let ([z 20])
  16004. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16005. (begin
  16006. (set! x 10)
  16007. (set! y 12)
  16008. (f y))))))
  16009. \end{lstlisting}
  16010. \fi}
  16011. {\if\edition\pythonEd\pythonColor
  16012. \begin{lstlisting}
  16013. def g(z : int) -> int:
  16014. x = 0
  16015. y = 0
  16016. f : Callable[[int],int] = lambda a: a + x + z
  16017. x = 10
  16018. y = 12
  16019. return f(y)
  16020. print(g(20))
  16021. \end{lstlisting}
  16022. \fi}
  16023. %
  16024. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16025. side of assignments. The variables \code{x} and \code{z} occur free
  16026. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16027. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16028. three transformations: initialize \code{x} with a tuple whose elements
  16029. are uninitialized, replace reads from \code{x} with tuple reads, and
  16030. replace each assignment to \code{x} with a tuple write. The output of
  16031. \code{convert\_assignments} for this example is as follows:
  16032. %
  16033. {\if\edition\racketEd
  16034. \begin{lstlisting}
  16035. (define (main) : Integer
  16036. (let ([x0 (vector 0)])
  16037. (let ([y1 0])
  16038. (let ([z2 20])
  16039. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16040. (+ a3 (+ (vector-ref x0 0) z2)))])
  16041. (begin
  16042. (vector-set! x0 0 10)
  16043. (set! y1 12)
  16044. (f4 y1)))))))
  16045. \end{lstlisting}
  16046. \fi}
  16047. %
  16048. {\if\edition\pythonEd\pythonColor
  16049. \begin{lstlisting}
  16050. def g(z : int)-> int:
  16051. x = (uninitialized(int),)
  16052. x[0] = 0
  16053. y = 0
  16054. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16055. x[0] = 10
  16056. y = 12
  16057. return f(y)
  16058. def main() -> int:
  16059. print(g(20))
  16060. return 0
  16061. \end{lstlisting}
  16062. \fi}
  16063. To compute the free variables of all the \code{lambda} expressions, we
  16064. recommend defining the following two auxiliary functions:
  16065. \begin{enumerate}
  16066. \item \code{free\_variables} computes the free variables of an expression, and
  16067. \item \code{free\_in\_lambda} collects all the variables that are
  16068. free in any of the \code{lambda} expressions, using
  16069. \code{free\_variables} in the case for each \code{lambda}.
  16070. \end{enumerate}
  16071. {\if\edition\racketEd
  16072. %
  16073. To compute the variables that are assigned to, we recommend updating
  16074. the \code{collect-set!} function that we introduced in
  16075. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16076. as \code{Lambda}.
  16077. %
  16078. \fi}
  16079. {\if\edition\pythonEd\pythonColor
  16080. %
  16081. To compute the variables that are assigned to, we recommend defining
  16082. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16083. the set of variables that occur in the left-hand side of an assignment
  16084. statement and otherwise returns the empty set.
  16085. %
  16086. \fi}
  16087. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16088. free in a \code{lambda} and that are assigned to in the enclosing
  16089. function definition.
  16090. Next we discuss the \code{convert\_assignments} pass. In the case for
  16091. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16092. $\VAR{x}$ to a tuple read.
  16093. %
  16094. {\if\edition\racketEd
  16095. \begin{lstlisting}
  16096. (Var |$x$|)
  16097. |$\Rightarrow$|
  16098. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16099. \end{lstlisting}
  16100. \fi}
  16101. %
  16102. {\if\edition\pythonEd\pythonColor
  16103. \begin{lstlisting}
  16104. Name(|$x$|)
  16105. |$\Rightarrow$|
  16106. Subscript(Name(|$x$|), Constant(0), Load())
  16107. \end{lstlisting}
  16108. \fi}
  16109. %
  16110. \noindent In the case for assignment, recursively process the
  16111. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16112. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16113. as follows:
  16114. %
  16115. {\if\edition\racketEd
  16116. \begin{lstlisting}
  16117. (SetBang |$x$| |$\itm{rhs}$|)
  16118. |$\Rightarrow$|
  16119. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16120. \end{lstlisting}
  16121. \fi}
  16122. {\if\edition\pythonEd\pythonColor
  16123. \begin{lstlisting}
  16124. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16125. |$\Rightarrow$|
  16126. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16127. \end{lstlisting}
  16128. \fi}
  16129. %
  16130. {\if\edition\racketEd
  16131. The case for \code{Lambda} is nontrivial, but it is similar to the
  16132. case for function definitions, which we discuss next.
  16133. \fi}
  16134. %
  16135. To translate a function definition, we first compute $\mathit{AF}$,
  16136. the intersection of the variables that are free in a \code{lambda} and
  16137. that are assigned to. We then apply assignment conversion to the body
  16138. of the function definition. Finally, we box the parameters of this
  16139. function definition that are in $\mathit{AF}$. For example,
  16140. the parameter \code{x} of the following function \code{g}
  16141. needs to be boxed:
  16142. {\if\edition\racketEd
  16143. \begin{lstlisting}
  16144. (define (g [x : Integer]) : Integer
  16145. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16146. (begin
  16147. (set! x 10)
  16148. (f 32))))
  16149. \end{lstlisting}
  16150. \fi}
  16151. %
  16152. {\if\edition\pythonEd\pythonColor
  16153. \begin{lstlisting}
  16154. def g(x : int) -> int:
  16155. f : Callable[[int],int] = lambda a: a + x
  16156. x = 10
  16157. return f(32)
  16158. \end{lstlisting}
  16159. \fi}
  16160. %
  16161. \noindent We box parameter \code{x} by creating a local variable named
  16162. \code{x} that is initialized to a tuple whose contents is the value of
  16163. the parameter, which has been renamed to \code{x\_0}.
  16164. %
  16165. {\if\edition\racketEd
  16166. \begin{lstlisting}
  16167. (define (g [x_0 : Integer]) : Integer
  16168. (let ([x (vector x_0)])
  16169. (let ([f (lambda: ([a : Integer]) : Integer
  16170. (+ a (vector-ref x 0)))])
  16171. (begin
  16172. (vector-set! x 0 10)
  16173. (f 32)))))
  16174. \end{lstlisting}
  16175. \fi}
  16176. %
  16177. {\if\edition\pythonEd\pythonColor
  16178. \begin{lstlisting}
  16179. def g(x_0 : int)-> int:
  16180. x = (x_0,)
  16181. f : Callable[[int], int] = (lambda a: a + x[0])
  16182. x[0] = 10
  16183. return f(32)
  16184. \end{lstlisting}
  16185. \fi}
  16186. \section{Closure Conversion}
  16187. \label{sec:closure-conversion}
  16188. \index{subject}{closure conversion}
  16189. The compiling of lexically scoped functions into top-level function
  16190. definitions and flat closures is accomplished in the pass
  16191. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16192. and before \code{limit\_functions}.
  16193. As usual, we implement the pass as a recursive function over the
  16194. AST. The interesting cases are for \key{lambda} and function
  16195. application. We transform a \key{lambda} expression into an expression
  16196. that creates a closure, that is, a tuple for which the first element
  16197. is a function pointer and the rest of the elements are the values of
  16198. the free variables of the \key{lambda}.
  16199. %
  16200. However, we use the \code{Closure} AST node instead of using a tuple
  16201. so that we can record the arity.
  16202. %
  16203. In the generated code that follows, \itm{fvs} is the free variables of
  16204. the lambda and \itm{name} is a unique symbol generated to identify the
  16205. lambda.
  16206. %
  16207. \racket{The \itm{arity} is the number of parameters (the length of
  16208. \itm{ps}).}
  16209. %
  16210. {\if\edition\racketEd
  16211. \begin{lstlisting}
  16212. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16213. |$\Rightarrow$|
  16214. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16215. \end{lstlisting}
  16216. \fi}
  16217. %
  16218. {\if\edition\pythonEd\pythonColor
  16219. \begin{lstlisting}
  16220. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16221. |$\Rightarrow$|
  16222. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  16223. \end{lstlisting}
  16224. \fi}
  16225. %
  16226. In addition to transforming each \key{Lambda} AST node into a
  16227. tuple, we create a top-level function definition for each
  16228. \key{Lambda}, as shown next.\\
  16229. \begin{minipage}{0.8\textwidth}
  16230. {\if\edition\racketEd
  16231. \begin{lstlisting}
  16232. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16233. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16234. ...
  16235. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16236. |\itm{body'}|)...))
  16237. \end{lstlisting}
  16238. \fi}
  16239. {\if\edition\pythonEd\pythonColor
  16240. \begin{lstlisting}
  16241. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  16242. |$\itm{fvs}_1$| = clos[1]
  16243. |$\ldots$|
  16244. |$\itm{fvs}_n$| = clos[|$n$|]
  16245. |\itm{body'}|
  16246. \end{lstlisting}
  16247. \fi}
  16248. \end{minipage}\\
  16249. The \code{clos} parameter refers to the closure. Translate the type
  16250. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16251. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  16252. \itm{closTy} is a tuple type for which the first element type is
  16253. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  16254. the element types are the types of the free variables in the
  16255. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16256. is nontrivial to give a type to the function in the closure's type.%
  16257. %
  16258. \footnote{To give an accurate type to a closure, we would need to add
  16259. existential types to the type checker~\citep{Minamide:1996ys}.}
  16260. %
  16261. %% The dummy type is considered to be equal to any other type during type
  16262. %% checking.
  16263. The free variables become local variables that are initialized with
  16264. their values in the closure.
  16265. Closure conversion turns every function into a tuple, so the type
  16266. annotations in the program must also be translated. We recommend
  16267. defining an auxiliary recursive function for this purpose. Function
  16268. types should be translated as follows:
  16269. %
  16270. {\if\edition\racketEd
  16271. \begin{lstlisting}
  16272. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16273. |$\Rightarrow$|
  16274. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16275. \end{lstlisting}
  16276. \fi}
  16277. {\if\edition\pythonEd\pythonColor
  16278. \begin{lstlisting}
  16279. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16280. |$\Rightarrow$|
  16281. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16282. \end{lstlisting}
  16283. \fi}
  16284. %
  16285. This type indicates that the first thing in the tuple is a
  16286. function. The first parameter of the function is a tuple (a closure)
  16287. and the rest of the parameters are the ones from the original
  16288. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16289. omits the types of the free variables because (1) those types are not
  16290. available in this context, and (2) we do not need them in the code that
  16291. is generated for function application. So this type describes only the
  16292. first component of the closure tuple. At runtime the tuple may have
  16293. more components, but we ignore them at this point.
  16294. We transform function application into code that retrieves the
  16295. function from the closure and then calls the function, passing the
  16296. closure as the first argument. We place $e'$ in a temporary variable
  16297. to avoid code duplication.
  16298. \begin{center}
  16299. \begin{minipage}{\textwidth}
  16300. {\if\edition\racketEd
  16301. \begin{lstlisting}
  16302. (Apply |$e$| |$\itm{es}$|)
  16303. |$\Rightarrow$|
  16304. (Let |$\itm{tmp}$| |$e'$|
  16305. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16306. \end{lstlisting}
  16307. \fi}
  16308. %
  16309. {\if\edition\pythonEd\pythonColor
  16310. \begin{lstlisting}
  16311. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16312. |$\Rightarrow$|
  16313. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16314. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16315. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16316. \end{lstlisting}
  16317. \fi}
  16318. \end{minipage}
  16319. \end{center}
  16320. There is also the question of what to do with references to top-level
  16321. function definitions. To maintain a uniform translation of function
  16322. application, we turn function references into closures.
  16323. \begin{tabular}{lll}
  16324. \begin{minipage}{0.2\textwidth}
  16325. {\if\edition\racketEd
  16326. \begin{lstlisting}
  16327. (FunRef |$f$| |$n$|)
  16328. \end{lstlisting}
  16329. \fi}
  16330. {\if\edition\pythonEd\pythonColor
  16331. \begin{lstlisting}
  16332. FunRef(|$f$|, |$n$|)
  16333. \end{lstlisting}
  16334. \fi}
  16335. \end{minipage}
  16336. &
  16337. $\Rightarrow\qquad$
  16338. &
  16339. \begin{minipage}{0.5\textwidth}
  16340. {\if\edition\racketEd
  16341. \begin{lstlisting}
  16342. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16343. \end{lstlisting}
  16344. \fi}
  16345. {\if\edition\pythonEd\pythonColor
  16346. \begin{lstlisting}
  16347. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16348. \end{lstlisting}
  16349. \fi}
  16350. \end{minipage}
  16351. \end{tabular} \\
  16352. We no longer need the annotated assignment statement \code{AnnAssign}
  16353. to support the type checking of \code{lambda} expressions, so we
  16354. translate it to a regular \code{Assign} statement.
  16355. The top-level function definitions need to be updated to take an extra
  16356. closure parameter, but that parameter is ignored in the body of those
  16357. functions.
  16358. \section{An Example Translation}
  16359. \label{sec:example-lambda}
  16360. Figure~\ref{fig:lexical-functions-example} shows the result of
  16361. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16362. program demonstrating lexical scoping that we discussed at the
  16363. beginning of this chapter.
  16364. \begin{figure}[tbp]
  16365. \begin{tcolorbox}[colback=white]
  16366. \begin{minipage}{0.8\textwidth}
  16367. {\if\edition\racketEd
  16368. % tests/lambda_test_6.rkt
  16369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16370. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16371. (let ([y8 4])
  16372. (lambda: ([z9 : Integer]) : Integer
  16373. (+ x7 (+ y8 z9)))))
  16374. (define (main) : Integer
  16375. (let ([g0 ((fun-ref f6 1) 5)])
  16376. (let ([h1 ((fun-ref f6 1) 3)])
  16377. (+ (g0 11) (h1 15)))))
  16378. \end{lstlisting}
  16379. $\Rightarrow$
  16380. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16381. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16382. (let ([y8 4])
  16383. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16384. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16385. (let ([x7 (vector-ref fvs3 1)])
  16386. (let ([y8 (vector-ref fvs3 2)])
  16387. (+ x7 (+ y8 z9)))))
  16388. (define (main) : Integer
  16389. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16390. ((vector-ref clos5 0) clos5 5))])
  16391. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16392. ((vector-ref clos6 0) clos6 3))])
  16393. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16394. \end{lstlisting}
  16395. \fi}
  16396. %
  16397. {\if\edition\pythonEd\pythonColor
  16398. % free_var.py
  16399. \begin{lstlisting}
  16400. def f(x: int) -> Callable[[int],int]:
  16401. y = 4
  16402. return lambda z: x + y + z
  16403. g = f(5)
  16404. h = f(3)
  16405. print(g(11) + h(15))
  16406. \end{lstlisting}
  16407. $\Rightarrow$
  16408. \begin{lstlisting}
  16409. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16410. x = fvs_1[1]
  16411. y = fvs_1[2]
  16412. return (x + y[0] + z)
  16413. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16414. y = (uninitialized(int),)
  16415. y[0] = 4
  16416. return closure{1}({lambda_0}, x, y)
  16417. def main() -> int:
  16418. g = (begin: clos_3 = closure{1}({f})
  16419. clos_3[0](clos_3, 5))
  16420. h = (begin: clos_4 = closure{1}({f})
  16421. clos_4[0](clos_4, 3))
  16422. print((begin: clos_5 = g
  16423. clos_5[0](clos_5, 11))
  16424. + (begin: clos_6 = h
  16425. clos_6[0](clos_6, 15)))
  16426. return 0
  16427. \end{lstlisting}
  16428. \fi}
  16429. \end{minipage}
  16430. \end{tcolorbox}
  16431. \caption{Example of closure conversion.}
  16432. \label{fig:lexical-functions-example}
  16433. \end{figure}
  16434. \begin{exercise}\normalfont\normalsize
  16435. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16436. Create five new programs that use \key{lambda} functions and make use of
  16437. lexical scoping. Test your compiler on these new programs and all
  16438. your previously created test programs.
  16439. \end{exercise}
  16440. \section{Expose Allocation}
  16441. \label{sec:expose-allocation-r5}
  16442. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16443. that allocates and initializes a tuple, similar to the translation of
  16444. the tuple creation in section~\ref{sec:expose-allocation}.
  16445. The only difference is replacing the use of
  16446. \ALLOC{\itm{len}}{\itm{type}} with
  16447. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16448. \section{Explicate Control and \LangCLam{}}
  16449. \label{sec:explicate-r5}
  16450. The output language of \code{explicate\_control} is \LangCLam{}; the
  16451. definition of its abstract syntax is shown in
  16452. figure~\ref{fig:Clam-syntax}.
  16453. %
  16454. \racket{The only differences with respect to \LangCFun{} are the
  16455. addition of the \code{AllocateClosure} form to the grammar for
  16456. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16457. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16458. similar to the handling of other expressions such as primitive
  16459. operators.}
  16460. %
  16461. \python{The differences with respect to \LangCFun{} are the
  16462. additions of \code{Uninitialized}, \code{AllocateClosure},
  16463. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16464. \code{explicate\_control} pass is similar to the handling of other
  16465. expressions such as primitive operators.}
  16466. \newcommand{\ClambdaASTRacket}{
  16467. \begin{array}{lcl}
  16468. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16469. \itm{op} &::= & \code{procedure-arity}
  16470. \end{array}
  16471. }
  16472. \newcommand{\ClambdaASTPython}{
  16473. \begin{array}{lcl}
  16474. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16475. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16476. &\MID& \ARITY{\Atm}
  16477. \end{array}
  16478. }
  16479. \begin{figure}[tp]
  16480. \begin{tcolorbox}[colback=white]
  16481. \small
  16482. {\if\edition\racketEd
  16483. \[
  16484. \begin{array}{l}
  16485. \gray{\CvarASTRacket} \\ \hline
  16486. \gray{\CifASTRacket} \\ \hline
  16487. \gray{\CloopASTRacket} \\ \hline
  16488. \gray{\CtupASTRacket} \\ \hline
  16489. \gray{\CfunASTRacket} \\ \hline
  16490. \ClambdaASTRacket \\
  16491. \begin{array}{lcl}
  16492. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16493. \end{array}
  16494. \end{array}
  16495. \]
  16496. \fi}
  16497. {\if\edition\pythonEd\pythonColor
  16498. \[
  16499. \begin{array}{l}
  16500. \gray{\CifASTPython} \\ \hline
  16501. \gray{\CtupASTPython} \\ \hline
  16502. \gray{\CfunASTPython} \\ \hline
  16503. \ClambdaASTPython \\
  16504. \begin{array}{lcl}
  16505. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16506. \end{array}
  16507. \end{array}
  16508. \]
  16509. \fi}
  16510. \end{tcolorbox}
  16511. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16512. \label{fig:Clam-syntax}
  16513. \end{figure}
  16514. \section{Select Instructions}
  16515. \label{sec:select-instructions-Llambda}
  16516. \index{subject}{select instructions}
  16517. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16518. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16519. (section~\ref{sec:select-instructions-gc}). The only difference is
  16520. that you should place the \itm{arity} in the tag that is stored at
  16521. position $0$ of the tuple. Recall that in
  16522. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16523. was not used. We store the arity in the $5$ bits starting at position
  16524. $58$.
  16525. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16526. instructions that access the tag from position $0$ of the vector and
  16527. extract the $5$ bits starting at position $58$ from the tag.}
  16528. %
  16529. \python{Compile a call to the \code{arity} operator to a sequence of
  16530. instructions that access the tag from position $0$ of the tuple
  16531. (representing a closure) and extract the $5$ bits starting at position
  16532. $58$ from the tag.}
  16533. \begin{figure}[p]
  16534. \begin{tcolorbox}[colback=white]
  16535. {\if\edition\racketEd
  16536. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16537. \node (Lfun) at (0,2) {\large \LangLam{}};
  16538. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16539. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16540. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16541. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16542. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16543. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16544. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16545. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16546. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16547. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16548. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16549. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16550. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16551. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16552. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16553. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16554. \path[->,bend left=15] (Lfun) edge [above] node
  16555. {\ttfamily\footnotesize shrink} (Lfun-2);
  16556. \path[->,bend left=15] (Lfun-2) edge [above] node
  16557. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16558. \path[->,bend left=15] (Lfun-3) edge [above] node
  16559. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16560. \path[->,bend left=15] (F1-0) edge [left] node
  16561. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16562. \path[->,bend left=15] (F1-1) edge [below] node
  16563. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16564. \path[->,bend right=15] (F1-2) edge [above] node
  16565. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16566. \path[->,bend right=15] (F1-3) edge [above] node
  16567. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16568. \path[->,bend left=15] (F1-4) edge [right] node
  16569. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16570. \path[->,bend right=15] (F1-5) edge [below] node
  16571. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16572. \path[->,bend left=15] (F1-6) edge [above] node
  16573. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16574. \path[->] (C3-2) edge [right] node
  16575. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16576. \path[->,bend right=15] (x86-2) edge [right] node
  16577. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16578. \path[->,bend right=15] (x86-2-1) edge [below] node
  16579. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16580. \path[->,bend right=15] (x86-2-2) edge [right] node
  16581. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16582. \path[->,bend left=15] (x86-3) edge [above] node
  16583. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16584. \path[->,bend left=15] (x86-4) edge [right] node
  16585. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16586. \end{tikzpicture}
  16587. \fi}
  16588. {\if\edition\pythonEd\pythonColor
  16589. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16590. \node (Lfun) at (0,2) {\large \LangLam{}};
  16591. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16592. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16593. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16594. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16595. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16596. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16597. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16598. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16599. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16600. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16601. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16602. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16603. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16604. \path[->,bend left=15] (Lfun) edge [above] node
  16605. {\ttfamily\footnotesize shrink} (Lfun-2);
  16606. \path[->,bend left=15] (Lfun-2) edge [above] node
  16607. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16608. \path[->,bend left=15] (Lfun-3) edge [above] node
  16609. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16610. \path[->,bend left=15] (F1-0) edge [left] node
  16611. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16612. \path[->,bend left=15] (F1-1) edge [below] node
  16613. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16614. \path[->,bend left=15] (F1-2) edge [below] node
  16615. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16616. \path[->,bend right=15] (F1-3) edge [above] node
  16617. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16618. \path[->,bend right=15] (F1-5) edge [right] node
  16619. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16620. \path[->,bend left=15] (F1-6) edge [right] node
  16621. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16622. \path[->,bend right=15] (C3-2) edge [right] node
  16623. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16624. \path[->,bend right=15] (x86-2) edge [below] node
  16625. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16626. \path[->,bend right=15] (x86-3) edge [below] node
  16627. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16628. \path[->,bend left=15] (x86-4) edge [above] node
  16629. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16630. \end{tikzpicture}
  16631. \fi}
  16632. \end{tcolorbox}
  16633. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16634. functions.}
  16635. \label{fig:Llambda-passes}
  16636. \end{figure}
  16637. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16638. needed for the compilation of \LangLam{}.
  16639. \clearpage
  16640. \section{Challenge: Optimize Closures}
  16641. \label{sec:optimize-closures}
  16642. In this chapter we compile lexically scoped functions into a
  16643. relatively efficient representation: flat closures. However, even this
  16644. representation comes with some overhead. For example, consider the
  16645. following program with a function \code{tail\_sum} that does not have
  16646. any free variables and where all the uses of \code{tail\_sum} are in
  16647. applications in which we know that only \code{tail\_sum} is being applied
  16648. (and not any other functions):
  16649. \begin{center}
  16650. \begin{minipage}{0.95\textwidth}
  16651. {\if\edition\racketEd
  16652. \begin{lstlisting}
  16653. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16654. (if (eq? n 0)
  16655. s
  16656. (tail_sum (- n 1) (+ n s))))
  16657. (+ (tail_sum 3 0) 36)
  16658. \end{lstlisting}
  16659. \fi}
  16660. {\if\edition\pythonEd\pythonColor
  16661. \begin{lstlisting}
  16662. def tail_sum(n : int, s : int) -> int:
  16663. if n == 0:
  16664. return s
  16665. else:
  16666. return tail_sum(n - 1, n + s)
  16667. print(tail_sum(3, 0) + 36)
  16668. \end{lstlisting}
  16669. \fi}
  16670. \end{minipage}
  16671. \end{center}
  16672. As described in this chapter, we uniformly apply closure conversion to
  16673. all functions, obtaining the following output for this program:
  16674. \begin{center}
  16675. \begin{minipage}{0.95\textwidth}
  16676. {\if\edition\racketEd
  16677. \begin{lstlisting}
  16678. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16679. (if (eq? n2 0)
  16680. s3
  16681. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16682. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16683. (define (main) : Integer
  16684. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16685. ((vector-ref clos6 0) clos6 3 0)) 27))
  16686. \end{lstlisting}
  16687. \fi}
  16688. {\if\edition\pythonEd\pythonColor
  16689. \begin{lstlisting}
  16690. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16691. if n_0 == 0:
  16692. return s_1
  16693. else:
  16694. return (begin: clos_2 = (tail_sum,)
  16695. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16696. def main() -> int :
  16697. print((begin: clos_4 = (tail_sum,)
  16698. clos_4[0](clos_4, 3, 0)) + 36)
  16699. return 0
  16700. \end{lstlisting}
  16701. \fi}
  16702. \end{minipage}
  16703. \end{center}
  16704. If this program were compiled according to the previous chapter, there
  16705. would be no allocation and the calls to \code{tail\_sum} would be
  16706. direct calls. In contrast, the program presented here allocates memory
  16707. for each closure and the calls to \code{tail\_sum} are indirect. These
  16708. two differences incur considerable overhead in a program such as this,
  16709. in which the allocations and indirect calls occur inside a tight loop.
  16710. One might think that this problem is trivial to solve: can't we just
  16711. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16712. and compile them to direct calls instead of treating it like a call to
  16713. a closure? We would also drop the new \code{fvs} parameter of
  16714. \code{tail\_sum}.
  16715. %
  16716. However, this problem is not so trivial, because a global function may
  16717. \emph{escape} and become involved in applications that also involve
  16718. closures. Consider the following example in which the application
  16719. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16720. application because the \code{lambda} may flow into \code{f}, but the
  16721. \code{inc} function might also flow into \code{f}:
  16722. \begin{center}
  16723. \begin{minipage}{\textwidth}
  16724. % lambda_test_30.rkt
  16725. {\if\edition\racketEd
  16726. \begin{lstlisting}
  16727. (define (inc [x : Integer]) : Integer
  16728. (+ x 1))
  16729. (let ([y (read)])
  16730. (let ([f (if (eq? (read) 0)
  16731. inc
  16732. (lambda: ([x : Integer]) : Integer (- x y)))])
  16733. (f 41)))
  16734. \end{lstlisting}
  16735. \fi}
  16736. {\if\edition\pythonEd\pythonColor
  16737. \begin{lstlisting}
  16738. def add1(x : int) -> int:
  16739. return x + 1
  16740. y = input_int()
  16741. g : Callable[[int], int] = lambda x: x - y
  16742. f = add1 if input_int() == 0 else g
  16743. print(f(41))
  16744. \end{lstlisting}
  16745. \fi}
  16746. \end{minipage}
  16747. \end{center}
  16748. If a global function name is used in any way other than as the
  16749. operator in a direct call, then we say that the function
  16750. \emph{escapes}. If a global function does not escape, then we do not
  16751. need to perform closure conversion on the function.
  16752. \begin{exercise}\normalfont\normalsize
  16753. Implement an auxiliary function for detecting which global
  16754. functions escape. Using that function, implement an improved version
  16755. of closure conversion that does not apply closure conversion to
  16756. global functions that do not escape but instead compiles them as
  16757. regular functions. Create several new test cases that check whether
  16758. your compiler properly detects whether global functions escape or not.
  16759. \end{exercise}
  16760. So far we have reduced the overhead of calling global functions, but
  16761. it would also be nice to reduce the overhead of calling a
  16762. \code{lambda} when we can determine at compile time which
  16763. \code{lambda} will be called. We refer to such calls as \emph{known
  16764. calls}. Consider the following example in which a \code{lambda} is
  16765. bound to \code{f} and then applied.
  16766. {\if\edition\racketEd
  16767. % lambda_test_9.rkt
  16768. \begin{lstlisting}
  16769. (let ([y (read)])
  16770. (let ([f (lambda: ([x : Integer]) : Integer
  16771. (+ x y))])
  16772. (f 21)))
  16773. \end{lstlisting}
  16774. \fi}
  16775. {\if\edition\pythonEd\pythonColor
  16776. \begin{lstlisting}
  16777. y = input_int()
  16778. f : Callable[[int],int] = lambda x: x + y
  16779. print(f(21))
  16780. \end{lstlisting}
  16781. \fi}
  16782. %
  16783. \noindent Closure conversion compiles the application
  16784. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16785. %
  16786. {\if\edition\racketEd
  16787. \begin{lstlisting}
  16788. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16789. (let ([y2 (vector-ref fvs6 1)])
  16790. (+ x3 y2)))
  16791. (define (main) : Integer
  16792. (let ([y2 (read)])
  16793. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16794. ((vector-ref f4 0) f4 21))))
  16795. \end{lstlisting}
  16796. \fi}
  16797. {\if\edition\pythonEd\pythonColor
  16798. \begin{lstlisting}
  16799. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16800. y_1 = fvs_4[1]
  16801. return x_2 + y_1[0]
  16802. def main() -> int:
  16803. y_1 = (777,)
  16804. y_1[0] = input_int()
  16805. f_0 = (lambda_3, y_1)
  16806. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16807. return 0
  16808. \end{lstlisting}
  16809. \fi}
  16810. %
  16811. \noindent However, we can instead compile the application
  16812. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16813. %
  16814. {\if\edition\racketEd
  16815. \begin{lstlisting}
  16816. (define (main) : Integer
  16817. (let ([y2 (read)])
  16818. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16819. ((fun-ref lambda5 1) f4 21))))
  16820. \end{lstlisting}
  16821. \fi}
  16822. {\if\edition\pythonEd\pythonColor
  16823. \begin{lstlisting}
  16824. def main() -> int:
  16825. y_1 = (777,)
  16826. y_1[0] = input_int()
  16827. f_0 = (lambda_3, y_1)
  16828. print(lambda_3(f_0, 21))
  16829. return 0
  16830. \end{lstlisting}
  16831. \fi}
  16832. The problem of determining which \code{lambda} will be called from a
  16833. particular application is quite challenging in general and the topic
  16834. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16835. following exercise we recommend that you compile an application to a
  16836. direct call when the operator is a variable and \racket{the variable
  16837. is \code{let}-bound to a closure}\python{the previous assignment to
  16838. the variable is a closure}. This can be accomplished by maintaining
  16839. an environment that maps variables to function names. Extend the
  16840. environment whenever you encounter a closure on the right-hand side of
  16841. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16842. name of the global function for the closure. This pass should come
  16843. after closure conversion.
  16844. \begin{exercise}\normalfont\normalsize
  16845. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16846. compiles known calls into direct calls. Verify that your compiler is
  16847. successful in this regard on several example programs.
  16848. \end{exercise}
  16849. These exercises only scratch the surface of closure optimization. A
  16850. good next step for the interested reader is to look at the work of
  16851. \citet{Keep:2012ab}.
  16852. \section{Further Reading}
  16853. The notion of lexically scoped functions predates modern computers by
  16854. about a decade. They were invented by \citet{Church:1932aa}, who
  16855. proposed the lambda calculus as a foundation for logic. Anonymous
  16856. functions were included in the LISP~\citep{McCarthy:1960dz}
  16857. programming language but were initially dynamically scoped. The Scheme
  16858. dialect of LISP adopted lexical scoping, and
  16859. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16860. Scheme programs. However, environments were represented as linked
  16861. lists, so variable look-up was linear in the size of the
  16862. environment. \citet{Appel91} gives a detailed description of several
  16863. closure representations. In this chapter we represent environments
  16864. using flat closures, which were invented by
  16865. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16866. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16867. closures, variable look-up is constant time but the time to create a
  16868. closure is proportional to the number of its free variables. Flat
  16869. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16870. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16871. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16872. % compilers)
  16873. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16874. \chapter{Dynamic Typing}
  16875. \label{ch:Ldyn}
  16876. \index{subject}{dynamic typing}
  16877. \setcounter{footnote}{0}
  16878. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16879. typed language that is a subset of \racket{Racket}\python{Python}. The
  16880. focus on dynamic typing is in contrast to the previous chapters, which
  16881. have studied the compilation of statically typed languages. In
  16882. dynamically typed languages such as \LangDyn{}, a particular
  16883. expression may produce a value of a different type each time it is
  16884. executed. Consider the following example with a conditional \code{if}
  16885. expression that may return a Boolean or an integer depending on the
  16886. input to the program:
  16887. % part of dynamic_test_25.rkt
  16888. {\if\edition\racketEd
  16889. \begin{lstlisting}
  16890. (not (if (eq? (read) 1) #f 0))
  16891. \end{lstlisting}
  16892. \fi}
  16893. {\if\edition\pythonEd\pythonColor
  16894. \begin{lstlisting}
  16895. not (False if input_int() == 1 else 0)
  16896. \end{lstlisting}
  16897. \fi}
  16898. Languages that allow expressions to produce different kinds of values
  16899. are called \emph{polymorphic}, a word composed of the Greek roots
  16900. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16901. There are several kinds of polymorphism in programming languages, such as
  16902. subtype polymorphism\index{subject}{subtype polymorphism} and
  16903. parametric polymorphism\index{subject}{parametric polymorphism}
  16904. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16905. study in this chapter does not have a special name; it is the kind
  16906. that arises in dynamically typed languages.
  16907. Another characteristic of dynamically typed languages is that
  16908. their primitive operations, such as \code{not}, are often defined to operate
  16909. on many different types of values. In fact, in
  16910. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16911. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16912. given anything else it returns \FALSE{}.
  16913. Furthermore, even when primitive operations restrict their inputs to
  16914. values of a certain type, this restriction is enforced at runtime
  16915. instead of during compilation. For example, the tuple read
  16916. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16917. results in a runtime error because the first argument must
  16918. be a tuple, not a Boolean.
  16919. \section{The \LangDyn{} Language}
  16920. \newcommand{\LdynGrammarRacket}{
  16921. \begin{array}{rcl}
  16922. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16923. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16924. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16925. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16926. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16927. \end{array}
  16928. }
  16929. \newcommand{\LdynASTRacket}{
  16930. \begin{array}{lcl}
  16931. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16932. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16933. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16934. \end{array}
  16935. }
  16936. \begin{figure}[tp]
  16937. \centering
  16938. \begin{tcolorbox}[colback=white]
  16939. \small
  16940. {\if\edition\racketEd
  16941. \[
  16942. \begin{array}{l}
  16943. \gray{\LintGrammarRacket{}} \\ \hline
  16944. \gray{\LvarGrammarRacket{}} \\ \hline
  16945. \gray{\LifGrammarRacket{}} \\ \hline
  16946. \gray{\LwhileGrammarRacket} \\ \hline
  16947. \gray{\LtupGrammarRacket} \\ \hline
  16948. \LdynGrammarRacket \\
  16949. \begin{array}{rcl}
  16950. \LangDynM{} &::=& \Def\ldots\; \Exp
  16951. \end{array}
  16952. \end{array}
  16953. \]
  16954. \fi}
  16955. {\if\edition\pythonEd\pythonColor
  16956. \[
  16957. \begin{array}{rcl}
  16958. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16959. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16960. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16961. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16962. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16963. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16964. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16965. \MID \CLEN{\Exp} \\
  16966. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16967. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16968. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16969. \MID \Var\mathop{\key{=}}\Exp \\
  16970. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16971. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16972. &\MID& \CRETURN{\Exp} \\
  16973. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16974. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16975. \end{array}
  16976. \]
  16977. \fi}
  16978. \end{tcolorbox}
  16979. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16980. \label{fig:r7-concrete-syntax}
  16981. \end{figure}
  16982. \begin{figure}[tp]
  16983. \centering
  16984. \begin{tcolorbox}[colback=white]
  16985. \small
  16986. {\if\edition\racketEd
  16987. \[
  16988. \begin{array}{l}
  16989. \gray{\LintASTRacket{}} \\ \hline
  16990. \gray{\LvarASTRacket{}} \\ \hline
  16991. \gray{\LifASTRacket{}} \\ \hline
  16992. \gray{\LwhileASTRacket} \\ \hline
  16993. \gray{\LtupASTRacket} \\ \hline
  16994. \LdynASTRacket \\
  16995. \begin{array}{lcl}
  16996. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16997. \end{array}
  16998. \end{array}
  16999. \]
  17000. \fi}
  17001. {\if\edition\pythonEd\pythonColor
  17002. \[
  17003. \begin{array}{rcl}
  17004. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17005. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17006. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17007. \MID \code{Is()} \\
  17008. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17009. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17010. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17011. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17012. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17013. &\MID& \VAR{\Var{}}
  17014. \MID \BOOL{\itm{bool}}
  17015. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17016. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17017. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17018. &\MID& \LEN{\Exp} \\
  17019. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17020. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17021. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17022. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17023. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17024. &\MID& \RETURN{\Exp} \\
  17025. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17026. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17027. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17028. \end{array}
  17029. \]
  17030. \fi}
  17031. \end{tcolorbox}
  17032. \caption{The abstract syntax of \LangDyn{}.}
  17033. \label{fig:r7-syntax}
  17034. \end{figure}
  17035. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17036. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17037. %
  17038. There is no type checker for \LangDyn{} because it checks types only
  17039. at runtime.
  17040. The definitional interpreter for \LangDyn{} is presented in
  17041. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17042. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17043. \INT{n}. Instead of simply returning the integer \code{n} (as
  17044. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17045. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17046. value} that combines an underlying value with a tag that identifies
  17047. what kind of value it is. We define the following \racket{struct}\python{class}
  17048. to represent tagged values:
  17049. %
  17050. {\if\edition\racketEd
  17051. \begin{lstlisting}
  17052. (struct Tagged (value tag) #:transparent)
  17053. \end{lstlisting}
  17054. \fi}
  17055. {\if\edition\pythonEd\pythonColor
  17056. \begin{minipage}{\textwidth}
  17057. \begin{lstlisting}
  17058. @dataclass(eq=True)
  17059. class Tagged(Value):
  17060. value : Value
  17061. tag : str
  17062. def __str__(self):
  17063. return str(self.value)
  17064. \end{lstlisting}
  17065. \end{minipage}
  17066. \fi}
  17067. %
  17068. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17069. \code{Vector}, and \code{Procedure}.}
  17070. %
  17071. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17072. \skey{tuple}, and \skey{function}.}
  17073. %
  17074. Tags are closely related to types but do not always capture all the
  17075. information that a type does.
  17076. %
  17077. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17078. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17079. Any)} is tagged with \code{Procedure}.}
  17080. %
  17081. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17082. is tagged with \skey{tuple} and a function of type
  17083. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17084. is tagged with \skey{function}.}
  17085. Next consider the match case for accessing the element of a tuple.
  17086. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17087. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17088. argument is a tuple and the second is an integer.
  17089. \racket{
  17090. If they are not, a \code{trapped-error} is raised. Recall from
  17091. section~\ref{sec:interp_Lint} that when a definition interpreter
  17092. raises a \code{trapped-error} error, the compiled code must also
  17093. signal an error by exiting with return code \code{255}. A
  17094. \code{trapped-error} is also raised if the index is not less than the
  17095. length of the vector.
  17096. }
  17097. %
  17098. \python{If they are not, an exception is raised. The compiled code
  17099. must also signal an error by exiting with return code \code{255}. A
  17100. exception is also raised if the index is not less than the length of the
  17101. tuple or if it is negative.}
  17102. \begin{figure}[tbp]
  17103. \begin{tcolorbox}[colback=white]
  17104. {\if\edition\racketEd
  17105. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17106. (define ((interp-Ldyn-exp env) ast)
  17107. (define recur (interp-Ldyn-exp env))
  17108. (match ast
  17109. [(Var x) (dict-ref env x)]
  17110. [(Int n) (Tagged n 'Integer)]
  17111. [(Bool b) (Tagged b 'Boolean)]
  17112. [(Lambda xs rt body)
  17113. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17114. [(Prim 'vector es)
  17115. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17116. [(Prim 'vector-ref (list e1 e2))
  17117. (define vec (recur e1)) (define i (recur e2))
  17118. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17119. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17120. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17121. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17122. [(Prim 'vector-set! (list e1 e2 e3))
  17123. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17124. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17125. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17126. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17127. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17128. (Tagged (void) 'Void)]
  17129. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17130. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17131. [(Prim 'or (list e1 e2))
  17132. (define v1 (recur e1))
  17133. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17134. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17135. [(Prim op (list e1))
  17136. #:when (set-member? type-predicates op)
  17137. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17138. [(Prim op es)
  17139. (define args (map recur es))
  17140. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17141. (unless (for/or ([expected-tags (op-tags op)])
  17142. (equal? expected-tags tags))
  17143. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17144. (tag-value
  17145. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17146. [(If q t f)
  17147. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17148. [(Apply f es)
  17149. (define new-f (recur f)) (define args (map recur es))
  17150. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17151. (match f-val
  17152. [`(function ,xs ,body ,lam-env)
  17153. (unless (eq? (length xs) (length args))
  17154. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17155. (define new-env (append (map cons xs args) lam-env))
  17156. ((interp-Ldyn-exp new-env) body)]
  17157. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17158. \end{lstlisting}
  17159. \fi}
  17160. {\if\edition\pythonEd\pythonColor
  17161. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17162. class InterpLdyn(InterpLlambda):
  17163. def interp_exp(self, e, env):
  17164. match e:
  17165. case Constant(n):
  17166. return self.tag(super().interp_exp(e, env))
  17167. case Tuple(es, Load()):
  17168. return self.tag(super().interp_exp(e, env))
  17169. case Lambda(params, body):
  17170. return self.tag(super().interp_exp(e, env))
  17171. case Call(Name('input_int'), []):
  17172. return self.tag(super().interp_exp(e, env))
  17173. case BinOp(left, Add(), right):
  17174. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17175. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17176. case BinOp(left, Sub(), right):
  17177. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17178. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17179. case UnaryOp(USub(), e1):
  17180. v = self.interp_exp(e1, env)
  17181. return self.tag(- self.untag(v, 'int', e))
  17182. case IfExp(test, body, orelse):
  17183. v = self.interp_exp(test, env)
  17184. if self.untag(v, 'bool', e):
  17185. return self.interp_exp(body, env)
  17186. else:
  17187. return self.interp_exp(orelse, env)
  17188. case UnaryOp(Not(), e1):
  17189. v = self.interp_exp(e1, env)
  17190. return self.tag(not self.untag(v, 'bool', e))
  17191. case BoolOp(And(), values):
  17192. left = values[0]; right = values[1]
  17193. l = self.interp_exp(left, env)
  17194. if self.untag(l, 'bool', e):
  17195. return self.interp_exp(right, env)
  17196. else:
  17197. return self.tag(False)
  17198. case BoolOp(Or(), values):
  17199. left = values[0]; right = values[1]
  17200. l = self.interp_exp(left, env)
  17201. if self.untag(l, 'bool', e):
  17202. return self.tag(True)
  17203. else:
  17204. return self.interp_exp(right, env)
  17205. case Compare(left, [cmp], [right]):
  17206. l = self.interp_exp(left, env)
  17207. r = self.interp_exp(right, env)
  17208. if l.tag == r.tag:
  17209. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17210. else:
  17211. raise Exception('interp Compare unexpected '
  17212. + repr(l) + ' ' + repr(r))
  17213. case Subscript(tup, index, Load()):
  17214. t = self.interp_exp(tup, env)
  17215. n = self.interp_exp(index, env)
  17216. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17217. case Call(Name('len'), [tup]):
  17218. t = self.interp_exp(tup, env)
  17219. return self.tag(len(self.untag(t, 'tuple', e)))
  17220. case _:
  17221. return self.tag(super().interp_exp(e, env))
  17222. \end{lstlisting}
  17223. \fi}
  17224. \end{tcolorbox}
  17225. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17226. \label{fig:interp-Ldyn}
  17227. \end{figure}
  17228. {\if\edition\pythonEd\pythonColor
  17229. \begin{figure}[tbp]
  17230. \begin{tcolorbox}[colback=white]
  17231. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17232. class InterpLdyn(InterpLlambda):
  17233. def interp_stmt(self, s, env, cont):
  17234. match s:
  17235. case If(test, body, orelse):
  17236. v = self.interp_exp(test, env)
  17237. match self.untag(v, 'bool', s):
  17238. case True:
  17239. return self.interp_stmts(body + cont, env)
  17240. case False:
  17241. return self.interp_stmts(orelse + cont, env)
  17242. case While(test, body, []):
  17243. v = self.interp_exp(test, env)
  17244. if self.untag(v, 'bool', test):
  17245. self.interp_stmts(body + [s] + cont, env)
  17246. else:
  17247. return self.interp_stmts(cont, env)
  17248. case Assign([Subscript(tup, index)], value):
  17249. tup = self.interp_exp(tup, env)
  17250. index = self.interp_exp(index, env)
  17251. tup_v = self.untag(tup, 'tuple', s)
  17252. index_v = self.untag(index, 'int', s)
  17253. tup_v[index_v] = self.interp_exp(value, env)
  17254. return self.interp_stmts(cont, env)
  17255. case FunctionDef(name, params, bod, dl, returns, comment):
  17256. if isinstance(params, ast.arguments):
  17257. ps = [p.arg for p in params.args]
  17258. else:
  17259. ps = [x for (x,t) in params]
  17260. env[name] = self.tag(Function(name, ps, bod, env))
  17261. return self.interp_stmts(cont, env)
  17262. case _:
  17263. return super().interp_stmt(s, env, cont)
  17264. \end{lstlisting}
  17265. \end{tcolorbox}
  17266. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17267. \label{fig:interp-Ldyn-2}
  17268. \end{figure}
  17269. \fi}
  17270. \begin{figure}[tbp]
  17271. \begin{tcolorbox}[colback=white]
  17272. {\if\edition\racketEd
  17273. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17274. (define (interp-op op)
  17275. (match op
  17276. ['+ fx+]
  17277. ['- fx-]
  17278. ['read read-fixnum]
  17279. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17280. ['< (lambda (v1 v2)
  17281. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17282. ['<= (lambda (v1 v2)
  17283. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17284. ['> (lambda (v1 v2)
  17285. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17286. ['>= (lambda (v1 v2)
  17287. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17288. ['boolean? boolean?]
  17289. ['integer? fixnum?]
  17290. ['void? void?]
  17291. ['vector? vector?]
  17292. ['vector-length vector-length]
  17293. ['procedure? (match-lambda
  17294. [`(functions ,xs ,body ,env) #t] [else #f])]
  17295. [else (error 'interp-op "unknown operator" op)]))
  17296. (define (op-tags op)
  17297. (match op
  17298. ['+ '((Integer Integer))]
  17299. ['- '((Integer Integer) (Integer))]
  17300. ['read '(())]
  17301. ['not '((Boolean))]
  17302. ['< '((Integer Integer))]
  17303. ['<= '((Integer Integer))]
  17304. ['> '((Integer Integer))]
  17305. ['>= '((Integer Integer))]
  17306. ['vector-length '((Vector))]))
  17307. (define type-predicates
  17308. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17309. (define (tag-value v)
  17310. (cond [(boolean? v) (Tagged v 'Boolean)]
  17311. [(fixnum? v) (Tagged v 'Integer)]
  17312. [(procedure? v) (Tagged v 'Procedure)]
  17313. [(vector? v) (Tagged v 'Vector)]
  17314. [(void? v) (Tagged v 'Void)]
  17315. [else (error 'tag-value "unidentified value ~a" v)]))
  17316. (define (check-tag val expected ast)
  17317. (define tag (Tagged-tag val))
  17318. (unless (eq? tag expected)
  17319. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17320. \end{lstlisting}
  17321. \fi}
  17322. {\if\edition\pythonEd\pythonColor
  17323. \begin{lstlisting}
  17324. class InterpLdyn(InterpLlambda):
  17325. def tag(self, v):
  17326. if v is True or v is False:
  17327. return Tagged(v, 'bool')
  17328. elif isinstance(v, int):
  17329. return Tagged(v, 'int')
  17330. elif isinstance(v, Function):
  17331. return Tagged(v, 'function')
  17332. elif isinstance(v, tuple):
  17333. return Tagged(v, 'tuple')
  17334. elif isinstance(v, type(None)):
  17335. return Tagged(v, 'none')
  17336. else:
  17337. raise Exception('tag: unexpected ' + repr(v))
  17338. def untag(self, v, expected_tag, ast):
  17339. match v:
  17340. case Tagged(val, tag) if tag == expected_tag:
  17341. return val
  17342. case _:
  17343. raise TrappedError('expected Tagged value with '
  17344. + expected_tag + ', not ' + ' ' + repr(v))
  17345. def apply_fun(self, fun, args, e):
  17346. f = self.untag(fun, 'function', e)
  17347. return super().apply_fun(f, args, e)
  17348. \end{lstlisting}
  17349. \fi}
  17350. \end{tcolorbox}
  17351. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17352. \label{fig:interp-Ldyn-aux}
  17353. \end{figure}
  17354. \clearpage
  17355. \section{Representation of Tagged Values}
  17356. The interpreter for \LangDyn{} introduced a new kind of value: the
  17357. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17358. represent tagged values at the bit level. Because almost every
  17359. operation in \LangDyn{} involves manipulating tagged values, the
  17360. representation must be efficient. Recall that all our values are 64
  17361. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17362. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17363. $011$ for procedures, and $101$ for the void value\python{,
  17364. \key{None}}. We define the following auxiliary function for mapping
  17365. types to tag codes:
  17366. %
  17367. {\if\edition\racketEd
  17368. \begin{align*}
  17369. \itm{tagof}(\key{Integer}) &= 001 \\
  17370. \itm{tagof}(\key{Boolean}) &= 100 \\
  17371. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17372. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17373. \itm{tagof}(\key{Void}) &= 101
  17374. \end{align*}
  17375. \fi}
  17376. {\if\edition\pythonEd\pythonColor
  17377. \begin{align*}
  17378. \itm{tagof}(\key{IntType()}) &= 001 \\
  17379. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17380. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17381. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17382. \itm{tagof}(\key{type(None)}) &= 101
  17383. \end{align*}
  17384. \fi}
  17385. %
  17386. This stealing of 3 bits comes at some price: integers are now restricted
  17387. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17388. affect tuples and procedures because those values are addresses, and
  17389. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17390. they are always $000$. Thus, we do not lose information by overwriting
  17391. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17392. to recover the original address.
  17393. To make tagged values into first-class entities, we can give them a
  17394. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17395. operations such as \code{Inject} and \code{Project} for creating and
  17396. using them, yielding the statically typed \LangAny{} intermediate
  17397. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17398. section~\ref{sec:compile-r7}; in the next section we describe the
  17399. \LangAny{} language in greater detail.
  17400. \section{The \LangAny{} Language}
  17401. \label{sec:Rany-lang}
  17402. \newcommand{\LanyASTRacket}{
  17403. \begin{array}{lcl}
  17404. \Type &::= & \ANYTY \\
  17405. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17406. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17407. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17408. \itm{op} &::= & \code{any-vector-length}
  17409. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17410. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17411. \MID \code{procedure?} \MID \code{void?} \\
  17412. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17413. \end{array}
  17414. }
  17415. \newcommand{\LanyASTPython}{
  17416. \begin{array}{lcl}
  17417. \Type &::= & \key{AnyType()} \\
  17418. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17419. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17420. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17421. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17422. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17423. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17424. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17425. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17426. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17427. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17428. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17429. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17430. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17431. \end{array}
  17432. }
  17433. \begin{figure}[tp]
  17434. \centering
  17435. \begin{tcolorbox}[colback=white]
  17436. \small
  17437. {\if\edition\racketEd
  17438. \[
  17439. \begin{array}{l}
  17440. \gray{\LintOpAST} \\ \hline
  17441. \gray{\LvarASTRacket{}} \\ \hline
  17442. \gray{\LifASTRacket{}} \\ \hline
  17443. \gray{\LwhileASTRacket{}} \\ \hline
  17444. \gray{\LtupASTRacket{}} \\ \hline
  17445. \gray{\LfunASTRacket} \\ \hline
  17446. \gray{\LlambdaASTRacket} \\ \hline
  17447. \LanyASTRacket \\
  17448. \begin{array}{lcl}
  17449. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17450. \end{array}
  17451. \end{array}
  17452. \]
  17453. \fi}
  17454. {\if\edition\pythonEd\pythonColor
  17455. \[
  17456. \begin{array}{l}
  17457. \gray{\LintASTPython} \\ \hline
  17458. \gray{\LvarASTPython{}} \\ \hline
  17459. \gray{\LifASTPython{}} \\ \hline
  17460. \gray{\LwhileASTPython{}} \\ \hline
  17461. \gray{\LtupASTPython{}} \\ \hline
  17462. \gray{\LfunASTPython} \\ \hline
  17463. \gray{\LlambdaASTPython} \\ \hline
  17464. \LanyASTPython \\
  17465. \begin{array}{lcl}
  17466. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17467. \end{array}
  17468. \end{array}
  17469. \]
  17470. \fi}
  17471. \end{tcolorbox}
  17472. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17473. \label{fig:Lany-syntax}
  17474. \end{figure}
  17475. The definition of the abstract syntax of \LangAny{} is given in
  17476. figure~\ref{fig:Lany-syntax}.
  17477. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17478. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17479. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17480. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17481. converts the tagged value produced by expression $e$ into a value of
  17482. type $T$ or halts the program if the type tag does not match $T$.
  17483. %
  17484. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17485. restricted to be a flat type (the nonterminal $\FType$) which
  17486. simplifies the implementation and complies with the needs for
  17487. compiling \LangDyn{}.
  17488. The \racket{\code{any-vector}} operators
  17489. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17490. operations so that they can be applied to a value of type
  17491. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17492. tuple operations in that the index is not restricted to a literal
  17493. integer in the grammar but is allowed to be any expression.
  17494. \racket{The type predicates such as
  17495. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17496. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17497. the predicate and return {\FALSE} otherwise.}
  17498. The type checker for \LangAny{} is shown in
  17499. figure~\ref{fig:type-check-Lany}
  17500. %
  17501. \racket{ and uses the auxiliary functions presented in
  17502. figure~\ref{fig:type-check-Lany-aux}}.
  17503. %
  17504. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17505. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17506. \begin{figure}[btp]
  17507. \begin{tcolorbox}[colback=white]
  17508. {\if\edition\racketEd
  17509. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17510. (define type-check-Lany-class
  17511. (class type-check-Llambda-class
  17512. (super-new)
  17513. (inherit check-type-equal?)
  17514. (define/override (type-check-exp env)
  17515. (lambda (e)
  17516. (define recur (type-check-exp env))
  17517. (match e
  17518. [(Inject e1 ty)
  17519. (unless (flat-ty? ty)
  17520. (error 'type-check "may only inject from flat type, not ~a" ty))
  17521. (define-values (new-e1 e-ty) (recur e1))
  17522. (check-type-equal? e-ty ty e)
  17523. (values (Inject new-e1 ty) 'Any)]
  17524. [(Project e1 ty)
  17525. (unless (flat-ty? ty)
  17526. (error 'type-check "may only project to flat type, not ~a" ty))
  17527. (define-values (new-e1 e-ty) (recur e1))
  17528. (check-type-equal? e-ty 'Any e)
  17529. (values (Project new-e1 ty) ty)]
  17530. [(Prim 'any-vector-length (list e1))
  17531. (define-values (e1^ t1) (recur e1))
  17532. (check-type-equal? t1 'Any e)
  17533. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17534. [(Prim 'any-vector-ref (list e1 e2))
  17535. (define-values (e1^ t1) (recur e1))
  17536. (define-values (e2^ t2) (recur e2))
  17537. (check-type-equal? t1 'Any e)
  17538. (check-type-equal? t2 'Integer e)
  17539. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17540. [(Prim 'any-vector-set! (list e1 e2 e3))
  17541. (define-values (e1^ t1) (recur e1))
  17542. (define-values (e2^ t2) (recur e2))
  17543. (define-values (e3^ t3) (recur e3))
  17544. (check-type-equal? t1 'Any e)
  17545. (check-type-equal? t2 'Integer e)
  17546. (check-type-equal? t3 'Any e)
  17547. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17548. [(Prim pred (list e1))
  17549. #:when (set-member? (type-predicates) pred)
  17550. (define-values (new-e1 e-ty) (recur e1))
  17551. (check-type-equal? e-ty 'Any e)
  17552. (values (Prim pred (list new-e1)) 'Boolean)]
  17553. [(Prim 'eq? (list arg1 arg2))
  17554. (define-values (e1 t1) (recur arg1))
  17555. (define-values (e2 t2) (recur arg2))
  17556. (match* (t1 t2)
  17557. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17558. [(other wise) (check-type-equal? t1 t2 e)])
  17559. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17560. [else ((super type-check-exp env) e)])))
  17561. ))
  17562. \end{lstlisting}
  17563. \fi}
  17564. {\if\edition\pythonEd\pythonColor
  17565. \begin{lstlisting}
  17566. class TypeCheckLany(TypeCheckLlambda):
  17567. def type_check_exp(self, e, env):
  17568. match e:
  17569. case Inject(value, typ):
  17570. self.check_exp(value, typ, env)
  17571. return AnyType()
  17572. case Project(value, typ):
  17573. self.check_exp(value, AnyType(), env)
  17574. return typ
  17575. case Call(Name('any_tuple_load'), [tup, index]):
  17576. self.check_exp(tup, AnyType(), env)
  17577. self.check_exp(index, IntType(), env)
  17578. return AnyType()
  17579. case Call(Name('any_len'), [tup]):
  17580. self.check_exp(tup, AnyType(), env)
  17581. return IntType()
  17582. case Call(Name('arity'), [fun]):
  17583. ty = self.type_check_exp(fun, env)
  17584. match ty:
  17585. case FunctionType(ps, rt):
  17586. return IntType()
  17587. case TupleType([FunctionType(ps,rs)]):
  17588. return IntType()
  17589. case _:
  17590. raise Exception('type check arity unexpected ' + repr(ty))
  17591. case Call(Name('make_any'), [value, tag]):
  17592. self.type_check_exp(value, env)
  17593. self.check_exp(tag, IntType(), env)
  17594. return AnyType()
  17595. case AnnLambda(params, returns, body):
  17596. new_env = {x:t for (x,t) in env.items()}
  17597. for (x,t) in params:
  17598. new_env[x] = t
  17599. return_t = self.type_check_exp(body, new_env)
  17600. self.check_type_equal(returns, return_t, e)
  17601. return FunctionType([t for (x,t) in params], return_t)
  17602. case _:
  17603. return super().type_check_exp(e, env)
  17604. \end{lstlisting}
  17605. \fi}
  17606. \end{tcolorbox}
  17607. \caption{Type checker for the \LangAny{} language.}
  17608. \label{fig:type-check-Lany}
  17609. \end{figure}
  17610. {\if\edition\racketEd
  17611. \begin{figure}[tbp]
  17612. \begin{tcolorbox}[colback=white]
  17613. \begin{lstlisting}
  17614. (define/override (operator-types)
  17615. (append
  17616. '((integer? . ((Any) . Boolean))
  17617. (vector? . ((Any) . Boolean))
  17618. (procedure? . ((Any) . Boolean))
  17619. (void? . ((Any) . Boolean)))
  17620. (super operator-types)))
  17621. (define/public (type-predicates)
  17622. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17623. (define/public (flat-ty? ty)
  17624. (match ty
  17625. [(or `Integer `Boolean `Void) #t]
  17626. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17627. [`(,ts ... -> ,rt)
  17628. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17629. [else #f]))
  17630. \end{lstlisting}
  17631. \end{tcolorbox}
  17632. \caption{Auxiliary methods for type checking \LangAny{}.}
  17633. \label{fig:type-check-Lany-aux}
  17634. \end{figure}
  17635. \fi}
  17636. \begin{figure}[btp]
  17637. \begin{tcolorbox}[colback=white]
  17638. {\if\edition\racketEd
  17639. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17640. (define interp-Lany-class
  17641. (class interp-Llambda-class
  17642. (super-new)
  17643. (define/override (interp-op op)
  17644. (match op
  17645. ['boolean? (match-lambda
  17646. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17647. [else #f])]
  17648. ['integer? (match-lambda
  17649. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17650. [else #f])]
  17651. ['vector? (match-lambda
  17652. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17653. [else #f])]
  17654. ['procedure? (match-lambda
  17655. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17656. [else #f])]
  17657. ['eq? (match-lambda*
  17658. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17659. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17660. [ls (apply (super interp-op op) ls)])]
  17661. ['any-vector-ref (lambda (v i)
  17662. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17663. ['any-vector-set! (lambda (v i a)
  17664. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17665. ['any-vector-length (lambda (v)
  17666. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17667. [else (super interp-op op)]))
  17668. (define/override ((interp-exp env) e)
  17669. (define recur (interp-exp env))
  17670. (match e
  17671. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17672. [(Project e ty2) (apply-project (recur e) ty2)]
  17673. [else ((super interp-exp env) e)]))
  17674. ))
  17675. (define (interp-Lany p)
  17676. (send (new interp-Lany-class) interp-program p))
  17677. \end{lstlisting}
  17678. \fi}
  17679. {\if\edition\pythonEd\pythonColor
  17680. \begin{lstlisting}
  17681. class InterpLany(InterpLlambda):
  17682. def interp_exp(self, e, env):
  17683. match e:
  17684. case Inject(value, typ):
  17685. v = self.interp_exp(value, env)
  17686. return Tagged(v, self.type_to_tag(typ))
  17687. case Project(value, typ):
  17688. v = self.interp_exp(value, env)
  17689. match v:
  17690. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17691. return val
  17692. case _:
  17693. raise Exception('interp project to ' + repr(typ)
  17694. + ' unexpected ' + repr(v))
  17695. case Call(Name('any_tuple_load'), [tup, index]):
  17696. tv = self.interp_exp(tup, env)
  17697. n = self.interp_exp(index, env)
  17698. match tv:
  17699. case Tagged(v, tag):
  17700. return v[n]
  17701. case _:
  17702. raise Exception('in any_tuple_load unexpected ' + repr(tv))
  17703. case Call(Name('any_len'), [value]):
  17704. v = self.interp_exp(value, env)
  17705. match v:
  17706. case Tagged(value, tag):
  17707. return len(value)
  17708. case _:
  17709. raise Exception('interp any_len unexpected ' + repr(v))
  17710. case Call(Name('arity'), [fun]):
  17711. f = self.interp_exp(fun, env)
  17712. return self.arity(f)
  17713. case _:
  17714. return super().interp_exp(e, env)
  17715. \end{lstlisting}
  17716. \fi}
  17717. \end{tcolorbox}
  17718. \caption{Interpreter for \LangAny{}.}
  17719. \label{fig:interp-Lany}
  17720. \end{figure}
  17721. \begin{figure}[tbp]
  17722. \begin{tcolorbox}[colback=white]
  17723. {\if\edition\racketEd
  17724. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17725. (define/public (apply-inject v tg) (Tagged v tg))
  17726. (define/public (apply-project v ty2)
  17727. (define tag2 (any-tag ty2))
  17728. (match v
  17729. [(Tagged v1 tag1)
  17730. (cond
  17731. [(eq? tag1 tag2)
  17732. (match ty2
  17733. [`(Vector ,ts ...)
  17734. (define l1 ((interp-op 'vector-length) v1))
  17735. (cond
  17736. [(eq? l1 (length ts)) v1]
  17737. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17738. l1 (length ts))])]
  17739. [`(,ts ... -> ,rt)
  17740. (match v1
  17741. [`(function ,xs ,body ,env)
  17742. (cond [(eq? (length xs) (length ts)) v1]
  17743. [else
  17744. (error 'apply-project "arity mismatch ~a != ~a"
  17745. (length xs) (length ts))])]
  17746. [else (error 'apply-project "expected function not ~a" v1)])]
  17747. [else v1])]
  17748. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17749. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17750. \end{lstlisting}
  17751. \fi}
  17752. {\if\edition\pythonEd\pythonColor
  17753. \begin{lstlisting}
  17754. class InterpLany(InterpLlambda):
  17755. def type_to_tag(self, typ):
  17756. match typ:
  17757. case FunctionType(params, rt):
  17758. return 'function'
  17759. case TupleType(fields):
  17760. return 'tuple'
  17761. case t if t == int:
  17762. return 'int'
  17763. case t if t == bool:
  17764. return 'bool'
  17765. case IntType():
  17766. return 'int'
  17767. case BoolType():
  17768. return 'int'
  17769. case _:
  17770. raise Exception('type_to_tag unexpected ' + repr(typ))
  17771. def arity(self, v):
  17772. match v:
  17773. case Function(name, params, body, env):
  17774. return len(params)
  17775. case ClosureTuple(args, arity):
  17776. return arity
  17777. case _:
  17778. raise Exception('Lany arity unexpected ' + repr(v))
  17779. \end{lstlisting}
  17780. \fi}
  17781. \end{tcolorbox}
  17782. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17783. \label{fig:interp-Lany-aux}
  17784. \end{figure}
  17785. \clearpage
  17786. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17787. \label{sec:compile-r7}
  17788. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17789. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17790. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17791. is that given any subexpression $e$ in the \LangDyn{} program, the
  17792. pass will produce an expression $e'$ in \LangAny{} that has type
  17793. \ANYTY{}. For example, the first row in
  17794. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17795. \TRUE{}, which must be injected to produce an expression of type
  17796. \ANYTY{}.
  17797. %
  17798. The compilation of addition is shown in the second row of
  17799. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17800. representative of many primitive operations: the arguments have type
  17801. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17802. be performed.
  17803. The compilation of \key{lambda} (third row of
  17804. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17805. produce type annotations: we simply use \ANYTY{}.
  17806. %
  17807. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17808. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17809. this pass has to account for some differences in behavior between
  17810. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17811. permissive than \LangAny{} regarding what kind of values can be used
  17812. in various places. For example, the condition of an \key{if} does
  17813. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17814. of the same type (in that case the result is \code{\#f}).}
  17815. \begin{figure}[btp]
  17816. \centering
  17817. \begin{tcolorbox}[colback=white]
  17818. {\if\edition\racketEd
  17819. \begin{tabular}{lll}
  17820. \begin{minipage}{0.27\textwidth}
  17821. \begin{lstlisting}
  17822. #t
  17823. \end{lstlisting}
  17824. \end{minipage}
  17825. &
  17826. $\Rightarrow$
  17827. &
  17828. \begin{minipage}{0.65\textwidth}
  17829. \begin{lstlisting}
  17830. (inject #t Boolean)
  17831. \end{lstlisting}
  17832. \end{minipage}
  17833. \\[2ex]\hline
  17834. \begin{minipage}{0.27\textwidth}
  17835. \begin{lstlisting}
  17836. (+ |$e_1$| |$e_2$|)
  17837. \end{lstlisting}
  17838. \end{minipage}
  17839. &
  17840. $\Rightarrow$
  17841. &
  17842. \begin{minipage}{0.65\textwidth}
  17843. \begin{lstlisting}
  17844. (inject
  17845. (+ (project |$e'_1$| Integer)
  17846. (project |$e'_2$| Integer))
  17847. Integer)
  17848. \end{lstlisting}
  17849. \end{minipage}
  17850. \\[2ex]\hline
  17851. \begin{minipage}{0.27\textwidth}
  17852. \begin{lstlisting}
  17853. (lambda (|$x_1 \ldots$|) |$e$|)
  17854. \end{lstlisting}
  17855. \end{minipage}
  17856. &
  17857. $\Rightarrow$
  17858. &
  17859. \begin{minipage}{0.65\textwidth}
  17860. \begin{lstlisting}
  17861. (inject
  17862. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17863. (Any|$\ldots$|Any -> Any))
  17864. \end{lstlisting}
  17865. \end{minipage}
  17866. \\[2ex]\hline
  17867. \begin{minipage}{0.27\textwidth}
  17868. \begin{lstlisting}
  17869. (|$e_0$| |$e_1 \ldots e_n$|)
  17870. \end{lstlisting}
  17871. \end{minipage}
  17872. &
  17873. $\Rightarrow$
  17874. &
  17875. \begin{minipage}{0.65\textwidth}
  17876. \begin{lstlisting}
  17877. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17878. \end{lstlisting}
  17879. \end{minipage}
  17880. \\[2ex]\hline
  17881. \begin{minipage}{0.27\textwidth}
  17882. \begin{lstlisting}
  17883. (vector-ref |$e_1$| |$e_2$|)
  17884. \end{lstlisting}
  17885. \end{minipage}
  17886. &
  17887. $\Rightarrow$
  17888. &
  17889. \begin{minipage}{0.65\textwidth}
  17890. \begin{lstlisting}
  17891. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17892. \end{lstlisting}
  17893. \end{minipage}
  17894. \\[2ex]\hline
  17895. \begin{minipage}{0.27\textwidth}
  17896. \begin{lstlisting}
  17897. (if |$e_1$| |$e_2$| |$e_3$|)
  17898. \end{lstlisting}
  17899. \end{minipage}
  17900. &
  17901. $\Rightarrow$
  17902. &
  17903. \begin{minipage}{0.65\textwidth}
  17904. \begin{lstlisting}
  17905. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17906. \end{lstlisting}
  17907. \end{minipage}
  17908. \\[2ex]\hline
  17909. \begin{minipage}{0.27\textwidth}
  17910. \begin{lstlisting}
  17911. (eq? |$e_1$| |$e_2$|)
  17912. \end{lstlisting}
  17913. \end{minipage}
  17914. &
  17915. $\Rightarrow$
  17916. &
  17917. \begin{minipage}{0.65\textwidth}
  17918. \begin{lstlisting}
  17919. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17920. \end{lstlisting}
  17921. \end{minipage}
  17922. \\[2ex]\hline
  17923. \begin{minipage}{0.27\textwidth}
  17924. \begin{lstlisting}
  17925. (not |$e_1$|)
  17926. \end{lstlisting}
  17927. \end{minipage}
  17928. &
  17929. $\Rightarrow$
  17930. &
  17931. \begin{minipage}{0.65\textwidth}
  17932. \begin{lstlisting}
  17933. (if (eq? |$e'_1$| (inject #f Boolean))
  17934. (inject #t Boolean) (inject #f Boolean))
  17935. \end{lstlisting}
  17936. \end{minipage}
  17937. \end{tabular}
  17938. \fi}
  17939. {\if\edition\pythonEd\pythonColor
  17940. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17941. \begin{minipage}{0.23\textwidth}
  17942. \begin{lstlisting}
  17943. True
  17944. \end{lstlisting}
  17945. \end{minipage}
  17946. &
  17947. $\Rightarrow$
  17948. &
  17949. \begin{minipage}{0.7\textwidth}
  17950. \begin{lstlisting}
  17951. Inject(True, BoolType())
  17952. \end{lstlisting}
  17953. \end{minipage}
  17954. \\[2ex]\hline
  17955. \begin{minipage}{0.23\textwidth}
  17956. \begin{lstlisting}
  17957. |$e_1$| + |$e_2$|
  17958. \end{lstlisting}
  17959. \end{minipage}
  17960. &
  17961. $\Rightarrow$
  17962. &
  17963. \begin{minipage}{0.7\textwidth}
  17964. \begin{lstlisting}
  17965. Inject(Project(|$e'_1$|, IntType())
  17966. + Project(|$e'_2$|, IntType()),
  17967. IntType())
  17968. \end{lstlisting}
  17969. \end{minipage}
  17970. \\[2ex]\hline
  17971. \begin{minipage}{0.23\textwidth}
  17972. \begin{lstlisting}
  17973. lambda |$x_1 \ldots$|: |$e$|
  17974. \end{lstlisting}
  17975. \end{minipage}
  17976. &
  17977. $\Rightarrow$
  17978. &
  17979. \begin{minipage}{0.7\textwidth}
  17980. \begin{lstlisting}
  17981. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17982. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17983. \end{lstlisting}
  17984. \end{minipage}
  17985. \\[2ex]\hline
  17986. \begin{minipage}{0.23\textwidth}
  17987. \begin{lstlisting}
  17988. |$e_0$|(|$e_1 \ldots e_n$|)
  17989. \end{lstlisting}
  17990. \end{minipage}
  17991. &
  17992. $\Rightarrow$
  17993. &
  17994. \begin{minipage}{0.7\textwidth}
  17995. \begin{lstlisting}
  17996. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17997. AnyType())), |$e'_1, \ldots, e'_n$|)
  17998. \end{lstlisting}
  17999. \end{minipage}
  18000. \\[2ex]\hline
  18001. \begin{minipage}{0.23\textwidth}
  18002. \begin{lstlisting}
  18003. |$e_1$|[|$e_2$|]
  18004. \end{lstlisting}
  18005. \end{minipage}
  18006. &
  18007. $\Rightarrow$
  18008. &
  18009. \begin{minipage}{0.7\textwidth}
  18010. \begin{lstlisting}
  18011. Call(Name('any_tuple_load'),
  18012. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18013. \end{lstlisting}
  18014. \end{minipage}
  18015. %% \begin{minipage}{0.23\textwidth}
  18016. %% \begin{lstlisting}
  18017. %% |$e_2$| if |$e_1$| else |$e_3$|
  18018. %% \end{lstlisting}
  18019. %% \end{minipage}
  18020. %% &
  18021. %% $\Rightarrow$
  18022. %% &
  18023. %% \begin{minipage}{0.7\textwidth}
  18024. %% \begin{lstlisting}
  18025. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18026. %% \end{lstlisting}
  18027. %% \end{minipage}
  18028. %% \\[2ex]\hline
  18029. %% \begin{minipage}{0.23\textwidth}
  18030. %% \begin{lstlisting}
  18031. %% (eq? |$e_1$| |$e_2$|)
  18032. %% \end{lstlisting}
  18033. %% \end{minipage}
  18034. %% &
  18035. %% $\Rightarrow$
  18036. %% &
  18037. %% \begin{minipage}{0.7\textwidth}
  18038. %% \begin{lstlisting}
  18039. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18040. %% \end{lstlisting}
  18041. %% \end{minipage}
  18042. %% \\[2ex]\hline
  18043. %% \begin{minipage}{0.23\textwidth}
  18044. %% \begin{lstlisting}
  18045. %% (not |$e_1$|)
  18046. %% \end{lstlisting}
  18047. %% \end{minipage}
  18048. %% &
  18049. %% $\Rightarrow$
  18050. %% &
  18051. %% \begin{minipage}{0.7\textwidth}
  18052. %% \begin{lstlisting}
  18053. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18054. %% (inject #t Boolean) (inject #f Boolean))
  18055. %% \end{lstlisting}
  18056. %% \end{minipage}
  18057. %% \\[2ex]\hline
  18058. \\\hline
  18059. \end{tabular}
  18060. \fi}
  18061. \end{tcolorbox}
  18062. \caption{Cast insertion.}
  18063. \label{fig:compile-r7-Lany}
  18064. \end{figure}
  18065. \section{Reveal Casts}
  18066. \label{sec:reveal-casts-Lany}
  18067. % TODO: define R'_6
  18068. In the \code{reveal\_casts} pass, we recommend compiling
  18069. \code{Project} into a conditional expression that checks whether the
  18070. value's tag matches the target type; if it does, the value is
  18071. converted to a value of the target type by removing the tag; if it
  18072. does not, the program exits.
  18073. %
  18074. {\if\edition\racketEd
  18075. %
  18076. To perform these actions we need a new primitive operation,
  18077. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18078. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18079. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18080. underlying value from a tagged value. The \code{ValueOf} form
  18081. includes the type for the underlying value that is used by the type
  18082. checker.
  18083. %
  18084. \fi}
  18085. %
  18086. {\if\edition\pythonEd\pythonColor
  18087. %
  18088. To perform these actions we need two new AST classes: \code{TagOf} and
  18089. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18090. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18091. the underlying value from a tagged value. The \code{ValueOf}
  18092. operation includes the type for the underlying value that is used by
  18093. the type checker.
  18094. %
  18095. \fi}
  18096. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18097. \code{Project} can be translated as follows:
  18098. \begin{center}
  18099. \begin{minipage}{1.0\textwidth}
  18100. {\if\edition\racketEd
  18101. \begin{lstlisting}
  18102. (Project |$e$| |$\FType$|)
  18103. |$\Rightarrow$|
  18104. (Let |$\itm{tmp}$| |$e'$|
  18105. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18106. (Int |$\itm{tagof}(\FType)$|)))
  18107. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18108. (Exit)))
  18109. \end{lstlisting}
  18110. \fi}
  18111. {\if\edition\pythonEd\pythonColor
  18112. \begin{lstlisting}
  18113. Project(|$e$|, |$\FType$|)
  18114. |$\Rightarrow$|
  18115. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18116. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18117. [Constant(|$\itm{tagof}(\FType)$|)]),
  18118. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18119. Call(Name('exit'), [])))
  18120. \end{lstlisting}
  18121. \fi}
  18122. \end{minipage}
  18123. \end{center}
  18124. If the target type of the projection is a tuple or function type, then
  18125. there is a bit more work to do. For tuples, check that the length of
  18126. the tuple type matches the length of the tuple. For functions, check
  18127. that the number of parameters in the function type matches the
  18128. function's arity.
  18129. Regarding \code{Inject}, we recommend compiling it to a slightly
  18130. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18131. takes a tag instead of a type.
  18132. \begin{center}
  18133. \begin{minipage}{1.0\textwidth}
  18134. {\if\edition\racketEd
  18135. \begin{lstlisting}
  18136. (Inject |$e$| |$\FType$|)
  18137. |$\Rightarrow$|
  18138. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18139. \end{lstlisting}
  18140. \fi}
  18141. {\if\edition\pythonEd\pythonColor
  18142. \begin{lstlisting}
  18143. Inject(|$e$|, |$\FType$|)
  18144. |$\Rightarrow$|
  18145. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18146. \end{lstlisting}
  18147. \fi}
  18148. \end{minipage}
  18149. \end{center}
  18150. {\if\edition\pythonEd\pythonColor
  18151. %
  18152. The introduction of \code{make\_any} makes it difficult to use
  18153. bidirectional type checking because we no longer have an expected type
  18154. to use for type checking the expression $e'$. Thus, we run into
  18155. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18156. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18157. annotated lambda), that contains its return type and the types of its
  18158. parameters.
  18159. %
  18160. \fi}
  18161. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18162. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18163. translation of \code{Project}.}
  18164. {\if\edition\racketEd
  18165. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18166. combine the projection action with the vector operation. Also, the
  18167. read and write operations allow arbitrary expressions for the index, so
  18168. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18169. cannot guarantee that the index is within bounds. Thus, we insert code
  18170. to perform bounds checking at runtime. The translation for
  18171. \code{any-vector-ref} is as follows, and the other two operations are
  18172. translated in a similar way:
  18173. \begin{center}
  18174. \begin{minipage}{0.95\textwidth}
  18175. \begin{lstlisting}
  18176. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18177. |$\Rightarrow$|
  18178. (Let |$v$| |$e'_1$|
  18179. (Let |$i$| |$e'_2$|
  18180. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18181. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18182. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18183. (Exit))
  18184. (Exit))))
  18185. \end{lstlisting}
  18186. \end{minipage}
  18187. \end{center}
  18188. \fi}
  18189. %
  18190. {\if\edition\pythonEd\pythonColor
  18191. %
  18192. The \code{any\_tuple\_load} operation combines the projection action
  18193. with the load operation. Also, the load operation allows arbitrary
  18194. expressions for the index so the type checker for \LangAny{}
  18195. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index, is
  18196. within bounds. Thus, we insert code to perform bounds checking at
  18197. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18198. \begin{lstlisting}
  18199. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18200. |$\Rightarrow$|
  18201. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18202. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18203. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18204. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18205. Call(Name('exit'), [])),
  18206. Call(Name('exit'), [])))
  18207. \end{lstlisting}
  18208. \fi}
  18209. {\if\edition\pythonEd\pythonColor
  18210. \section{Assignment Conversion}
  18211. \label{sec:convert-assignments-Lany}
  18212. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18213. \code{AnnLambda} AST classes.
  18214. \section{Closure Conversion}
  18215. \label{sec:closure-conversion-Lany}
  18216. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18217. \code{AnnLambda} AST classes.
  18218. \fi}
  18219. \section{Remove Complex Operands}
  18220. \label{sec:rco-Lany}
  18221. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18222. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18223. %
  18224. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18225. complex expressions. Their subexpressions must be atomic.}
  18226. \section{Explicate Control and \LangCAny{}}
  18227. \label{sec:explicate-Lany}
  18228. The output of \code{explicate\_control} is the \LangCAny{} language,
  18229. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18230. %
  18231. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18232. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18233. note that the index argument of \code{vector-ref} and
  18234. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18235. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18236. %
  18237. \python{Update the auxiliary functions \code{explicate\_tail},
  18238. \code{explicate\_effect}, and \code{explicate\_pred} as
  18239. appropriate to handle the new expressions in \LangCAny{}. }
  18240. \newcommand{\CanyASTPython}{
  18241. \begin{array}{lcl}
  18242. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18243. &\MID& \key{TagOf}\LP \Atm \RP
  18244. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18245. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18246. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18247. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18248. \end{array}
  18249. }
  18250. \newcommand{\CanyASTRacket}{
  18251. \begin{array}{lcl}
  18252. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18253. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18254. &\MID& \VALUEOF{\Atm}{\FType} \\
  18255. \Tail &::= & \LP\key{Exit}\RP
  18256. \end{array}
  18257. }
  18258. \begin{figure}[tp]
  18259. \begin{tcolorbox}[colback=white]
  18260. \small
  18261. {\if\edition\racketEd
  18262. \[
  18263. \begin{array}{l}
  18264. \gray{\CvarASTRacket} \\ \hline
  18265. \gray{\CifASTRacket} \\ \hline
  18266. \gray{\CloopASTRacket} \\ \hline
  18267. \gray{\CtupASTRacket} \\ \hline
  18268. \gray{\CfunASTRacket} \\ \hline
  18269. \gray{\ClambdaASTRacket} \\ \hline
  18270. \CanyASTRacket \\
  18271. \begin{array}{lcl}
  18272. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18273. \end{array}
  18274. \end{array}
  18275. \]
  18276. \fi}
  18277. {\if\edition\pythonEd\pythonColor
  18278. \[
  18279. \begin{array}{l}
  18280. \gray{\CifASTPython} \\ \hline
  18281. \gray{\CtupASTPython} \\ \hline
  18282. \gray{\CfunASTPython} \\ \hline
  18283. \gray{\ClambdaASTPython} \\ \hline
  18284. \CanyASTPython \\
  18285. \begin{array}{lcl}
  18286. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18287. \end{array}
  18288. \end{array}
  18289. \]
  18290. \fi}
  18291. \end{tcolorbox}
  18292. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18293. \label{fig:c5-syntax}
  18294. \end{figure}
  18295. \section{Select Instructions}
  18296. \label{sec:select-Lany}
  18297. \index{subject}{select instructions}
  18298. In the \code{select\_instructions} pass, we translate the primitive
  18299. operations on the \ANYTY{} type to x86 instructions that manipulate
  18300. the three tag bits of the tagged value. In the following descriptions,
  18301. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18302. of translating $e$ into an x86 argument:
  18303. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18304. We recommend compiling the
  18305. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18306. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18307. shifts the destination to the left by the number of bits specified by its
  18308. source argument (in this case three, the length of the tag), and it
  18309. preserves the sign of the integer. We use the \key{orq} instruction to
  18310. combine the tag and the value to form the tagged value.
  18311. {\if\edition\racketEd
  18312. \begin{lstlisting}
  18313. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18314. |$\Rightarrow$|
  18315. movq |$e'$|, |\itm{lhs'}|
  18316. salq $3, |\itm{lhs'}|
  18317. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18318. \end{lstlisting}
  18319. \fi}
  18320. %
  18321. {\if\edition\pythonEd\pythonColor
  18322. \begin{lstlisting}
  18323. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18324. |$\Rightarrow$|
  18325. movq |$e'$|, |\itm{lhs'}|
  18326. salq $3, |\itm{lhs'}|
  18327. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18328. \end{lstlisting}
  18329. \fi}
  18330. %
  18331. The instruction selection\index{subject}{instruction selection} for
  18332. tuples and procedures is different because there is no need to shift
  18333. them to the left. The rightmost 3 bits are already zeros, so we simply
  18334. combine the value and the tag using \key{orq}. \\
  18335. %
  18336. {\if\edition\racketEd
  18337. \begin{center}
  18338. \begin{minipage}{\textwidth}
  18339. \begin{lstlisting}
  18340. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18341. |$\Rightarrow$|
  18342. movq |$e'$|, |\itm{lhs'}|
  18343. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18344. \end{lstlisting}
  18345. \end{minipage}
  18346. \end{center}
  18347. \fi}
  18348. %
  18349. {\if\edition\pythonEd\pythonColor
  18350. \begin{lstlisting}
  18351. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18352. |$\Rightarrow$|
  18353. movq |$e'$|, |\itm{lhs'}|
  18354. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18355. \end{lstlisting}
  18356. \fi}
  18357. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18358. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18359. operation extracts the type tag from a value of type \ANYTY{}. The
  18360. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18361. bitwise-and of the value with $111$ ($7$ decimal).
  18362. %
  18363. {\if\edition\racketEd
  18364. \begin{lstlisting}
  18365. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18366. |$\Rightarrow$|
  18367. movq |$e'$|, |\itm{lhs'}|
  18368. andq $7, |\itm{lhs'}|
  18369. \end{lstlisting}
  18370. \fi}
  18371. %
  18372. {\if\edition\pythonEd\pythonColor
  18373. \begin{lstlisting}
  18374. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18375. |$\Rightarrow$|
  18376. movq |$e'$|, |\itm{lhs'}|
  18377. andq $7, |\itm{lhs'}|
  18378. \end{lstlisting}
  18379. \fi}
  18380. \paragraph{\code{ValueOf}}
  18381. The instructions for \key{ValueOf} also differ, depending on whether
  18382. the type $T$ is a pointer (tuple or function) or not (integer or
  18383. Boolean). The following shows the instruction
  18384. selection for integers and
  18385. Booleans, in which we produce an untagged value by shifting it to the
  18386. right by 3 bits:
  18387. %
  18388. {\if\edition\racketEd
  18389. \begin{lstlisting}
  18390. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18391. |$\Rightarrow$|
  18392. movq |$e'$|, |\itm{lhs'}|
  18393. sarq $3, |\itm{lhs'}|
  18394. \end{lstlisting}
  18395. \fi}
  18396. %
  18397. {\if\edition\pythonEd\pythonColor
  18398. \begin{lstlisting}
  18399. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18400. |$\Rightarrow$|
  18401. movq |$e'$|, |\itm{lhs'}|
  18402. sarq $3, |\itm{lhs'}|
  18403. \end{lstlisting}
  18404. \fi}
  18405. %
  18406. In the case for tuples and procedures, we zero out the rightmost 3
  18407. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18408. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18409. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18410. Finally, we apply \code{andq} with the tagged value to get the desired
  18411. result.
  18412. %
  18413. {\if\edition\racketEd
  18414. \begin{lstlisting}
  18415. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18416. |$\Rightarrow$|
  18417. movq $|$-8$|, |\itm{lhs'}|
  18418. andq |$e'$|, |\itm{lhs'}|
  18419. \end{lstlisting}
  18420. \fi}
  18421. %
  18422. {\if\edition\pythonEd\pythonColor
  18423. \begin{lstlisting}
  18424. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18425. |$\Rightarrow$|
  18426. movq $|$-8$|, |\itm{lhs'}|
  18427. andq |$e'$|, |\itm{lhs'}|
  18428. \end{lstlisting}
  18429. \fi}
  18430. %% \paragraph{Type Predicates} We leave it to the reader to
  18431. %% devise a sequence of instructions to implement the type predicates
  18432. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18433. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18434. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18435. operation combines the effect of \code{ValueOf} with accessing the
  18436. length of a tuple from the tag stored at the zero index of the tuple.
  18437. {\if\edition\racketEd
  18438. \begin{lstlisting}
  18439. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18440. |$\Longrightarrow$|
  18441. movq $|$-8$|, %r11
  18442. andq |$e_1'$|, %r11
  18443. movq 0(%r11), %r11
  18444. andq $126, %r11
  18445. sarq $1, %r11
  18446. movq %r11, |$\itm{lhs'}$|
  18447. \end{lstlisting}
  18448. \fi}
  18449. {\if\edition\pythonEd\pythonColor
  18450. \begin{lstlisting}
  18451. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18452. |$\Longrightarrow$|
  18453. movq $|$-8$|, %r11
  18454. andq |$e_1'$|, %r11
  18455. movq 0(%r11), %r11
  18456. andq $126, %r11
  18457. sarq $1, %r11
  18458. movq %r11, |$\itm{lhs'}$|
  18459. \end{lstlisting}
  18460. \fi}
  18461. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18462. This operation combines the effect of \code{ValueOf} with reading an
  18463. element of the tuple (see
  18464. section~\ref{sec:select-instructions-gc}). However, the index may be
  18465. an arbitrary atom, so instead of computing the offset at compile time,
  18466. we must generate instructions to compute the offset at runtime as
  18467. follows. Note the use of the new instruction \code{imulq}.
  18468. \begin{center}
  18469. \begin{minipage}{0.96\textwidth}
  18470. {\if\edition\racketEd
  18471. \begin{lstlisting}
  18472. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18473. |$\Longrightarrow$|
  18474. movq |$\neg 111$|, %r11
  18475. andq |$e_1'$|, %r11
  18476. movq |$e_2'$|, %rax
  18477. addq $1, %rax
  18478. imulq $8, %rax
  18479. addq %rax, %r11
  18480. movq 0(%r11) |$\itm{lhs'}$|
  18481. \end{lstlisting}
  18482. \fi}
  18483. %
  18484. {\if\edition\pythonEd\pythonColor
  18485. \begin{lstlisting}
  18486. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18487. |$\Longrightarrow$|
  18488. movq $|$-8$|, %r11
  18489. andq |$e_1'$|, %r11
  18490. movq |$e_2'$|, %rax
  18491. addq $1, %rax
  18492. imulq $8, %rax
  18493. addq %rax, %r11
  18494. movq 0(%r11) |$\itm{lhs'}$|
  18495. \end{lstlisting}
  18496. \fi}
  18497. \end{minipage}
  18498. \end{center}
  18499. % $ pacify font lock
  18500. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18501. %% The code generation for
  18502. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18503. %% analogous to the above translation for reading from a tuple.
  18504. \section{Register Allocation for \LangAny{}}
  18505. \label{sec:register-allocation-Lany}
  18506. \index{subject}{register allocation}
  18507. There is an interesting interaction between tagged values and garbage
  18508. collection that has an impact on register allocation. A variable of
  18509. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18510. that needs to be inspected and copied during garbage collection. Thus,
  18511. we need to treat variables of type \ANYTY{} in a similar way to
  18512. variables of tuple type for purposes of register allocation,
  18513. with particular attention to the following:
  18514. \begin{itemize}
  18515. \item If a variable of type \ANYTY{} is live during a function call,
  18516. then it must be spilled. This can be accomplished by changing
  18517. \code{build\_interference} to mark all variables of type \ANYTY{}
  18518. that are live after a \code{callq} to be interfering with all the
  18519. registers.
  18520. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18521. the root stack instead of the normal procedure call stack.
  18522. \end{itemize}
  18523. Another concern regarding the root stack is that the garbage collector
  18524. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18525. tagged value that points to a tuple, and (3) a tagged value that is
  18526. not a tuple. We enable this differentiation by choosing not to use the
  18527. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18528. reserved for identifying plain old pointers to tuples. That way, if
  18529. one of the first three bits is set, then we have a tagged value and
  18530. inspecting the tag can differentiate between tuples ($010$) and the
  18531. other kinds of values.
  18532. %% \begin{exercise}\normalfont
  18533. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18534. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18535. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18536. %% compiler on these new programs and all of your previously created test
  18537. %% programs.
  18538. %% \end{exercise}
  18539. \begin{exercise}\normalfont\normalsize
  18540. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18541. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18542. by removing type annotations. Add five more test programs that
  18543. specifically rely on the language being dynamically typed. That is,
  18544. they should not be legal programs in a statically typed language, but
  18545. nevertheless they should be valid \LangDyn{} programs that run to
  18546. completion without error.
  18547. \end{exercise}
  18548. \begin{figure}[p]
  18549. \begin{tcolorbox}[colback=white]
  18550. {\if\edition\racketEd
  18551. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18552. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18553. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18554. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18555. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18556. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18557. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18558. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18559. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18560. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18561. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18562. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18563. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18564. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18565. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18566. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18567. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18568. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18569. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18570. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18571. \path[->,bend left=15] (Lfun) edge [above] node
  18572. {\ttfamily\footnotesize shrink} (Lfun-2);
  18573. \path[->,bend left=15] (Lfun-2) edge [above] node
  18574. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18575. \path[->,bend left=15] (Lfun-3) edge [above] node
  18576. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18577. \path[->,bend left=15] (Lfun-4) edge [left] node
  18578. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18579. \path[->,bend left=15] (Lfun-5) edge [below] node
  18580. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18581. \path[->,bend left=15] (Lfun-6) edge [below] node
  18582. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18583. \path[->,bend right=15] (Lfun-7) edge [above] node
  18584. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18585. \path[->,bend right=15] (F1-2) edge [right] node
  18586. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18587. \path[->,bend right=15] (F1-3) edge [below] node
  18588. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18589. \path[->,bend right=15] (F1-4) edge [below] node
  18590. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18591. \path[->,bend left=15] (F1-5) edge [above] node
  18592. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18593. \path[->,bend left=10] (F1-6) edge [below] node
  18594. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18595. \path[->,bend left=15] (C3-2) edge [right] node
  18596. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18597. \path[->,bend right=15] (x86-2) edge [right] node
  18598. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18599. \path[->,bend right=15] (x86-2-1) edge [below] node
  18600. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18601. \path[->,bend right=15] (x86-2-2) edge [right] node
  18602. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18603. \path[->,bend left=15] (x86-3) edge [above] node
  18604. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18605. \path[->,bend left=15] (x86-4) edge [right] node
  18606. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18607. \end{tikzpicture}
  18608. \fi}
  18609. {\if\edition\pythonEd\pythonColor
  18610. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18611. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18612. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18613. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18614. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18615. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18616. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18617. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18618. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18619. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18620. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18621. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18622. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18623. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18624. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18625. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18626. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18627. \path[->,bend left=15] (Lfun) edge [above] node
  18628. {\ttfamily\footnotesize shrink} (Lfun-2);
  18629. \path[->,bend left=15] (Lfun-2) edge [above] node
  18630. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18631. \path[->,bend left=15] (Lfun-3) edge [above] node
  18632. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18633. \path[->,bend left=15] (Lfun-4) edge [left] node
  18634. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18635. \path[->,bend left=15] (Lfun-5) edge [below] node
  18636. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18637. \path[->,bend right=15] (Lfun-6) edge [above] node
  18638. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18639. \path[->,bend right=15] (Lfun-7) edge [above] node
  18640. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18641. \path[->,bend right=15] (F1-2) edge [right] node
  18642. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18643. \path[->,bend right=15] (F1-3) edge [below] node
  18644. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18645. \path[->,bend left=15] (F1-5) edge [above] node
  18646. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18647. \path[->,bend left=10] (F1-6) edge [below] node
  18648. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18649. \path[->,bend right=15] (C3-2) edge [right] node
  18650. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18651. \path[->,bend right=15] (x86-2) edge [below] node
  18652. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18653. \path[->,bend right=15] (x86-3) edge [below] node
  18654. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18655. \path[->,bend left=15] (x86-4) edge [above] node
  18656. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18657. \end{tikzpicture}
  18658. \fi}
  18659. \end{tcolorbox}
  18660. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18661. \label{fig:Ldyn-passes}
  18662. \end{figure}
  18663. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18664. for the compilation of \LangDyn{}.
  18665. % Further Reading
  18666. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18667. %% {\if\edition\pythonEd\pythonColor
  18668. %% \chapter{Objects}
  18669. %% \label{ch:Lobject}
  18670. %% \index{subject}{objects}
  18671. %% \index{subject}{classes}
  18672. %% \setcounter{footnote}{0}
  18673. %% \fi}
  18674. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18675. \chapter{Gradual Typing}
  18676. \label{ch:Lgrad}
  18677. \index{subject}{gradual typing}
  18678. \setcounter{footnote}{0}
  18679. This chapter studies the language \LangGrad{}, in which the programmer
  18680. can choose between static and dynamic type checking in different parts
  18681. of a program, thereby mixing the statically typed \LangLam{} language
  18682. with the dynamically typed \LangDyn{}. There are several approaches to
  18683. mixing static and dynamic typing, including multilanguage
  18684. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18685. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18686. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18687. programmer controls the amount of static versus dynamic checking by
  18688. adding or removing type annotations on parameters and
  18689. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18690. The definition of the concrete syntax of \LangGrad{} is shown in
  18691. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18692. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18693. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18694. annotations are optional, which is specified in the grammar using the
  18695. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18696. annotations are not optional, but we use the \CANYTY{} type when a type
  18697. annotation is absent.
  18698. %
  18699. Both the type checker and the interpreter for \LangGrad{} require some
  18700. interesting changes to enable gradual typing, which we discuss in the
  18701. next two sections.
  18702. \newcommand{\LgradGrammarRacket}{
  18703. \begin{array}{lcl}
  18704. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18705. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18706. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18707. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18708. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18709. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18710. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18711. \end{array}
  18712. }
  18713. \newcommand{\LgradASTRacket}{
  18714. \begin{array}{lcl}
  18715. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18716. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18717. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18718. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18719. \itm{op} &::=& \code{procedure-arity} \\
  18720. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18721. \end{array}
  18722. }
  18723. \newcommand{\LgradGrammarPython}{
  18724. \begin{array}{lcl}
  18725. \Type &::=& \key{Any}
  18726. \MID \key{int}
  18727. \MID \key{bool}
  18728. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18729. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18730. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18731. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18732. \MID \CARITY{\Exp} \\
  18733. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18734. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18735. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18736. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18737. \end{array}
  18738. }
  18739. \newcommand{\LgradASTPython}{
  18740. \begin{array}{lcl}
  18741. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18742. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18743. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18744. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18745. &\MID& \ARITY{\Exp} \\
  18746. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18747. \MID \RETURN{\Exp} \\
  18748. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18749. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18750. \end{array}
  18751. }
  18752. \begin{figure}[tp]
  18753. \centering
  18754. \begin{tcolorbox}[colback=white]
  18755. \small
  18756. {\if\edition\racketEd
  18757. \[
  18758. \begin{array}{l}
  18759. \gray{\LintGrammarRacket{}} \\ \hline
  18760. \gray{\LvarGrammarRacket{}} \\ \hline
  18761. \gray{\LifGrammarRacket{}} \\ \hline
  18762. \gray{\LwhileGrammarRacket} \\ \hline
  18763. \gray{\LtupGrammarRacket} \\ \hline
  18764. \LgradGrammarRacket \\
  18765. \begin{array}{lcl}
  18766. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18767. \end{array}
  18768. \end{array}
  18769. \]
  18770. \fi}
  18771. {\if\edition\pythonEd\pythonColor
  18772. \[
  18773. \begin{array}{l}
  18774. \gray{\LintGrammarPython{}} \\ \hline
  18775. \gray{\LvarGrammarPython{}} \\ \hline
  18776. \gray{\LifGrammarPython{}} \\ \hline
  18777. \gray{\LwhileGrammarPython} \\ \hline
  18778. \gray{\LtupGrammarPython} \\ \hline
  18779. \LgradGrammarPython \\
  18780. \begin{array}{lcl}
  18781. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18782. \end{array}
  18783. \end{array}
  18784. \]
  18785. \fi}
  18786. \end{tcolorbox}
  18787. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18788. \label{fig:Lgrad-concrete-syntax}
  18789. \end{figure}
  18790. \begin{figure}[tp]
  18791. \centering
  18792. \begin{tcolorbox}[colback=white]
  18793. \small
  18794. {\if\edition\racketEd
  18795. \[
  18796. \begin{array}{l}
  18797. \gray{\LintOpAST} \\ \hline
  18798. \gray{\LvarASTRacket{}} \\ \hline
  18799. \gray{\LifASTRacket{}} \\ \hline
  18800. \gray{\LwhileASTRacket{}} \\ \hline
  18801. \gray{\LtupASTRacket{}} \\ \hline
  18802. \LgradASTRacket \\
  18803. \begin{array}{lcl}
  18804. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18805. \end{array}
  18806. \end{array}
  18807. \]
  18808. \fi}
  18809. {\if\edition\pythonEd\pythonColor
  18810. \[
  18811. \begin{array}{l}
  18812. \gray{\LintASTPython{}} \\ \hline
  18813. \gray{\LvarASTPython{}} \\ \hline
  18814. \gray{\LifASTPython{}} \\ \hline
  18815. \gray{\LwhileASTPython} \\ \hline
  18816. \gray{\LtupASTPython} \\ \hline
  18817. \LgradASTPython \\
  18818. \begin{array}{lcl}
  18819. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18820. \end{array}
  18821. \end{array}
  18822. \]
  18823. \fi}
  18824. \end{tcolorbox}
  18825. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18826. \label{fig:Lgrad-syntax}
  18827. \end{figure}
  18828. % TODO: more road map -Jeremy
  18829. %\clearpage
  18830. \section{Type Checking \LangGrad{}}
  18831. \label{sec:gradual-type-check}
  18832. We begin by discussing the type checking of a partially typed variant
  18833. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18834. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18835. statically typed, so there is nothing special happening there with
  18836. respect to type checking. On the other hand, the \code{inc} function
  18837. does not have type annotations, so the type checker assigns the type
  18838. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18839. \code{+} operator inside \code{inc}. It expects both arguments to have
  18840. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18841. a gradually typed language, such differences are allowed so long as
  18842. the types are \emph{consistent}; that is, they are equal except in
  18843. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18844. is consistent with every other type. Figure~\ref{fig:consistent}
  18845. shows the definition of the
  18846. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18847. %
  18848. So the type checker allows the \code{+} operator to be applied
  18849. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18850. %
  18851. Next consider the call to the \code{map} function shown in
  18852. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18853. tuple. The \code{inc} function has type
  18854. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18855. but parameter \code{f} of \code{map} has type
  18856. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18857. The type checker for \LangGrad{} accepts this call because the two types are
  18858. consistent.
  18859. \begin{figure}[btp]
  18860. % gradual_test_9.rkt
  18861. \begin{tcolorbox}[colback=white]
  18862. {\if\edition\racketEd
  18863. \begin{lstlisting}
  18864. (define (map [f : (Integer -> Integer)]
  18865. [v : (Vector Integer Integer)])
  18866. : (Vector Integer Integer)
  18867. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18868. (define (inc x) (+ x 1))
  18869. (vector-ref (map inc (vector 0 41)) 1)
  18870. \end{lstlisting}
  18871. \fi}
  18872. {\if\edition\pythonEd\pythonColor
  18873. \begin{lstlisting}
  18874. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18875. return f(v[0]), f(v[1])
  18876. def inc(x):
  18877. return x + 1
  18878. t = map(inc, (0, 41))
  18879. print(t[1])
  18880. \end{lstlisting}
  18881. \fi}
  18882. \end{tcolorbox}
  18883. \caption{A partially typed version of the \code{map} example.}
  18884. \label{fig:gradual-map}
  18885. \end{figure}
  18886. \begin{figure}[tbp]
  18887. \begin{tcolorbox}[colback=white]
  18888. {\if\edition\racketEd
  18889. \begin{lstlisting}
  18890. (define/public (consistent? t1 t2)
  18891. (match* (t1 t2)
  18892. [('Integer 'Integer) #t]
  18893. [('Boolean 'Boolean) #t]
  18894. [('Void 'Void) #t]
  18895. [('Any t2) #t]
  18896. [(t1 'Any) #t]
  18897. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18898. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18899. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18900. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18901. (consistent? rt1 rt2))]
  18902. [(other wise) #f]))
  18903. \end{lstlisting}
  18904. \fi}
  18905. {\if\edition\pythonEd\pythonColor
  18906. \begin{lstlisting}
  18907. def consistent(self, t1, t2):
  18908. match (t1, t2):
  18909. case (AnyType(), _):
  18910. return True
  18911. case (_, AnyType()):
  18912. return True
  18913. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18914. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18915. case (TupleType(ts1), TupleType(ts2)):
  18916. return all(map(self.consistent, ts1, ts2))
  18917. case (_, _):
  18918. return t1 == t2
  18919. \end{lstlisting}
  18920. \fi}
  18921. \end{tcolorbox}
  18922. \caption{The consistency method on types.}
  18923. \label{fig:consistent}
  18924. \end{figure}
  18925. It is also helpful to consider how gradual typing handles programs with an
  18926. error, such as applying \code{map} to a function that sometimes
  18927. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18928. type checker for \LangGrad{} accepts this program because the type of
  18929. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18930. \code{map}; that is,
  18931. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18932. is consistent with
  18933. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18934. One might say that a gradual type checker is optimistic in that it
  18935. accepts programs that might execute without a runtime type error.
  18936. %
  18937. The definition of the type checker for \LangGrad{} is shown in
  18938. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18939. and \ref{fig:type-check-Lgradual-3}.
  18940. %% \begin{figure}[tp]
  18941. %% \centering
  18942. %% \fbox{
  18943. %% \begin{minipage}{0.96\textwidth}
  18944. %% \small
  18945. %% \[
  18946. %% \begin{array}{lcl}
  18947. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18948. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18949. %% \end{array}
  18950. %% \]
  18951. %% \end{minipage}
  18952. %% }
  18953. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18954. %% \label{fig:Lgrad-prime-syntax}
  18955. %% \end{figure}
  18956. \begin{figure}[tbp]
  18957. \begin{tcolorbox}[colback=white]
  18958. {\if\edition\racketEd
  18959. \begin{lstlisting}
  18960. (define (map [f : (Integer -> Integer)]
  18961. [v : (Vector Integer Integer)])
  18962. : (Vector Integer Integer)
  18963. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18964. (define (inc x) (+ x 1))
  18965. (define (true) #t)
  18966. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18967. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18968. \end{lstlisting}
  18969. \fi}
  18970. {\if\edition\pythonEd\pythonColor
  18971. \begin{lstlisting}
  18972. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18973. return f(v[0]), f(v[1])
  18974. def inc(x):
  18975. return x + 1
  18976. def true():
  18977. return True
  18978. def maybe_inc(x):
  18979. return inc(x) if input_int() == 0 else true()
  18980. t = map(maybe_inc, (0, 41))
  18981. print(t[1])
  18982. \end{lstlisting}
  18983. \fi}
  18984. \end{tcolorbox}
  18985. \caption{A variant of the \code{map} example with an error.}
  18986. \label{fig:map-maybe_inc}
  18987. \end{figure}
  18988. Running this program with input \code{1} triggers an
  18989. error when the \code{maybe\_inc} function returns
  18990. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18991. performs checking at runtime to ensure the integrity of the static
  18992. types, such as the
  18993. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18994. annotation on
  18995. parameter \code{f} of \code{map}.
  18996. Here we give a preview of how the runtime checking is accomplished;
  18997. the following sections provide the details.
  18998. The runtime checking is carried out by a new \code{Cast} AST node that
  18999. is generated in a new pass named \code{cast\_insert}. The output of
  19000. \code{cast\_insert} is a program in the \LangCast{} language, which
  19001. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19002. %
  19003. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19004. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19005. inserted every time the type checker encounters two types that are
  19006. consistent but not equal. In the \code{inc} function, \code{x} is
  19007. cast to \INTTY{} and the result of the \code{+} is cast to
  19008. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19009. is cast from
  19010. \racket{\code{(Any -> Any)}}
  19011. \python{\code{Callable[[Any], Any]}}
  19012. to
  19013. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19014. %
  19015. In the next section we see how to interpret the \code{Cast} node.
  19016. \begin{figure}[btp]
  19017. \begin{tcolorbox}[colback=white]
  19018. {\if\edition\racketEd
  19019. \begin{lstlisting}
  19020. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19021. : (Vector Integer Integer)
  19022. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19023. (define (inc [x : Any]) : Any
  19024. (cast (+ (cast x Any Integer) 1) Integer Any))
  19025. (define (true) : Any (cast #t Boolean Any))
  19026. (define (maybe_inc [x : Any]) : Any
  19027. (if (eq? 0 (read)) (inc x) (true)))
  19028. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19029. (vector 0 41)) 0)
  19030. \end{lstlisting}
  19031. \fi}
  19032. {\if\edition\pythonEd\pythonColor
  19033. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19034. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19035. return f(v[0]), f(v[1])
  19036. def inc(x : Any) -> Any:
  19037. return Cast(Cast(x, Any, int) + 1, int, Any)
  19038. def true() -> Any:
  19039. return Cast(True, bool, Any)
  19040. def maybe_inc(x : Any) -> Any:
  19041. return inc(x) if input_int() == 0 else true()
  19042. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19043. (0, 41))
  19044. print(t[1])
  19045. \end{lstlisting}
  19046. \fi}
  19047. \end{tcolorbox}
  19048. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19049. and \code{maybe\_inc} example.}
  19050. \label{fig:map-cast}
  19051. \end{figure}
  19052. {\if\edition\pythonEd\pythonColor
  19053. \begin{figure}[tbp]
  19054. \begin{tcolorbox}[colback=white]
  19055. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19056. class TypeCheckLgrad(TypeCheckLlambda):
  19057. def type_check_exp(self, e, env) -> Type:
  19058. match e:
  19059. case Name(id):
  19060. return env[id]
  19061. case Constant(value) if isinstance(value, bool):
  19062. return BoolType()
  19063. case Constant(value) if isinstance(value, int):
  19064. return IntType()
  19065. case Call(Name('input_int'), []):
  19066. return IntType()
  19067. case BinOp(left, op, right):
  19068. left_type = self.type_check_exp(left, env)
  19069. self.check_consistent(left_type, IntType(), left)
  19070. right_type = self.type_check_exp(right, env)
  19071. self.check_consistent(right_type, IntType(), right)
  19072. return IntType()
  19073. case IfExp(test, body, orelse):
  19074. test_t = self.type_check_exp(test, env)
  19075. self.check_consistent(test_t, BoolType(), test)
  19076. body_t = self.type_check_exp(body, env)
  19077. orelse_t = self.type_check_exp(orelse, env)
  19078. self.check_consistent(body_t, orelse_t, e)
  19079. return self.join_types(body_t, orelse_t)
  19080. case Call(func, args):
  19081. func_t = self.type_check_exp(func, env)
  19082. args_t = [self.type_check_exp(arg, env) for arg in args]
  19083. match func_t:
  19084. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  19085. for (arg_t, param_t) in zip(args_t, params_t):
  19086. self.check_consistent(param_t, arg_t, e)
  19087. return return_t
  19088. case AnyType():
  19089. return AnyType()
  19090. case _:
  19091. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  19092. ...
  19093. case _:
  19094. raise Exception('type_check_exp: unexpected ' + repr(e))
  19095. \end{lstlisting}
  19096. \end{tcolorbox}
  19097. \caption{Type checking expressions in the \LangGrad{} language.}
  19098. \label{fig:type-check-Lgradual-1}
  19099. \end{figure}
  19100. \begin{figure}[tbp]
  19101. \begin{tcolorbox}[colback=white]
  19102. \begin{lstlisting}
  19103. def check_exp(self, e, expected_ty, env):
  19104. match e:
  19105. case Lambda(params, body):
  19106. match expected_ty:
  19107. case FunctionType(params_t, return_t):
  19108. new_env = env.copy().update(zip(params, params_t))
  19109. e.has_type = expected_ty
  19110. body_ty = self.type_check_exp(body, new_env)
  19111. self.check_consistent(body_ty, return_t)
  19112. case AnyType():
  19113. new_env = env.copy().update((p, AnyType()) for p in params)
  19114. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19115. body_ty = self.type_check_exp(body, new_env)
  19116. case _:
  19117. raise Exception('lambda is not of type ' + str(expected_ty))
  19118. case _:
  19119. e_ty = self.type_check_exp(e, env)
  19120. self.check_consistent(e_ty, expected_ty, e)
  19121. \end{lstlisting}
  19122. \end{tcolorbox}
  19123. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19124. \label{fig:type-check-Lgradual-2}
  19125. \end{figure}
  19126. \begin{figure}[tbp]
  19127. \begin{tcolorbox}[colback=white]
  19128. \begin{lstlisting}
  19129. def type_check_stmt(self, s, env, return_type):
  19130. match s:
  19131. case Assign([Name(id)], value):
  19132. value_ty = self.type_check_exp(value, env)
  19133. if id in env:
  19134. self.check_consistent(env[id], value_ty, value)
  19135. else:
  19136. env[id] = value_ty
  19137. ...
  19138. case _:
  19139. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19140. def type_check_stmts(self, ss, env, return_type):
  19141. for s in ss:
  19142. self.type_check_stmt(s, env, return_type)
  19143. \end{lstlisting}
  19144. \end{tcolorbox}
  19145. \caption{Type checking statements in the \LangGrad{} language.}
  19146. \label{fig:type-check-Lgradual-3}
  19147. \end{figure}
  19148. \begin{figure}[tbp]
  19149. \begin{tcolorbox}[colback=white]
  19150. \begin{lstlisting}
  19151. def join_types(self, t1, t2):
  19152. match (t1, t2):
  19153. case (AnyType(), _):
  19154. return t2
  19155. case (_, AnyType()):
  19156. return t1
  19157. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19158. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19159. self.join_types(rt1,rt2))
  19160. case (TupleType(ts1), TupleType(ts2)):
  19161. return TupleType(list(map(self.join_types, ts1, ts2)))
  19162. case (_, _):
  19163. return t1
  19164. def check_consistent(self, t1, t2, e):
  19165. if not self.consistent(t1, t2):
  19166. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19167. + repr(t2) + ' in ' + repr(e))
  19168. \end{lstlisting}
  19169. \end{tcolorbox}
  19170. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19171. \label{fig:type-check-Lgradual-aux}
  19172. \end{figure}
  19173. \fi}
  19174. {\if\edition\racketEd
  19175. \begin{figure}[tbp]
  19176. \begin{tcolorbox}[colback=white]
  19177. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19178. (define/override (type-check-exp env)
  19179. (lambda (e)
  19180. (define recur (type-check-exp env))
  19181. (match e
  19182. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19183. (define-values (new-es ts)
  19184. (for/lists (exprs types) ([e es])
  19185. (recur e)))
  19186. (define t-ret (type-check-op op ts e))
  19187. (values (Prim op new-es) t-ret)]
  19188. [(Prim 'eq? (list e1 e2))
  19189. (define-values (e1^ t1) (recur e1))
  19190. (define-values (e2^ t2) (recur e2))
  19191. (check-consistent? t1 t2 e)
  19192. (define T (meet t1 t2))
  19193. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19194. [(Prim 'and (list e1 e2))
  19195. (recur (If e1 e2 (Bool #f)))]
  19196. [(Prim 'or (list e1 e2))
  19197. (define tmp (gensym 'tmp))
  19198. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19199. [(If e1 e2 e3)
  19200. (define-values (e1^ T1) (recur e1))
  19201. (define-values (e2^ T2) (recur e2))
  19202. (define-values (e3^ T3) (recur e3))
  19203. (check-consistent? T1 'Boolean e)
  19204. (check-consistent? T2 T3 e)
  19205. (define Tif (meet T2 T3))
  19206. (values (If e1^ e2^ e3^) Tif)]
  19207. [(SetBang x e1)
  19208. (define-values (e1^ T1) (recur e1))
  19209. (define varT (dict-ref env x))
  19210. (check-consistent? T1 varT e)
  19211. (values (SetBang x e1^) 'Void)]
  19212. [(WhileLoop e1 e2)
  19213. (define-values (e1^ T1) (recur e1))
  19214. (check-consistent? T1 'Boolean e)
  19215. (define-values (e2^ T2) ((type-check-exp env) e2))
  19216. (values (WhileLoop e1^ e2^) 'Void)]
  19217. [(Prim 'vector-length (list e1))
  19218. (define-values (e1^ t) (recur e1))
  19219. (match t
  19220. [`(Vector ,ts ...)
  19221. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19222. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19223. \end{lstlisting}
  19224. \end{tcolorbox}
  19225. \caption{Type checker for the \LangGrad{} language, part 1.}
  19226. \label{fig:type-check-Lgradual-1}
  19227. \end{figure}
  19228. \begin{figure}[tbp]
  19229. \begin{tcolorbox}[colback=white]
  19230. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19231. [(Prim 'vector-ref (list e1 e2))
  19232. (define-values (e1^ t1) (recur e1))
  19233. (define-values (e2^ t2) (recur e2))
  19234. (check-consistent? t2 'Integer e)
  19235. (match t1
  19236. [`(Vector ,ts ...)
  19237. (match e2^
  19238. [(Int i)
  19239. (unless (and (0 . <= . i) (i . < . (length ts)))
  19240. (error 'type-check "invalid index ~a in ~a" i e))
  19241. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19242. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19243. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19244. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19245. [(Prim 'vector-set! (list e1 e2 e3) )
  19246. (define-values (e1^ t1) (recur e1))
  19247. (define-values (e2^ t2) (recur e2))
  19248. (define-values (e3^ t3) (recur e3))
  19249. (check-consistent? t2 'Integer e)
  19250. (match t1
  19251. [`(Vector ,ts ...)
  19252. (match e2^
  19253. [(Int i)
  19254. (unless (and (0 . <= . i) (i . < . (length ts)))
  19255. (error 'type-check "invalid index ~a in ~a" i e))
  19256. (check-consistent? (list-ref ts i) t3 e)
  19257. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19258. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19259. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19260. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19261. [(Apply e1 e2s)
  19262. (define-values (e1^ T1) (recur e1))
  19263. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19264. (match T1
  19265. [`(,T1ps ... -> ,T1rt)
  19266. (for ([T2 T2s] [Tp T1ps])
  19267. (check-consistent? T2 Tp e))
  19268. (values (Apply e1^ e2s^) T1rt)]
  19269. [`Any (values (Apply e1^ e2s^) 'Any)]
  19270. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19271. [(Lambda params Tr e1)
  19272. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19273. (match p
  19274. [`[,x : ,T] (values x T)]
  19275. [(? symbol? x) (values x 'Any)])))
  19276. (define-values (e1^ T1)
  19277. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19278. (check-consistent? Tr T1 e)
  19279. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19280. `(,@Ts -> ,Tr))]
  19281. [else ((super type-check-exp env) e)]
  19282. )))
  19283. \end{lstlisting}
  19284. \end{tcolorbox}
  19285. \caption{Type checker for the \LangGrad{} language, part 2.}
  19286. \label{fig:type-check-Lgradual-2}
  19287. \end{figure}
  19288. \begin{figure}[tbp]
  19289. \begin{tcolorbox}[colback=white]
  19290. \begin{lstlisting}
  19291. (define/override (type-check-def env)
  19292. (lambda (e)
  19293. (match e
  19294. [(Def f params rt info body)
  19295. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19296. (match p
  19297. [`[,x : ,T] (values x T)]
  19298. [(? symbol? x) (values x 'Any)])))
  19299. (define new-env (append (map cons xs ps) env))
  19300. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19301. (check-consistent? ty^ rt e)
  19302. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19303. [else (error 'type-check "ill-formed function definition ~a" e)]
  19304. )))
  19305. (define/override (type-check-program e)
  19306. (match e
  19307. [(Program info body)
  19308. (define-values (body^ ty) ((type-check-exp '()) body))
  19309. (check-consistent? ty 'Integer e)
  19310. (ProgramDefsExp info '() body^)]
  19311. [(ProgramDefsExp info ds body)
  19312. (define new-env (for/list ([d ds])
  19313. (cons (Def-name d) (fun-def-type d))))
  19314. (define ds^ (for/list ([d ds])
  19315. ((type-check-def new-env) d)))
  19316. (define-values (body^ ty) ((type-check-exp new-env) body))
  19317. (check-consistent? ty 'Integer e)
  19318. (ProgramDefsExp info ds^ body^)]
  19319. [else (super type-check-program e)]))
  19320. \end{lstlisting}
  19321. \end{tcolorbox}
  19322. \caption{Type checker for the \LangGrad{} language, part 3.}
  19323. \label{fig:type-check-Lgradual-3}
  19324. \end{figure}
  19325. \begin{figure}[tbp]
  19326. \begin{tcolorbox}[colback=white]
  19327. \begin{lstlisting}
  19328. (define/public (join t1 t2)
  19329. (match* (t1 t2)
  19330. [('Integer 'Integer) 'Integer]
  19331. [('Boolean 'Boolean) 'Boolean]
  19332. [('Void 'Void) 'Void]
  19333. [('Any t2) t2]
  19334. [(t1 'Any) t1]
  19335. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19336. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19337. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19338. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19339. -> ,(join rt1 rt2))]))
  19340. (define/public (meet t1 t2)
  19341. (match* (t1 t2)
  19342. [('Integer 'Integer) 'Integer]
  19343. [('Boolean 'Boolean) 'Boolean]
  19344. [('Void 'Void) 'Void]
  19345. [('Any t2) 'Any]
  19346. [(t1 'Any) 'Any]
  19347. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19348. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19349. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19350. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19351. -> ,(meet rt1 rt2))]))
  19352. (define/public (check-consistent? t1 t2 e)
  19353. (unless (consistent? t1 t2)
  19354. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19355. (define explicit-prim-ops
  19356. (set-union
  19357. (type-predicates)
  19358. (set 'procedure-arity 'eq? 'not 'and 'or
  19359. 'vector 'vector-length 'vector-ref 'vector-set!
  19360. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19361. (define/override (fun-def-type d)
  19362. (match d
  19363. [(Def f params rt info body)
  19364. (define ps
  19365. (for/list ([p params])
  19366. (match p
  19367. [`[,x : ,T] T]
  19368. [(? symbol?) 'Any]
  19369. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19370. `(,@ps -> ,rt)]
  19371. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19372. \end{lstlisting}
  19373. \end{tcolorbox}
  19374. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19375. \label{fig:type-check-Lgradual-aux}
  19376. \end{figure}
  19377. \fi}
  19378. \clearpage
  19379. \section{Interpreting \LangCast{}}
  19380. \label{sec:interp-casts}
  19381. The runtime behavior of casts involving simple types such as
  19382. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19383. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19384. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19385. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19386. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19387. operator, by checking the value's tag and either retrieving
  19388. the underlying integer or signaling an error if the tag is not the
  19389. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19390. %
  19391. Things get more interesting with casts involving
  19392. \racket{function and tuple types}\python{function, tuple, and array types}.
  19393. Consider the cast of the function \code{maybe\_inc} from
  19394. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19395. to
  19396. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19397. shown in figure~\ref{fig:map-maybe_inc}.
  19398. When the \code{maybe\_inc} function flows through
  19399. this cast at runtime, we don't know whether it will return
  19400. an integer, because that depends on the input from the user.
  19401. The \LangCast{} interpreter therefore delays the checking
  19402. of the cast until the function is applied. To do so it
  19403. wraps \code{maybe\_inc} in a new function that casts its parameter
  19404. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19405. casts the return value from \CANYTY{} to \INTTY{}.
  19406. {\if\edition\pythonEd\pythonColor
  19407. %
  19408. There are further complications regarding casts on mutable data,
  19409. such as the \code{list} type introduced in
  19410. the challenge assignment of section~\ref{sec:arrays}.
  19411. %
  19412. \fi}
  19413. %
  19414. Consider the example presented in figure~\ref{fig:map-bang} that
  19415. defines a partially typed version of \code{map} whose parameter
  19416. \code{v} has type
  19417. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19418. and that updates \code{v} in place
  19419. instead of returning a new tuple. We name this function
  19420. \code{map\_inplace}. We apply \code{map\_inplace} to
  19421. \racket{a tuple}\python{an array} of integers, so the type checker
  19422. inserts a cast from
  19423. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19424. to
  19425. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19426. A naive way for the \LangCast{} interpreter to cast between
  19427. \racket{tuple}\python{array} types would be to build a new
  19428. \racket{tuple}\python{array} whose elements are the result
  19429. of casting each of the original elements to the appropriate target
  19430. type. However, this approach is not valid for mutable data structures.
  19431. In the example of figure~\ref{fig:map-bang},
  19432. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19433. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19434. the original one.
  19435. \begin{figure}[tbp]
  19436. \begin{tcolorbox}[colback=white]
  19437. % gradual_test_11.rkt
  19438. {\if\edition\racketEd
  19439. \begin{lstlisting}
  19440. (define (map_inplace [f : (Any -> Any)]
  19441. [v : (Vector Any Any)]) : Void
  19442. (begin
  19443. (vector-set! v 0 (f (vector-ref v 0)))
  19444. (vector-set! v 1 (f (vector-ref v 1)))))
  19445. (define (inc x) (+ x 1))
  19446. (let ([v (vector 0 41)])
  19447. (begin (map_inplace inc v) (vector-ref v 1)))
  19448. \end{lstlisting}
  19449. \fi}
  19450. {\if\edition\pythonEd\pythonColor
  19451. \begin{lstlisting}
  19452. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19453. i = 0
  19454. while i != len(v):
  19455. v[i] = f(v[i])
  19456. i = i + 1
  19457. def inc(x : int) -> int:
  19458. return x + 1
  19459. v = [0, 41]
  19460. map_inplace(inc, v)
  19461. print(v[1])
  19462. \end{lstlisting}
  19463. \fi}
  19464. \end{tcolorbox}
  19465. \caption{An example involving casts on arrays.}
  19466. \label{fig:map-bang}
  19467. \end{figure}
  19468. Instead the interpreter needs to create a new kind of value, a
  19469. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19470. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19471. and then applies a
  19472. cast to the resulting value. On a write, the proxy casts the argument
  19473. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19474. \racket{
  19475. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19476. \code{0} from \INTTY{} to \CANYTY{}.
  19477. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19478. from \CANYTY{} to \INTTY{}.
  19479. }
  19480. \python{
  19481. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19482. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19483. For the subscript on the left of the assignment,
  19484. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19485. }
  19486. Finally we consider casts between the \CANYTY{} type and higher-order types
  19487. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19488. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19489. have a type annotation, so it is given type \CANYTY{}. In the call to
  19490. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19491. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19492. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19493. \code{Inject}, but that doesn't work because
  19494. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19495. a flat type. Instead, we must first cast to
  19496. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19497. and then inject to \CANYTY{}.
  19498. \begin{figure}[tbp]
  19499. \begin{tcolorbox}[colback=white]
  19500. {\if\edition\racketEd
  19501. \begin{lstlisting}
  19502. (define (map_inplace [f : (Any -> Any)] v) : Void
  19503. (begin
  19504. (vector-set! v 0 (f (vector-ref v 0)))
  19505. (vector-set! v 1 (f (vector-ref v 1)))))
  19506. (define (inc x) (+ x 1))
  19507. (let ([v (vector 0 41)])
  19508. (begin (map_inplace inc v) (vector-ref v 1)))
  19509. \end{lstlisting}
  19510. \fi}
  19511. {\if\edition\pythonEd\pythonColor
  19512. \begin{lstlisting}
  19513. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19514. i = 0
  19515. while i != len(v):
  19516. v[i] = f(v[i])
  19517. i = i + 1
  19518. def inc(x):
  19519. return x + 1
  19520. v = [0, 41]
  19521. map_inplace(inc, v)
  19522. print(v[1])
  19523. \end{lstlisting}
  19524. \fi}
  19525. \end{tcolorbox}
  19526. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19527. \label{fig:map-any}
  19528. \end{figure}
  19529. \begin{figure}[tbp]
  19530. \begin{tcolorbox}[colback=white]
  19531. {\if\edition\racketEd
  19532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19533. (define/public (apply_cast v s t)
  19534. (match* (s t)
  19535. [(t1 t2) #:when (equal? t1 t2) v]
  19536. [('Any t2)
  19537. (match t2
  19538. [`(,ts ... -> ,rt)
  19539. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19540. (define v^ (apply-project v any->any))
  19541. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19542. [`(Vector ,ts ...)
  19543. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19544. (define v^ (apply-project v vec-any))
  19545. (apply_cast v^ vec-any `(Vector ,@ts))]
  19546. [else (apply-project v t2)])]
  19547. [(t1 'Any)
  19548. (match t1
  19549. [`(,ts ... -> ,rt)
  19550. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19551. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19552. (apply-inject v^ (any-tag any->any))]
  19553. [`(Vector ,ts ...)
  19554. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19555. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19556. (apply-inject v^ (any-tag vec-any))]
  19557. [else (apply-inject v (any-tag t1))])]
  19558. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19559. (define x (gensym 'x))
  19560. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19561. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19562. (define cast-writes
  19563. (for/list ([t1 ts1] [t2 ts2])
  19564. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19565. `(vector-proxy ,(vector v (apply vector cast-reads)
  19566. (apply vector cast-writes)))]
  19567. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19568. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19569. `(function ,xs ,(Cast
  19570. (Apply (Value v)
  19571. (for/list ([x xs][t1 ts1][t2 ts2])
  19572. (Cast (Var x) t2 t1)))
  19573. rt1 rt2) ())]
  19574. ))
  19575. \end{lstlisting}
  19576. \fi}
  19577. {\if\edition\pythonEd\pythonColor
  19578. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19579. def apply_cast(self, value, src, tgt):
  19580. match (src, tgt):
  19581. case (AnyType(), FunctionType(ps2, rt2)):
  19582. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19583. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19584. case (AnyType(), TupleType(ts2)):
  19585. anytup = TupleType([AnyType() for t1 in ts2])
  19586. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19587. case (AnyType(), ListType(t2)):
  19588. anylist = ListType([AnyType() for t1 in ts2])
  19589. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19590. case (AnyType(), AnyType()):
  19591. return value
  19592. case (AnyType(), _):
  19593. return self.apply_project(value, tgt)
  19594. case (FunctionType(ps1,rt1), AnyType()):
  19595. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19596. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19597. case (TupleType(ts1), AnyType()):
  19598. anytup = TupleType([AnyType() for t1 in ts1])
  19599. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19600. case (ListType(t1), AnyType()):
  19601. anylist = ListType(AnyType())
  19602. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19603. case (_, AnyType()):
  19604. return self.apply_inject(value, src)
  19605. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19606. params = [generate_name('x') for p in ps2]
  19607. args = [Cast(Name(x), t2, t1)
  19608. for (x,t1,t2) in zip(params, ps1, ps2)]
  19609. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19610. return Function('cast', params, [Return(body)], {})
  19611. case (TupleType(ts1), TupleType(ts2)):
  19612. x = generate_name('x')
  19613. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19614. for (t1,t2) in zip(ts1,ts2)]
  19615. return ProxiedTuple(value, reads)
  19616. case (ListType(t1), ListType(t2)):
  19617. x = generate_name('x')
  19618. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19619. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19620. return ProxiedList(value, read, write)
  19621. case (t1, t2) if t1 == t2:
  19622. return value
  19623. case (t1, t2):
  19624. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19625. def apply_inject(self, value, src):
  19626. return Tagged(value, self.type_to_tag(src))
  19627. def apply_project(self, value, tgt):
  19628. match value:
  19629. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19630. return val
  19631. case _:
  19632. raise Exception('apply_project, unexpected ' + repr(value))
  19633. \end{lstlisting}
  19634. \fi}
  19635. \end{tcolorbox}
  19636. \caption{The \code{apply\_cast} auxiliary method.}
  19637. \label{fig:apply_cast}
  19638. \end{figure}
  19639. The \LangCast{} interpreter uses an auxiliary function named
  19640. \code{apply\_cast} to cast a value from a source type to a target type,
  19641. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19642. the kinds of casts that we've discussed in this section.
  19643. %
  19644. The definition of the interpreter for \LangCast{} is shown in
  19645. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19646. dispatching to \code{apply\_cast}.
  19647. \racket{To handle the addition of tuple
  19648. proxies, we update the tuple primitives in \code{interp-op} using the
  19649. functions given in figure~\ref{fig:guarded-tuple}.}
  19650. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19651. \begin{figure}[tbp]
  19652. \begin{tcolorbox}[colback=white]
  19653. {\if\edition\racketEd
  19654. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19655. (define interp-Lcast-class
  19656. (class interp-Llambda-class
  19657. (super-new)
  19658. (inherit apply-fun apply-inject apply-project)
  19659. (define/override (interp-op op)
  19660. (match op
  19661. ['vector-length guarded-vector-length]
  19662. ['vector-ref guarded-vector-ref]
  19663. ['vector-set! guarded-vector-set!]
  19664. ['any-vector-ref (lambda (v i)
  19665. (match v [`(tagged ,v^ ,tg)
  19666. (guarded-vector-ref v^ i)]))]
  19667. ['any-vector-set! (lambda (v i a)
  19668. (match v [`(tagged ,v^ ,tg)
  19669. (guarded-vector-set! v^ i a)]))]
  19670. ['any-vector-length (lambda (v)
  19671. (match v [`(tagged ,v^ ,tg)
  19672. (guarded-vector-length v^)]))]
  19673. [else (super interp-op op)]
  19674. ))
  19675. (define/override ((interp-exp env) e)
  19676. (define (recur e) ((interp-exp env) e))
  19677. (match e
  19678. [(Value v) v]
  19679. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19680. [else ((super interp-exp env) e)]))
  19681. ))
  19682. (define (interp-Lcast p)
  19683. (send (new interp-Lcast-class) interp-program p))
  19684. \end{lstlisting}
  19685. \fi}
  19686. {\if\edition\pythonEd\pythonColor
  19687. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19688. class InterpLcast(InterpLany):
  19689. def interp_exp(self, e, env):
  19690. match e:
  19691. case Cast(value, src, tgt):
  19692. v = self.interp_exp(value, env)
  19693. return self.apply_cast(v, src, tgt)
  19694. case ValueExp(value):
  19695. return value
  19696. ...
  19697. case _:
  19698. return super().interp_exp(e, env)
  19699. \end{lstlisting}
  19700. \fi}
  19701. \end{tcolorbox}
  19702. \caption{The interpreter for \LangCast{}.}
  19703. \label{fig:interp-Lcast}
  19704. \end{figure}
  19705. {\if\edition\racketEd
  19706. \begin{figure}[tbp]
  19707. \begin{tcolorbox}[colback=white]
  19708. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19709. (define (guarded-vector-ref vec i)
  19710. (match vec
  19711. [`(vector-proxy ,proxy)
  19712. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19713. (define rd (vector-ref (vector-ref proxy 1) i))
  19714. (apply-fun rd (list val) 'guarded-vector-ref)]
  19715. [else (vector-ref vec i)]))
  19716. (define (guarded-vector-set! vec i arg)
  19717. (match vec
  19718. [`(vector-proxy ,proxy)
  19719. (define wr (vector-ref (vector-ref proxy 2) i))
  19720. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19721. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19722. [else (vector-set! vec i arg)]))
  19723. (define (guarded-vector-length vec)
  19724. (match vec
  19725. [`(vector-proxy ,proxy)
  19726. (guarded-vector-length (vector-ref proxy 0))]
  19727. [else (vector-length vec)]))
  19728. \end{lstlisting}
  19729. %% {\if\edition\pythonEd\pythonColor
  19730. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19731. %% UNDER CONSTRUCTION
  19732. %% \end{lstlisting}
  19733. %% \fi}
  19734. \end{tcolorbox}
  19735. \caption{The \code{guarded-vector} auxiliary functions.}
  19736. \label{fig:guarded-tuple}
  19737. \end{figure}
  19738. \fi}
  19739. {\if\edition\pythonEd\pythonColor
  19740. \section{Overload Resolution}
  19741. \label{sec:gradual-resolution}
  19742. Recall that when we added support for arrays in
  19743. section~\ref{sec:arrays}, the syntax for the array operations were the
  19744. same as for tuple operations (for example, accessing an element and
  19745. getting the length). So we performed overload resolution, with a pass
  19746. named \code{resolve}, to separate the array and tuple operations. In
  19747. particular, we introduced the primitives \code{array\_load},
  19748. \code{array\_store}, and \code{array\_len}.
  19749. For gradual typing, we further overload these operators to work on
  19750. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19751. updated with new cases for the \CANYTY{} type, translating the element
  19752. access and length operations to the primitives \code{any\_load},
  19753. \code{any\_store}, and \code{any\_len}.
  19754. \fi}
  19755. \section{Cast Insertion}
  19756. \label{sec:gradual-insert-casts}
  19757. In our discussion of type checking of \LangGrad{}, we mentioned how
  19758. the runtime aspect of type checking is carried out by the \code{Cast}
  19759. AST node, which is added to the program by a new pass named
  19760. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19761. language. We now discuss the details of this pass.
  19762. The \code{cast\_insert} pass is closely related to the type checker
  19763. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19764. In particular, the type checker allows implicit casts between
  19765. consistent types. The job of the \code{cast\_insert} pass is to make
  19766. those casts explicit. It does so by inserting
  19767. \code{Cast} nodes into the AST.
  19768. %
  19769. For the most part, the implicit casts occur in places where the type
  19770. checker checks two types for consistency. Consider the case for
  19771. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19772. checker requires that the type of the left operand is consistent with
  19773. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19774. \code{Cast} around the left operand, converting from its type to
  19775. \INTTY{}. The story is similar for the right operand. It is not always
  19776. necessary to insert a cast, for example, if the left operand already has type
  19777. \INTTY{} then there is no need for a \code{Cast}.
  19778. Some of the implicit casts are not as straightforward. One such case
  19779. arises with the
  19780. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19781. see that the type checker requires that the two branches have
  19782. consistent types and that type of the conditional expression is the
  19783. meet of the branches' types. In the target language \LangCast{}, both
  19784. branches will need to have the same type, and that type
  19785. will be the type of the conditional expression. Thus, each branch requires
  19786. a \code{Cast} to convert from its type to the meet of the branches' types.
  19787. The case for the function call exhibits another interesting situation. If
  19788. the function expression is of type \CANYTY{}, then it needs to be cast
  19789. to a function type so that it can be used in a function call in
  19790. \LangCast{}. Which function type should it be cast to? The parameter
  19791. and return types are unknown, so we can simply use \CANYTY{} for all
  19792. of them. Furthermore, in \LangCast{} the argument types will need to
  19793. exactly match the parameter types, so we must cast all the arguments
  19794. to type \CANYTY{} (if they are not already of that type).
  19795. {\if\edition\racketEd
  19796. %
  19797. Likewise, the cases for the tuple operators \code{vector-length},
  19798. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19799. where the tuple expression is of type \CANYTY{}. Instead of
  19800. handling these situations with casts, we recommend translating
  19801. the special-purpose variants of the tuple operators that handle
  19802. tuples of type \CANYTY{}: \code{any-vector-length},
  19803. \code{any-vector-ref}, and \code{any-vector-set!}.
  19804. %
  19805. \fi}
  19806. \section{Lower Casts}
  19807. \label{sec:lower_casts}
  19808. The next step in the journey toward x86 is the \code{lower\_casts}
  19809. pass that translates the casts in \LangCast{} to the lower-level
  19810. \code{Inject} and \code{Project} operators and new operators for
  19811. proxies, extending the \LangLam{} language to \LangProxy{}.
  19812. The \LangProxy{} language can also be described as an extension of
  19813. \LangAny{}, with the addition of proxies. We recommend creating an
  19814. auxiliary function named \code{lower\_cast} that takes an expression
  19815. (in \LangCast{}), a source type, and a target type and translates it
  19816. to an expression in \LangProxy{}.
  19817. The \code{lower\_cast} function can follow a code structure similar to
  19818. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19819. the interpreter for \LangCast{}, because it must handle the same cases
  19820. as \code{apply\_cast} and it needs to mimic the behavior of
  19821. \code{apply\_cast}. The most interesting cases concern
  19822. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19823. {\if\edition\racketEd
  19824. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19825. type to another tuple type is accomplished by creating a proxy that
  19826. intercepts the operations on the underlying tuple. Here we make the
  19827. creation of the proxy explicit with the \code{vector-proxy} AST
  19828. node. It takes three arguments: the first is an expression for the
  19829. tuple, the second is a tuple of functions for casting an element that is
  19830. being read from the tuple, and the third is a tuple of functions for
  19831. casting an element that is being written to the array. You can create
  19832. the functions for reading and writing using lambda expressions. Also,
  19833. as we show in the next section, we need to differentiate these tuples
  19834. of functions from the user-created ones, so we recommend using a new
  19835. AST node named \code{raw-vector} instead of \code{vector}.
  19836. %
  19837. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19838. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19839. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19840. \fi}
  19841. {\if\edition\pythonEd\pythonColor
  19842. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19843. type to another array type is accomplished by creating a proxy that
  19844. intercepts the operations on the underlying array. Here we make the
  19845. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19846. takes fives arguments: the first is an expression for the array, the
  19847. second is a function for casting an element that is being read from
  19848. the array, the third is a function for casting an element that is
  19849. being written to the array, the fourth is the type of the underlying
  19850. array, and the fifth is the type of the proxied array. You can create
  19851. the functions for reading and writing using lambda expressions.
  19852. A cast between two tuple types can be handled in a similar manner. We
  19853. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19854. immutable, so there is no need for a function to cast the value during
  19855. a write. Because there is a separate element type for each slot in
  19856. the tuple, we need more than one function for casting during a read:
  19857. we need a tuple of functions.
  19858. %
  19859. Also, as we show in the next section, we need to differentiate these
  19860. tuples from the user-created ones, so we recommend using a new AST
  19861. node named \code{RawTuple} instead of \code{Tuple} to create the
  19862. tuples of functions.
  19863. %
  19864. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19865. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19866. that involves casting an array of integers to an array of \CANYTY{}.
  19867. \fi}
  19868. \begin{figure}[tbp]
  19869. \begin{tcolorbox}[colback=white]
  19870. {\if\edition\racketEd
  19871. \begin{lstlisting}
  19872. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19873. (begin
  19874. (vector-set! v 0 (f (vector-ref v 0)))
  19875. (vector-set! v 1 (f (vector-ref v 1)))))
  19876. (define (inc [x : Any]) : Any
  19877. (inject (+ (project x Integer) 1) Integer))
  19878. (let ([v (vector 0 41)])
  19879. (begin
  19880. (map_inplace inc (vector-proxy v
  19881. (raw-vector (lambda: ([x9 : Integer]) : Any
  19882. (inject x9 Integer))
  19883. (lambda: ([x9 : Integer]) : Any
  19884. (inject x9 Integer)))
  19885. (raw-vector (lambda: ([x9 : Any]) : Integer
  19886. (project x9 Integer))
  19887. (lambda: ([x9 : Any]) : Integer
  19888. (project x9 Integer)))))
  19889. (vector-ref v 1)))
  19890. \end{lstlisting}
  19891. \fi}
  19892. {\if\edition\pythonEd\pythonColor
  19893. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19894. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19895. i = 0
  19896. while i != array_len(v):
  19897. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19898. i = (i + 1)
  19899. def inc(x : int) -> int:
  19900. return (x + 1)
  19901. def main() -> int:
  19902. v = [0, 41]
  19903. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19904. print(array_load(v, 1))
  19905. return 0
  19906. \end{lstlisting}
  19907. \fi}
  19908. \end{tcolorbox}
  19909. \caption{Output of \code{lower\_casts} on the example shown in
  19910. figure~\ref{fig:map-bang}.}
  19911. \label{fig:map-bang-lower-cast}
  19912. \end{figure}
  19913. A cast from one function type to another function type is accomplished
  19914. by generating a \code{lambda} whose parameter and return types match
  19915. the target function type. The body of the \code{lambda} should cast
  19916. the parameters from the target type to the source type. (Yes,
  19917. backward! Functions are contravariant\index{subject}{contravariant}
  19918. in the parameters.) Afterward, call the underlying function and then
  19919. cast the result from the source return type to the target return type.
  19920. Figure~\ref{fig:map-lower-cast} shows the output of the
  19921. \code{lower\_casts} pass on the \code{map} example give in
  19922. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19923. call to \code{map} is wrapped in a \code{lambda}.
  19924. \begin{figure}[tbp]
  19925. \begin{tcolorbox}[colback=white]
  19926. {\if\edition\racketEd
  19927. \begin{lstlisting}
  19928. (define (map [f : (Integer -> Integer)]
  19929. [v : (Vector Integer Integer)])
  19930. : (Vector Integer Integer)
  19931. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19932. (define (inc [x : Any]) : Any
  19933. (inject (+ (project x Integer) 1) Integer))
  19934. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19935. (project (inc (inject x9 Integer)) Integer))
  19936. (vector 0 41)) 1)
  19937. \end{lstlisting}
  19938. \fi}
  19939. {\if\edition\pythonEd\pythonColor
  19940. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19941. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19942. return (f(v[0]), f(v[1]),)
  19943. def inc(x : any) -> any:
  19944. return inject((project(x, int) + 1), int)
  19945. def main() -> int:
  19946. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19947. print(t[1])
  19948. return 0
  19949. \end{lstlisting}
  19950. \fi}
  19951. \end{tcolorbox}
  19952. \caption{Output of \code{lower\_casts} on the example shown in
  19953. figure~\ref{fig:gradual-map}.}
  19954. \label{fig:map-lower-cast}
  19955. \end{figure}
  19956. \section{Differentiate Proxies}
  19957. \label{sec:differentiate-proxies}
  19958. So far, the responsibility of differentiating tuples and tuple proxies
  19959. has been the job of the interpreter.
  19960. %
  19961. \racket{For example, the interpreter for \LangCast{} implements
  19962. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19963. figure~\ref{fig:guarded-tuple}.}
  19964. %
  19965. In the \code{differentiate\_proxies} pass we shift this responsibility
  19966. to the generated code.
  19967. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19968. we used the type \TUPLETYPENAME{} for both
  19969. real tuples and tuple proxies.
  19970. \python{Similarly, we use the type \code{list} for both arrays and
  19971. array proxies.}
  19972. In \LangPVec{} we return the
  19973. \TUPLETYPENAME{} type to its original
  19974. meaning, as the type of just tuples, and we introduce a new type,
  19975. \PTUPLETYNAME{}, whose values
  19976. can be either real tuples or tuple
  19977. proxies.
  19978. %
  19979. {\if\edition\pythonEd\pythonColor
  19980. Likewise, we return the
  19981. \ARRAYTYPENAME{} type to its original
  19982. meaning, as the type of arrays, and we introduce a new type,
  19983. \PARRAYTYNAME{}, whose values
  19984. can be either arrays or array proxies.
  19985. These new types come with a suite of new primitive operations.
  19986. \fi}
  19987. {\if\edition\racketEd
  19988. A tuple proxy is represented by a tuple containing three things: (1) the
  19989. underlying tuple, (2) a tuple of functions for casting elements that
  19990. are read from the tuple, and (3) a tuple of functions for casting
  19991. values to be written to the tuple. So, we define the following
  19992. abbreviation for the type of a tuple proxy:
  19993. \[
  19994. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19995. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  19996. \]
  19997. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19998. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19999. %
  20000. Next we describe each of the new primitive operations.
  20001. \begin{description}
  20002. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20003. (\key{PVector} $T \ldots$)]\ \\
  20004. %
  20005. This operation brands a vector as a value of the \code{PVector} type.
  20006. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20007. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20008. %
  20009. This operation brands a vector proxy as value of the \code{PVector} type.
  20010. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20011. \BOOLTY{}] \ \\
  20012. %
  20013. This returns true if the value is a tuple proxy and false if it is a
  20014. real tuple.
  20015. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20016. (\key{Vector} $T \ldots$)]\ \\
  20017. %
  20018. Assuming that the input is a tuple, this operation returns the
  20019. tuple.
  20020. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20021. $\to$ \INTTY{}]\ \\
  20022. %
  20023. Given a tuple proxy, this operation returns the length of the tuple.
  20024. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20025. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20026. %
  20027. Given a tuple proxy, this operation returns the $i$th element of the
  20028. tuple.
  20029. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20030. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20031. Given a tuple proxy, this operation writes a value to the $i$th element
  20032. of the tuple.
  20033. \end{description}
  20034. \fi}
  20035. {\if\edition\pythonEd\pythonColor
  20036. %
  20037. A tuple proxy is represented by a tuple containing (1) the underlying
  20038. tuple and (2) a tuple of functions for casting elements that are read
  20039. from the tuple. The \LangPVec{} language includes the following AST
  20040. classes and primitive functions.
  20041. \begin{description}
  20042. \item[\code{InjectTuple}] \ \\
  20043. %
  20044. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20045. \item[\code{InjectTupleProxy}]\ \\
  20046. %
  20047. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20048. \item[\code{is\_tuple\_proxy}]\ \\
  20049. %
  20050. This primitive returns true if the value is a tuple proxy and false
  20051. if it is a tuple.
  20052. \item[\code{project\_tuple}]\ \\
  20053. %
  20054. Converts a tuple that is branded as \PTUPLETYNAME{}
  20055. back to a tuple.
  20056. \item[\code{proxy\_tuple\_len}]\ \\
  20057. %
  20058. Given a tuple proxy, returns the length of the underlying tuple.
  20059. \item[\code{proxy\_tuple\_load}]\ \\
  20060. %
  20061. Given a tuple proxy, returns the $i$th element of the underlying
  20062. tuple.
  20063. \end{description}
  20064. An array proxy is represented by a tuple containing (1) the underlying
  20065. array, (2) a function for casting elements that are read from the
  20066. array, and (3) a function for casting elements that are written to the
  20067. array. The \LangPVec{} language includes the following AST classes
  20068. and primitive functions.
  20069. \begin{description}
  20070. \item[\code{InjectList}]\ \\
  20071. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20072. \item[\code{InjectListProxy}]\ \\
  20073. %
  20074. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20075. \item[\code{is\_array\_proxy}]\ \\
  20076. %
  20077. Returns true if the value is an array proxy and false if it is an
  20078. array.
  20079. \item[\code{project\_array}]\ \\
  20080. %
  20081. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20082. array.
  20083. \item[\code{proxy\_array\_len}]\ \\
  20084. %
  20085. Given an array proxy, returns the length of the underlying array.
  20086. \item[\code{proxy\_array\_load}]\ \\
  20087. %
  20088. Given an array proxy, returns the $i$th element of the underlying
  20089. array.
  20090. \item[\code{proxy\_array\_store}]\ \\
  20091. %
  20092. Given an array proxy, writes a value to the $i$th element of the
  20093. underlying array.
  20094. \end{description}
  20095. \fi}
  20096. Now we discuss the translation that differentiates tuples and arrays
  20097. from proxies. First, every type annotation in the program is
  20098. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20099. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20100. places. For example, we wrap every tuple creation with an
  20101. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20102. %
  20103. {\if\edition\racketEd
  20104. \begin{minipage}{0.96\textwidth}
  20105. \begin{lstlisting}
  20106. (vector |$e_1 \ldots e_n$|)
  20107. |$\Rightarrow$|
  20108. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20109. \end{lstlisting}
  20110. \end{minipage}
  20111. \fi}
  20112. {\if\edition\pythonEd\pythonColor
  20113. \begin{lstlisting}
  20114. Tuple(|$e_1, \ldots, e_n$|)
  20115. |$\Rightarrow$|
  20116. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20117. \end{lstlisting}
  20118. \fi}
  20119. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20120. AST node that we introduced in the previous
  20121. section does not get injected.
  20122. {\if\edition\racketEd
  20123. \begin{lstlisting}
  20124. (raw-vector |$e_1 \ldots e_n$|)
  20125. |$\Rightarrow$|
  20126. (vector |$e'_1 \ldots e'_n$|)
  20127. \end{lstlisting}
  20128. \fi}
  20129. {\if\edition\pythonEd\pythonColor
  20130. \begin{lstlisting}
  20131. RawTuple(|$e_1, \ldots, e_n$|)
  20132. |$\Rightarrow$|
  20133. Tuple(|$e'_1, \ldots, e'_n$|)
  20134. \end{lstlisting}
  20135. \fi}
  20136. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20137. translates as follows:
  20138. %
  20139. {\if\edition\racketEd
  20140. \begin{lstlisting}
  20141. (vector-proxy |$e_1~e_2~e_3$|)
  20142. |$\Rightarrow$|
  20143. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20144. \end{lstlisting}
  20145. \fi}
  20146. {\if\edition\pythonEd\pythonColor
  20147. \begin{lstlisting}
  20148. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20149. |$\Rightarrow$|
  20150. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20151. \end{lstlisting}
  20152. \fi}
  20153. We translate the element access operations into conditional
  20154. expressions that check whether the value is a proxy and then dispatch
  20155. to either the appropriate proxy tuple operation or the regular tuple
  20156. operation.
  20157. {\if\edition\racketEd
  20158. \begin{lstlisting}
  20159. (vector-ref |$e_1$| |$i$|)
  20160. |$\Rightarrow$|
  20161. (let ([|$v~e_1$|])
  20162. (if (proxy? |$v$|)
  20163. (proxy-vector-ref |$v$| |$i$|)
  20164. (vector-ref (project-vector |$v$|) |$i$|)
  20165. \end{lstlisting}
  20166. \fi}
  20167. %
  20168. Note that in the branch for a tuple, we must apply
  20169. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20170. from the tuple.
  20171. The translation of array operations is similar to the ones for tuples.
  20172. \section{Reveal Casts}
  20173. \label{sec:reveal-casts-gradual}
  20174. {\if\edition\racketEd
  20175. Recall that the \code{reveal\_casts} pass
  20176. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20177. \code{Inject} and \code{Project} into lower-level operations.
  20178. %
  20179. In particular, \code{Project} turns into a conditional expression that
  20180. inspects the tag and retrieves the underlying value. Here we need to
  20181. augment the translation of \code{Project} to handle the situation in which
  20182. the target type is \code{PVector}. Instead of using
  20183. \code{vector-length} we need to use \code{proxy-vector-length}.
  20184. \begin{lstlisting}
  20185. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20186. |$\Rightarrow$|
  20187. (let |$\itm{tmp}$| |$e'$|
  20188. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20189. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20190. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20191. (exit)))
  20192. \end{lstlisting}
  20193. \fi}
  20194. %
  20195. {\if\edition\pythonEd\pythonColor
  20196. Recall that the $\itm{tagof}$ function determines the bits used to
  20197. identify values of different types, and it is used in the \code{reveal\_casts}
  20198. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20199. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  20200. decimal), just like the tuple and array types.
  20201. \fi}
  20202. %
  20203. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20204. \section{Closure Conversion}
  20205. \label{sec:closure-conversion-gradual}
  20206. The auxiliary function that translates type annotations needs to be
  20207. updated to handle the \PTUPLETYNAME{}
  20208. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20209. %
  20210. Otherwise, the only other changes are adding cases that copy the new
  20211. AST nodes.
  20212. \section{Select Instructions}
  20213. \label{sec:select-instructions-gradual}
  20214. \index{subject}{select instructions}
  20215. Recall that the \code{select\_instructions} pass is responsible for
  20216. lowering the primitive operations into x86 instructions. So, we need
  20217. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20218. to x86. To do so, the first question we need to answer is how to
  20219. differentiate between tuple and tuple proxies\python{, and likewise for
  20220. arrays and array proxies}. We need just one bit to accomplish this;
  20221. we use the bit in position $63$ of the 64-bit tag at the front of
  20222. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20223. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20224. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20225. it that way.
  20226. {\if\edition\racketEd
  20227. \begin{lstlisting}
  20228. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20229. |$\Rightarrow$|
  20230. movq |$e'_1$|, |$\itm{lhs'}$|
  20231. \end{lstlisting}
  20232. \fi}
  20233. {\if\edition\pythonEd\pythonColor
  20234. \begin{lstlisting}
  20235. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20236. |$\Rightarrow$|
  20237. movq |$e'_1$|, |$\itm{lhs'}$|
  20238. \end{lstlisting}
  20239. \fi}
  20240. \python{The translation for \code{InjectList} is also a move instruction.}
  20241. \noindent On the other hand,
  20242. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20243. $63$ to $1$.
  20244. %
  20245. {\if\edition\racketEd
  20246. \begin{lstlisting}
  20247. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20248. |$\Rightarrow$|
  20249. movq |$e'_1$|, %r11
  20250. movq |$(1 << 63)$|, %rax
  20251. orq 0(%r11), %rax
  20252. movq %rax, 0(%r11)
  20253. movq %r11, |$\itm{lhs'}$|
  20254. \end{lstlisting}
  20255. \fi}
  20256. {\if\edition\pythonEd\pythonColor
  20257. \begin{lstlisting}
  20258. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20259. |$\Rightarrow$|
  20260. movq |$e'_1$|, %r11
  20261. movq |$(1 << 63)$|, %rax
  20262. orq 0(%r11), %rax
  20263. movq %rax, 0(%r11)
  20264. movq %r11, |$\itm{lhs'}$|
  20265. \end{lstlisting}
  20266. \fi}
  20267. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20268. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20269. The \racket{\code{proxy?} operation consumes}%
  20270. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20271. consume}
  20272. the information so carefully stashed away by the injections. It
  20273. isolates bit $63$ to tell whether the value is a proxy.
  20274. %
  20275. {\if\edition\racketEd
  20276. \begin{lstlisting}
  20277. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20278. |$\Rightarrow$|
  20279. movq |$e_1'$|, %r11
  20280. movq 0(%r11), %rax
  20281. sarq $63, %rax
  20282. andq $1, %rax
  20283. movq %rax, |$\itm{lhs'}$|
  20284. \end{lstlisting}
  20285. \fi}%
  20286. %
  20287. {\if\edition\pythonEd\pythonColor
  20288. \begin{lstlisting}
  20289. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20290. |$\Rightarrow$|
  20291. movq |$e_1'$|, %r11
  20292. movq 0(%r11), %rax
  20293. sarq $63, %rax
  20294. andq $1, %rax
  20295. movq %rax, |$\itm{lhs'}$|
  20296. \end{lstlisting}
  20297. \fi}%
  20298. %
  20299. The \racket{\code{project-vector} operation is}
  20300. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20301. straightforward to translate, so we leave that to the reader.
  20302. Regarding the element access operations for tuples\python{ and arrays}, the
  20303. runtime provides procedures that implement them (they are recursive
  20304. functions!), so here we simply need to translate these tuple
  20305. operations into the appropriate function call. For example, here is
  20306. the translation for
  20307. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20308. {\if\edition\racketEd
  20309. \begin{minipage}{0.96\textwidth}
  20310. \begin{lstlisting}
  20311. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20312. |$\Rightarrow$|
  20313. movq |$e_1'$|, %rdi
  20314. movq |$e_2'$|, %rsi
  20315. callq proxy_vector_ref
  20316. movq %rax, |$\itm{lhs'}$|
  20317. \end{lstlisting}
  20318. \end{minipage}
  20319. \fi}
  20320. {\if\edition\pythonEd\pythonColor
  20321. \begin{lstlisting}
  20322. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20323. |$\Rightarrow$|
  20324. movq |$e_1'$|, %rdi
  20325. movq |$e_2'$|, %rsi
  20326. callq proxy_vector_ref
  20327. movq %rax, |$\itm{lhs'}$|
  20328. \end{lstlisting}
  20329. \fi}
  20330. {\if\edition\pythonEd\pythonColor
  20331. % TODO: revisit the names vecof for python -Jeremy
  20332. We translate
  20333. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20334. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20335. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20336. \fi}
  20337. We have another batch of operations to deal with: those for the
  20338. \CANYTY{} type. Recall that we generate an
  20339. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20340. there is a element access on something of type \CANYTY{}, and
  20341. similarly for
  20342. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20343. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20344. section~\ref{sec:select-Lany} we selected instructions for these
  20345. operations on the basis of the idea that the underlying value was a tuple or
  20346. array. But in the current setting, the underlying value is of type
  20347. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20348. functions to deal with this:
  20349. \code{proxy\_vector\_ref},
  20350. \code{proxy\_vector\_set}, and
  20351. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20352. to determine whether the value is a proxy, and then
  20353. dispatches to the the appropriate code.
  20354. %
  20355. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20356. can be translated as follows.
  20357. We begin by projecting the underlying value out of the tagged value and
  20358. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20359. {\if\edition\racketEd
  20360. \begin{lstlisting}
  20361. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20362. |$\Rightarrow$|
  20363. movq |$\neg 111$|, %rdi
  20364. andq |$e_1'$|, %rdi
  20365. movq |$e_2'$|, %rsi
  20366. callq proxy_vector_ref
  20367. movq %rax, |$\itm{lhs'}$|
  20368. \end{lstlisting}
  20369. \fi}
  20370. {\if\edition\pythonEd\pythonColor
  20371. \begin{lstlisting}
  20372. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20373. |$\Rightarrow$|
  20374. movq |$\neg 111$|, %rdi
  20375. andq |$e_1'$|, %rdi
  20376. movq |$e_2'$|, %rsi
  20377. callq proxy_vector_ref
  20378. movq %rax, |$\itm{lhs'}$|
  20379. \end{lstlisting}
  20380. \fi}
  20381. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20382. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20383. are translated in a similar way. Alternatively, you could generate
  20384. instructions to open-code
  20385. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20386. and \code{proxy\_vector\_length} functions.
  20387. \begin{exercise}\normalfont\normalsize
  20388. Implement a compiler for the gradually typed \LangGrad{} language by
  20389. extending and adapting your compiler for \LangLam{}. Create ten new
  20390. partially typed test programs. In addition to testing with these
  20391. new programs, test your compiler on all the tests for \LangLam{}
  20392. and for \LangDyn{}.
  20393. %
  20394. \racket{Sometimes you may get a type-checking error on the
  20395. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20396. the \CANYTY{} type around each subexpression that has caused a type
  20397. error. Although \LangDyn{} does not have explicit casts, you can
  20398. induce one by wrapping the subexpression \code{e} with a call to
  20399. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20400. %
  20401. \python{Sometimes you may get a type-checking error on the
  20402. \LangDyn{} programs, but you can adapt them by inserting a
  20403. temporary variable of type \CANYTY{} that is initialized with the
  20404. troublesome expression.}
  20405. \end{exercise}
  20406. \begin{figure}[t]
  20407. \begin{tcolorbox}[colback=white]
  20408. {\if\edition\racketEd
  20409. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20410. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20411. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20412. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20413. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20414. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20415. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20416. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20417. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20418. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20419. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20420. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20421. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20422. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20423. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20424. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20425. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20426. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20427. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20428. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20429. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20430. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20431. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20432. \path[->,bend left=15] (Lgradual) edge [above] node
  20433. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20434. \path[->,bend left=15] (Lgradual2) edge [above] node
  20435. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20436. \path[->,bend left=15] (Lgradual3) edge [above] node
  20437. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20438. \path[->,bend left=15] (Lgradual4) edge [left] node
  20439. {\ttfamily\footnotesize shrink} (Lgradualr);
  20440. \path[->,bend left=15] (Lgradualr) edge [above] node
  20441. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20442. \path[->,bend right=15] (Lgradualp) edge [above] node
  20443. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20444. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20445. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20446. \path[->,bend right=15] (Llambdapp) edge [above] node
  20447. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20448. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20449. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20450. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20451. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20452. \path[->,bend left=15] (F1-2) edge [above] node
  20453. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20454. \path[->,bend left=15] (F1-3) edge [left] node
  20455. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20456. \path[->,bend left=15] (F1-4) edge [below] node
  20457. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20458. \path[->,bend right=15] (F1-5) edge [above] node
  20459. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20460. \path[->,bend right=15] (F1-6) edge [above] node
  20461. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20462. \path[->,bend right=15] (C3-2) edge [right] node
  20463. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20464. \path[->,bend right=15] (x86-2) edge [right] node
  20465. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20466. \path[->,bend right=15] (x86-2-1) edge [below] node
  20467. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20468. \path[->,bend right=15] (x86-2-2) edge [right] node
  20469. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20470. \path[->,bend left=15] (x86-3) edge [above] node
  20471. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20472. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20473. \end{tikzpicture}
  20474. \fi}
  20475. {\if\edition\pythonEd\pythonColor
  20476. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20477. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20478. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20479. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20480. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20481. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20482. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20483. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20484. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20485. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20486. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20487. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20488. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20489. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20490. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20491. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20492. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20493. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20494. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20495. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20496. \path[->,bend left=15] (Lgradual) edge [above] node
  20497. {\ttfamily\footnotesize shrink} (Lgradual2);
  20498. \path[->,bend left=15] (Lgradual2) edge [above] node
  20499. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20500. \path[->,bend left=15] (Lgradual3) edge [above] node
  20501. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20502. \path[->,bend left=15] (Lgradual4) edge [left] node
  20503. {\ttfamily\footnotesize resolve} (Lgradualr);
  20504. \path[->,bend left=15] (Lgradualr) edge [below] node
  20505. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20506. \path[->,bend right=15] (Lgradualp) edge [above] node
  20507. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20508. \path[->,bend right=15] (Llambdapp) edge [above] node
  20509. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20510. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20511. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20512. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20513. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20514. \path[->,bend left=15] (F1-1) edge [above] node
  20515. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20516. \path[->,bend left=15] (F1-2) edge [above] node
  20517. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20518. \path[->,bend left=15] (F1-3) edge [right] node
  20519. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20520. \path[->,bend right=15] (F1-5) edge [above] node
  20521. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20522. \path[->,bend right=15] (F1-6) edge [above] node
  20523. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20524. \path[->,bend right=15] (C3-2) edge [right] node
  20525. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20526. \path[->,bend right=15] (x86-2) edge [below] node
  20527. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20528. \path[->,bend right=15] (x86-3) edge [below] node
  20529. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20530. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20531. \end{tikzpicture}
  20532. \fi}
  20533. \end{tcolorbox}
  20534. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20535. \label{fig:Lgradual-passes}
  20536. \end{figure}
  20537. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20538. needed for the compilation of \LangGrad{}.
  20539. \section{Further Reading}
  20540. This chapter just scratches the surface of gradual typing. The basic
  20541. approach described here is missing two key ingredients that one would
  20542. want in a implementation of gradual typing: blame
  20543. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20544. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20545. problem addressed by blame tracking is that when a cast on a
  20546. higher-order value fails, it often does so at a point in the program
  20547. that is far removed from the original cast. Blame tracking is a
  20548. technique for propagating extra information through casts and proxies
  20549. so that when a cast fails, the error message can point back to the
  20550. original location of the cast in the source program.
  20551. The problem addressed by space-efficient casts also relates to
  20552. higher-order casts. It turns out that in partially typed programs, a
  20553. function or tuple can flow through a great many casts at runtime. With
  20554. the approach described in this chapter, each cast adds another
  20555. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20556. considerable space, but it also makes the function calls and tuple
  20557. operations slow. For example, a partially typed version of quicksort
  20558. could, in the worst case, build a chain of proxies of length $O(n)$
  20559. around the tuple, changing the overall time complexity of the
  20560. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20561. solution to this problem by representing casts using the coercion
  20562. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20563. long chains of proxies by compressing them into a concise normal
  20564. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20565. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20566. the Grift compiler:
  20567. \begin{center}
  20568. \url{https://github.com/Gradual-Typing/Grift}
  20569. \end{center}
  20570. There are also interesting interactions between gradual typing and
  20571. other language features, such as generics, information-flow types, and
  20572. type inference, to name a few. We recommend to the reader the
  20573. online gradual typing bibliography for more material:
  20574. \begin{center}
  20575. \url{http://samth.github.io/gradual-typing-bib/}
  20576. \end{center}
  20577. % TODO: challenge problem:
  20578. % type analysis and type specialization?
  20579. % coercions?
  20580. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20581. \chapter{Generics}
  20582. \label{ch:Lpoly}
  20583. \setcounter{footnote}{0}
  20584. This chapter studies the compilation of
  20585. generics\index{subject}{generics} (aka parametric
  20586. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20587. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20588. enable programmers to make code more reusable by parameterizing
  20589. functions and data structures with respect to the types on which they
  20590. operate. For example, figure~\ref{fig:map-poly} revisits the
  20591. \code{map} example and this time gives it a more fitting type. This
  20592. \code{map} function is parameterized with respect to the element type
  20593. of the tuple. The type of \code{map} is the following generic type
  20594. specified by the \code{All} type with parameter \code{T}:
  20595. {\if\edition\racketEd
  20596. \begin{lstlisting}
  20597. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20598. \end{lstlisting}
  20599. \fi}
  20600. {\if\edition\pythonEd\pythonColor
  20601. \begin{lstlisting}
  20602. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20603. \end{lstlisting}
  20604. \fi}
  20605. %
  20606. The idea is that \code{map} can be used at \emph{all} choices of a
  20607. type for parameter \code{T}. In the example shown in
  20608. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20609. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20610. \code{T}, but we could have just as well applied \code{map} to a tuple
  20611. of Booleans.
  20612. %
  20613. A \emph{monomorphic} function is simply one that is not generic.
  20614. %
  20615. We use the term \emph{instantiation} for the process (within the
  20616. language implementation) of turning a generic function into a
  20617. monomorphic one, where the type parameters have been replaced by
  20618. types.
  20619. {\if\edition\pythonEd\pythonColor
  20620. %
  20621. In Python, when writing a generic function such as \code{map}, one
  20622. does not explicitly write its generic type (using \code{All}).
  20623. Instead, that the function is generic is implied by the use of type
  20624. variables (such as \code{T}) in the type annotations of its
  20625. parameters.
  20626. %
  20627. \fi}
  20628. \begin{figure}[tbp]
  20629. % poly_test_2.rkt
  20630. \begin{tcolorbox}[colback=white]
  20631. {\if\edition\racketEd
  20632. \begin{lstlisting}
  20633. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20634. (define (map f v)
  20635. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20636. (define (inc [x : Integer]) : Integer (+ x 1))
  20637. (vector-ref (map inc (vector 0 41)) 1)
  20638. \end{lstlisting}
  20639. \fi}
  20640. {\if\edition\pythonEd\pythonColor
  20641. \begin{lstlisting}
  20642. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20643. return (f(tup[0]), f(tup[1]))
  20644. def add1(x : int) -> int:
  20645. return x + 1
  20646. t = map(add1, (0, 41))
  20647. print(t[1])
  20648. \end{lstlisting}
  20649. \fi}
  20650. \end{tcolorbox}
  20651. \caption{A generic version of the \code{map} function.}
  20652. \label{fig:map-poly}
  20653. \end{figure}
  20654. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20655. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20656. shows the definition of the abstract syntax.
  20657. %
  20658. {\if\edition\racketEd
  20659. We add a second form for function definitions in which a type
  20660. declaration comes before the \code{define}. In the abstract syntax,
  20661. the return type in the \code{Def} is \CANYTY{}, but that should be
  20662. ignored in favor of the return type in the type declaration. (The
  20663. \CANYTY{} comes from using the same parser as discussed in
  20664. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20665. enables the use of an \code{All} type for a function, thereby making
  20666. it generic.
  20667. \fi}
  20668. %
  20669. The grammar for types is extended to include the type of a generic
  20670. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20671. abstract syntax)}.
  20672. \newcommand{\LpolyGrammarRacket}{
  20673. \begin{array}{lcl}
  20674. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20675. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20676. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20677. \end{array}
  20678. }
  20679. \newcommand{\LpolyASTRacket}{
  20680. \begin{array}{lcl}
  20681. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20682. \Def &::=& \DECL{\Var}{\Type} \\
  20683. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20684. \end{array}
  20685. }
  20686. \newcommand{\LpolyGrammarPython}{
  20687. \begin{array}{lcl}
  20688. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20689. \end{array}
  20690. }
  20691. \newcommand{\LpolyASTPython}{
  20692. \begin{array}{lcl}
  20693. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20694. \MID \key{GenericVar}\LP\Var\RP
  20695. \end{array}
  20696. }
  20697. \begin{figure}[tp]
  20698. \centering
  20699. \begin{tcolorbox}[colback=white]
  20700. \footnotesize
  20701. {\if\edition\racketEd
  20702. \[
  20703. \begin{array}{l}
  20704. \gray{\LintGrammarRacket{}} \\ \hline
  20705. \gray{\LvarGrammarRacket{}} \\ \hline
  20706. \gray{\LifGrammarRacket{}} \\ \hline
  20707. \gray{\LwhileGrammarRacket} \\ \hline
  20708. \gray{\LtupGrammarRacket} \\ \hline
  20709. \gray{\LfunGrammarRacket} \\ \hline
  20710. \gray{\LlambdaGrammarRacket} \\ \hline
  20711. \LpolyGrammarRacket \\
  20712. \begin{array}{lcl}
  20713. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20714. \end{array}
  20715. \end{array}
  20716. \]
  20717. \fi}
  20718. {\if\edition\pythonEd\pythonColor
  20719. \[
  20720. \begin{array}{l}
  20721. \gray{\LintGrammarPython{}} \\ \hline
  20722. \gray{\LvarGrammarPython{}} \\ \hline
  20723. \gray{\LifGrammarPython{}} \\ \hline
  20724. \gray{\LwhileGrammarPython} \\ \hline
  20725. \gray{\LtupGrammarPython} \\ \hline
  20726. \gray{\LfunGrammarPython} \\ \hline
  20727. \gray{\LlambdaGrammarPython} \\\hline
  20728. \LpolyGrammarPython \\
  20729. \begin{array}{lcl}
  20730. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20731. \end{array}
  20732. \end{array}
  20733. \]
  20734. \fi}
  20735. \end{tcolorbox}
  20736. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20737. (figure~\ref{fig:Llam-concrete-syntax}).}
  20738. \label{fig:Lpoly-concrete-syntax}
  20739. \end{figure}
  20740. \begin{figure}[tp]
  20741. \centering
  20742. \begin{tcolorbox}[colback=white]
  20743. \footnotesize
  20744. {\if\edition\racketEd
  20745. \[
  20746. \begin{array}{l}
  20747. \gray{\LintOpAST} \\ \hline
  20748. \gray{\LvarASTRacket{}} \\ \hline
  20749. \gray{\LifASTRacket{}} \\ \hline
  20750. \gray{\LwhileASTRacket{}} \\ \hline
  20751. \gray{\LtupASTRacket{}} \\ \hline
  20752. \gray{\LfunASTRacket} \\ \hline
  20753. \gray{\LlambdaASTRacket} \\ \hline
  20754. \LpolyASTRacket \\
  20755. \begin{array}{lcl}
  20756. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20757. \end{array}
  20758. \end{array}
  20759. \]
  20760. \fi}
  20761. {\if\edition\pythonEd\pythonColor
  20762. \[
  20763. \begin{array}{l}
  20764. \gray{\LintASTPython} \\ \hline
  20765. \gray{\LvarASTPython{}} \\ \hline
  20766. \gray{\LifASTPython{}} \\ \hline
  20767. \gray{\LwhileASTPython{}} \\ \hline
  20768. \gray{\LtupASTPython{}} \\ \hline
  20769. \gray{\LfunASTPython} \\ \hline
  20770. \gray{\LlambdaASTPython} \\ \hline
  20771. \LpolyASTPython \\
  20772. \begin{array}{lcl}
  20773. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20774. \end{array}
  20775. \end{array}
  20776. \]
  20777. \fi}
  20778. \end{tcolorbox}
  20779. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20780. (figure~\ref{fig:Llam-syntax}).}
  20781. \label{fig:Lpoly-syntax}
  20782. \end{figure}
  20783. By including the \code{All} type in the $\Type$ nonterminal of the
  20784. grammar we choose to make generics first class, which has interesting
  20785. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20786. not include syntax for the \code{All} type. It is inferred for functions whose
  20787. type annotations contain type variables.} Many languages with generics, such as
  20788. C++~\citep{stroustrup88:_param_types} and Standard
  20789. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20790. may be helpful to see an example of first-class generics in action. In
  20791. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20792. whose parameter is a generic function. Indeed, because the grammar for
  20793. $\Type$ includes the \code{All} type, a generic function may also be
  20794. returned from a function or stored inside a tuple. The body of
  20795. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20796. and also to an integer, which would not be possible if \code{f} were
  20797. not generic.
  20798. \begin{figure}[tbp]
  20799. \begin{tcolorbox}[colback=white]
  20800. {\if\edition\racketEd
  20801. \begin{lstlisting}
  20802. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20803. (define (apply_twice f)
  20804. (if (f #t) (f 42) (f 777)))
  20805. (: id (All (T) (T -> T)))
  20806. (define (id x) x)
  20807. (apply_twice id)
  20808. \end{lstlisting}
  20809. \fi}
  20810. {\if\edition\pythonEd\pythonColor
  20811. \begin{lstlisting}
  20812. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20813. if f(True):
  20814. return f(42)
  20815. else:
  20816. return f(777)
  20817. def id(x: T) -> T:
  20818. return x
  20819. print(apply_twice(id))
  20820. \end{lstlisting}
  20821. \fi}
  20822. \end{tcolorbox}
  20823. \caption{An example illustrating first-class generics.}
  20824. \label{fig:apply-twice}
  20825. \end{figure}
  20826. The type checker for \LangPoly{} shown in
  20827. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20828. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20829. {\if\edition\pythonEd\pythonColor
  20830. %
  20831. Regarding function definitions, if the type annotations on its
  20832. parameters contain generic variables, then the function is generic and
  20833. therefore its type is an \code{All} type wrapped around a function
  20834. type. Otherwise the function is monomorphic and its type is simply
  20835. a function type.
  20836. %
  20837. \fi}
  20838. The type checking of a function application is extended to handle the
  20839. case in which the operator expression is a generic function. In that case
  20840. the type arguments are deduced by matching the types of the parameters
  20841. with the types of the arguments.
  20842. %
  20843. The \code{match\_types} auxiliary function
  20844. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20845. recursively descending through a parameter type \code{param\_ty} and
  20846. the corresponding argument type \code{arg\_ty}, making sure that they
  20847. are equal except when there is a type parameter in the parameter
  20848. type. Upon encountering a type parameter for the first time, the
  20849. algorithm deduces an association of the type parameter to the
  20850. corresponding part of the argument type. If it is not the first time
  20851. that the type parameter has been encountered, the algorithm looks up
  20852. its deduced type and makes sure that it is equal to the corresponding
  20853. part of the argument type. The return type of the application is the
  20854. return type of the generic function with the type parameters
  20855. replaced by the deduced type arguments, using the
  20856. \code{substitute\_type} auxiliary function, which is also listed in
  20857. figure~\ref{fig:type-check-Lpoly-aux}.
  20858. The type checker extends type equality to handle the \code{All} type.
  20859. This is not quite as simple as for other types, such as function and
  20860. tuple types, because two \code{All} types can be syntactically
  20861. different even though they are equivalent. For example,
  20862. \begin{center}
  20863. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20864. \end{center}
  20865. is equivalent to
  20866. \begin{center}
  20867. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20868. \end{center}
  20869. Two generic types are equal if they differ only in
  20870. the choice of the names of the type parameters. The definition of type
  20871. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20872. parameters in one type to match the type parameters of the other type.
  20873. {\if\edition\racketEd
  20874. %
  20875. The type checker also ensures that only defined type variables appear
  20876. in type annotations. The \code{check\_well\_formed} function for which
  20877. the definition is shown in figure~\ref{fig:well-formed-types}
  20878. recursively inspects a type, making sure that each type variable has
  20879. been defined.
  20880. %
  20881. \fi}
  20882. \begin{figure}[tbp]
  20883. \begin{tcolorbox}[colback=white]
  20884. {\if\edition\racketEd
  20885. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20886. (define type-check-poly-class
  20887. (class type-check-Llambda-class
  20888. (super-new)
  20889. (inherit check-type-equal?)
  20890. (define/override (type-check-apply env e1 es)
  20891. (define-values (e^ ty) ((type-check-exp env) e1))
  20892. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20893. ((type-check-exp env) e)))
  20894. (match ty
  20895. [`(,ty^* ... -> ,rt)
  20896. (for ([arg-ty ty*] [param-ty ty^*])
  20897. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20898. (values e^ es^ rt)]
  20899. [`(All ,xs (,tys ... -> ,rt))
  20900. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20901. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20902. (match_types env^^ param-ty arg-ty)))
  20903. (define targs
  20904. (for/list ([x xs])
  20905. (match (dict-ref env^^ x (lambda () #f))
  20906. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20907. x (Apply e1 es))]
  20908. [ty ty])))
  20909. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20910. [else (error 'type-check "expected a function, not ~a" ty)]))
  20911. (define/override ((type-check-exp env) e)
  20912. (match e
  20913. [(Lambda `([,xs : ,Ts] ...) rT body)
  20914. (for ([T Ts]) ((check_well_formed env) T))
  20915. ((check_well_formed env) rT)
  20916. ((super type-check-exp env) e)]
  20917. [(HasType e1 ty)
  20918. ((check_well_formed env) ty)
  20919. ((super type-check-exp env) e)]
  20920. [else ((super type-check-exp env) e)]))
  20921. (define/override ((type-check-def env) d)
  20922. (verbose 'type-check "poly/def" d)
  20923. (match d
  20924. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20925. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20926. (for ([p ps]) ((check_well_formed ts-env) p))
  20927. ((check_well_formed ts-env) rt)
  20928. (define new-env (append ts-env (map cons xs ps) env))
  20929. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20930. (check-type-equal? ty^ rt body)
  20931. (Generic ts (Def f p:t* rt info body^))]
  20932. [else ((super type-check-def env) d)]))
  20933. (define/override (type-check-program p)
  20934. (match p
  20935. [(Program info body)
  20936. (type-check-program (ProgramDefsExp info '() body))]
  20937. [(ProgramDefsExp info ds body)
  20938. (define ds^ (combine-decls-defs ds))
  20939. (define new-env (for/list ([d ds^])
  20940. (cons (def-name d) (fun-def-type d))))
  20941. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20942. (define-values (body^ ty) ((type-check-exp new-env) body))
  20943. (check-type-equal? ty 'Integer body)
  20944. (ProgramDefsExp info ds^^ body^)]))
  20945. ))
  20946. \end{lstlisting}
  20947. \fi}
  20948. {\if\edition\pythonEd\pythonColor
  20949. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20950. def type_check_exp(self, e, env):
  20951. match e:
  20952. case Call(Name(f), args) if f in builtin_functions:
  20953. return super().type_check_exp(e, env)
  20954. case Call(func, args):
  20955. func_t = self.type_check_exp(func, env)
  20956. func.has_type = func_t
  20957. match func_t:
  20958. case AllType(ps, FunctionType(p_tys, rt)):
  20959. for arg in args:
  20960. arg.has_type = self.type_check_exp(arg, env)
  20961. arg_tys = [arg.has_type for arg in args]
  20962. deduced = {}
  20963. for (p, a) in zip(p_tys, arg_tys):
  20964. self.match_types(p, a, deduced, e)
  20965. return self.substitute_type(rt, deduced)
  20966. case _:
  20967. return super().type_check_exp(e, env)
  20968. case _:
  20969. return super().type_check_exp(e, env)
  20970. def type_check(self, p):
  20971. match p:
  20972. case Module(body):
  20973. env = {}
  20974. for s in body:
  20975. match s:
  20976. case FunctionDef(name, params, bod, dl, returns, comment):
  20977. params_t = [t for (x,t) in params]
  20978. ty_params = set()
  20979. for t in params_t:
  20980. ty_params |$\mid$|= self.generic_variables(t)
  20981. ty = FunctionType(params_t, returns)
  20982. if len(ty_params) > 0:
  20983. ty = AllType(list(ty_params), ty)
  20984. env[name] = ty
  20985. self.check_stmts(body, IntType(), env)
  20986. case _:
  20987. raise Exception('type_check: unexpected ' + repr(p))
  20988. \end{lstlisting}
  20989. \fi}
  20990. \end{tcolorbox}
  20991. \caption{Type checker for the \LangPoly{} language.}
  20992. \label{fig:type-check-Lpoly}
  20993. \end{figure}
  20994. \begin{figure}[tbp]
  20995. \begin{tcolorbox}[colback=white]
  20996. {\if\edition\racketEd
  20997. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20998. (define/override (type-equal? t1 t2)
  20999. (match* (t1 t2)
  21000. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21001. (define env (map cons xs ys))
  21002. (type-equal? (substitute_type env T1) T2)]
  21003. [(other wise)
  21004. (super type-equal? t1 t2)]))
  21005. (define/public (match_types env pt at)
  21006. (match* (pt at)
  21007. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21008. [('Void 'Void) env] [('Any 'Any) env]
  21009. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21010. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21011. (match_types env^ pt1 at1))]
  21012. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21013. (define env^ (match_types env prt art))
  21014. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21015. (match_types env^^ pt1 at1))]
  21016. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21017. (define env^ (append (map cons pxs axs) env))
  21018. (match_types env^ pt1 at1)]
  21019. [((? symbol? x) at)
  21020. (match (dict-ref env x (lambda () #f))
  21021. [#f (error 'type-check "undefined type variable ~a" x)]
  21022. ['Type (cons (cons x at) env)]
  21023. [t^ (check-type-equal? at t^ 'matching) env])]
  21024. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21025. (define/public (substitute_type env pt)
  21026. (match pt
  21027. ['Integer 'Integer] ['Boolean 'Boolean]
  21028. ['Void 'Void] ['Any 'Any]
  21029. [`(Vector ,ts ...)
  21030. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21031. [`(,ts ... -> ,rt)
  21032. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21033. [`(All ,xs ,t)
  21034. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21035. [(? symbol? x) (dict-ref env x)]
  21036. [else (error 'type-check "expected a type not ~a" pt)]))
  21037. (define/public (combine-decls-defs ds)
  21038. (match ds
  21039. ['() '()]
  21040. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21041. (unless (equal? name f)
  21042. (error 'type-check "name mismatch, ~a != ~a" name f))
  21043. (match type
  21044. [`(All ,xs (,ps ... -> ,rt))
  21045. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21046. (cons (Generic xs (Def name params^ rt info body))
  21047. (combine-decls-defs ds^))]
  21048. [`(,ps ... -> ,rt)
  21049. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21050. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21051. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21052. [`(,(Def f params rt info body) . ,ds^)
  21053. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21054. \end{lstlisting}
  21055. \fi}
  21056. {\if\edition\pythonEd\pythonColor
  21057. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21058. def match_types(self, param_ty, arg_ty, deduced, e):
  21059. match (param_ty, arg_ty):
  21060. case (GenericVar(id), _):
  21061. if id in deduced:
  21062. self.check_type_equal(arg_ty, deduced[id], e)
  21063. else:
  21064. deduced[id] = arg_ty
  21065. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21066. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21067. new_arg_ty = self.substitute_type(arg_ty, rename)
  21068. self.match_types(ty, new_arg_ty, deduced, e)
  21069. case (TupleType(ps), TupleType(ts)):
  21070. for (p, a) in zip(ps, ts):
  21071. self.match_types(p, a, deduced, e)
  21072. case (ListType(p), ListType(a)):
  21073. self.match_types(p, a, deduced, e)
  21074. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21075. for (pp, ap) in zip(pps, aps):
  21076. self.match_types(pp, ap, deduced, e)
  21077. self.match_types(prt, art, deduced, e)
  21078. case (IntType(), IntType()):
  21079. pass
  21080. case (BoolType(), BoolType()):
  21081. pass
  21082. case _:
  21083. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21084. def substitute_type(self, ty, var_map):
  21085. match ty:
  21086. case GenericVar(id):
  21087. return var_map[id]
  21088. case AllType(ps, ty):
  21089. new_map = copy.deepcopy(var_map)
  21090. for p in ps:
  21091. new_map[p] = GenericVar(p)
  21092. return AllType(ps, self.substitute_type(ty, new_map))
  21093. case TupleType(ts):
  21094. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21095. case ListType(ty):
  21096. return ListType(self.substitute_type(ty, var_map))
  21097. case FunctionType(pts, rt):
  21098. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21099. self.substitute_type(rt, var_map))
  21100. case IntType():
  21101. return IntType()
  21102. case BoolType():
  21103. return BoolType()
  21104. case _:
  21105. raise Exception('substitute_type: unexpected ' + repr(ty))
  21106. def check_type_equal(self, t1, t2, e):
  21107. match (t1, t2):
  21108. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21109. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21110. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21111. case (_, _):
  21112. return super().check_type_equal(t1, t2, e)
  21113. \end{lstlisting}
  21114. \fi}
  21115. \end{tcolorbox}
  21116. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21117. \label{fig:type-check-Lpoly-aux}
  21118. \end{figure}
  21119. {\if\edition\racketEd
  21120. \begin{figure}[tbp]
  21121. \begin{tcolorbox}[colback=white]
  21122. \begin{lstlisting}
  21123. (define/public ((check_well_formed env) ty)
  21124. (match ty
  21125. ['Integer (void)]
  21126. ['Boolean (void)]
  21127. ['Void (void)]
  21128. [(? symbol? a)
  21129. (match (dict-ref env a (lambda () #f))
  21130. ['Type (void)]
  21131. [else (error 'type-check "undefined type variable ~a" a)])]
  21132. [`(Vector ,ts ...)
  21133. (for ([t ts]) ((check_well_formed env) t))]
  21134. [`(,ts ... -> ,t)
  21135. (for ([t ts]) ((check_well_formed env) t))
  21136. ((check_well_formed env) t)]
  21137. [`(All ,xs ,t)
  21138. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21139. ((check_well_formed env^) t)]
  21140. [else (error 'type-check "unrecognized type ~a" ty)]))
  21141. \end{lstlisting}
  21142. \end{tcolorbox}
  21143. \caption{Well-formed types.}
  21144. \label{fig:well-formed-types}
  21145. \end{figure}
  21146. \fi}
  21147. % TODO: interpreter for R'_10
  21148. \clearpage
  21149. \section{Compiling Generics}
  21150. \label{sec:compiling-poly}
  21151. Broadly speaking, there are four approaches to compiling generics, as
  21152. follows:
  21153. \begin{description}
  21154. \item[Monomorphization] generates a different version of a generic
  21155. function for each set of type arguments with which it is used,
  21156. producing type-specialized code. This approach results in the most
  21157. efficient code but requires whole-program compilation (no separate
  21158. compilation) and may increase code size. Unfortunately,
  21159. monomorphization is incompatible with first-class generics because
  21160. it is not always possible to determine which generic functions are
  21161. used with which type arguments during compilation. (It can be done
  21162. at runtime with just-in-time compilation.) Monomorphization is
  21163. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21164. generic functions in NESL~\citep{Blelloch:1993aa} and
  21165. ML~\citep{Weeks:2006aa}.
  21166. \item[Uniform representation] generates one version of each generic
  21167. function and requires all values to have a common \emph{boxed} format,
  21168. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21169. generic and monomorphic code is compiled similarly to code in a
  21170. dynamically typed language (like \LangDyn{}), in which primitive
  21171. operators require their arguments to be projected from \CANYTY{} and
  21172. their results to be injected into \CANYTY{}. (In object-oriented
  21173. languages, the projection is accomplished via virtual method
  21174. dispatch.) The uniform representation approach is compatible with
  21175. separate compilation and with first-class generics. However, it
  21176. produces the least efficient code because it introduces overhead in
  21177. the entire program. This approach is used in
  21178. Java~\citep{Bracha:1998fk},
  21179. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21180. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21181. \item[Mixed representation] generates one version of each generic
  21182. function, using a boxed representation for type variables. However,
  21183. monomorphic code is compiled as usual (as in \LangLam{}), and
  21184. conversions are performed at the boundaries between monomorphic code
  21185. and polymorphic code (for example, when a generic function is instantiated
  21186. and called). This approach is compatible with separate compilation
  21187. and first-class generics and maintains efficiency in monomorphic
  21188. code. The trade-off is increased overhead at the boundary between
  21189. monomorphic and generic code. This approach is used in
  21190. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21191. Java 5 with the addition of autoboxing.
  21192. \item[Type passing] uses the unboxed representation in both
  21193. monomorphic and generic code. Each generic function is compiled to a
  21194. single function with extra parameters that describe the type
  21195. arguments. The type information is used by the generated code to
  21196. determine how to access the unboxed values at runtime. This approach is
  21197. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21198. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21199. compilation and first-class generics and maintains the
  21200. efficiency for monomorphic code. There is runtime overhead in
  21201. polymorphic code from dispatching on type information.
  21202. \end{description}
  21203. In this chapter we use the mixed representation approach, partly
  21204. because of its favorable attributes and partly because it is
  21205. straightforward to implement using the tools that we have already
  21206. built to support gradual typing. The work of compiling generic
  21207. functions is performed in two passes, \code{resolve} and
  21208. \code{erase\_types}, that we discuss next. The output of
  21209. \code{erase\_types} is \LangCast{}
  21210. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21211. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21212. \section{Resolve Instantiation}
  21213. \label{sec:generic-resolve}
  21214. Recall that the type checker for \LangPoly{} deduces the type
  21215. arguments at call sites to a generic function. The purpose of the
  21216. \code{resolve} pass is to turn this implicit instantiation into an
  21217. explicit one, by adding \code{inst} nodes to the syntax of the
  21218. intermediate language. An \code{inst} node records the mapping of
  21219. type parameters to type arguments. The semantics of the \code{inst}
  21220. node is to instantiate the result of its first argument, a generic
  21221. function, to produce a monomorphic function. However, because the
  21222. interpreter never analyzes type annotations, instantiation can be a
  21223. no-op and simply return the generic function.
  21224. %
  21225. The output language of the \code{resolve} pass is \LangInst{},
  21226. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21227. {\if\edition\racketEd
  21228. The \code{resolve} pass combines the type declaration and polymorphic
  21229. function into a single definition, using the \code{Poly} form, to make
  21230. polymorphic functions more convenient to process in the next pass of the
  21231. compiler.
  21232. \fi}
  21233. \newcommand{\LinstASTRacket}{
  21234. \begin{array}{lcl}
  21235. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21236. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21237. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21238. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21239. \end{array}
  21240. }
  21241. \newcommand{\LinstASTPython}{
  21242. \begin{array}{lcl}
  21243. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21244. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21245. \end{array}
  21246. }
  21247. \begin{figure}[tp]
  21248. \centering
  21249. \begin{tcolorbox}[colback=white]
  21250. \small
  21251. {\if\edition\racketEd
  21252. \[
  21253. \begin{array}{l}
  21254. \gray{\LintOpAST} \\ \hline
  21255. \gray{\LvarASTRacket{}} \\ \hline
  21256. \gray{\LifASTRacket{}} \\ \hline
  21257. \gray{\LwhileASTRacket{}} \\ \hline
  21258. \gray{\LtupASTRacket{}} \\ \hline
  21259. \gray{\LfunASTRacket} \\ \hline
  21260. \gray{\LlambdaASTRacket} \\ \hline
  21261. \LinstASTRacket \\
  21262. \begin{array}{lcl}
  21263. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21264. \end{array}
  21265. \end{array}
  21266. \]
  21267. \fi}
  21268. {\if\edition\pythonEd\pythonColor
  21269. \[
  21270. \begin{array}{l}
  21271. \gray{\LintASTPython} \\ \hline
  21272. \gray{\LvarASTPython{}} \\ \hline
  21273. \gray{\LifASTPython{}} \\ \hline
  21274. \gray{\LwhileASTPython{}} \\ \hline
  21275. \gray{\LtupASTPython{}} \\ \hline
  21276. \gray{\LfunASTPython} \\ \hline
  21277. \gray{\LlambdaASTPython} \\ \hline
  21278. \LinstASTPython \\
  21279. \begin{array}{lcl}
  21280. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21281. \end{array}
  21282. \end{array}
  21283. \]
  21284. \fi}
  21285. \end{tcolorbox}
  21286. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21287. (figure~\ref{fig:Llam-syntax}).}
  21288. \label{fig:Lpoly-prime-syntax}
  21289. \end{figure}
  21290. The output of the \code{resolve} pass on the generic \code{map}
  21291. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21292. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21293. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21294. \begin{figure}[tbp]
  21295. % poly_test_2.rkt
  21296. \begin{tcolorbox}[colback=white]
  21297. {\if\edition\racketEd
  21298. \begin{lstlisting}
  21299. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21300. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21301. (define (inc [x : Integer]) : Integer (+ x 1))
  21302. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21303. (Integer))
  21304. inc (vector 0 41)) 1)
  21305. \end{lstlisting}
  21306. \fi}
  21307. {\if\edition\pythonEd\pythonColor
  21308. \begin{lstlisting}
  21309. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21310. return (f(tup[0]), f(tup[1]))
  21311. def add1(x : int) -> int:
  21312. return x + 1
  21313. t = inst(map, {T: int})(add1, (0, 41))
  21314. print(t[1])
  21315. \end{lstlisting}
  21316. \fi}
  21317. \end{tcolorbox}
  21318. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21319. \label{fig:map-resolve}
  21320. \end{figure}
  21321. \section{Erase Generic Types}
  21322. \label{sec:erase_types}
  21323. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21324. represent type variables. For example, figure~\ref{fig:map-erase}
  21325. shows the output of the \code{erase\_types} pass on the generic
  21326. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21327. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21328. \code{All} types are removed from the type of \code{map}.
  21329. \begin{figure}[tbp]
  21330. \begin{tcolorbox}[colback=white]
  21331. {\if\edition\racketEd
  21332. \begin{lstlisting}
  21333. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21334. : (Vector Any Any)
  21335. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21336. (define (inc [x : Integer]) : Integer (+ x 1))
  21337. (vector-ref ((cast map
  21338. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21339. ((Integer -> Integer) (Vector Integer Integer)
  21340. -> (Vector Integer Integer)))
  21341. inc (vector 0 41)) 1)
  21342. \end{lstlisting}
  21343. \fi}
  21344. {\if\edition\pythonEd\pythonColor
  21345. \begin{lstlisting}
  21346. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21347. return (f(tup[0]), f(tup[1]))
  21348. def add1(x : int) -> int:
  21349. return (x + 1)
  21350. def main() -> int:
  21351. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21352. print(t[1])
  21353. return 0
  21354. \end{lstlisting}
  21355. {\small
  21356. where\\
  21357. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21358. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21359. }
  21360. \fi}
  21361. \end{tcolorbox}
  21362. \caption{The generic \code{map} example after type erasure.}
  21363. \label{fig:map-erase}
  21364. \end{figure}
  21365. This process of type erasure creates a challenge at points of
  21366. instantiation. For example, consider the instantiation of
  21367. \code{map} shown in figure~\ref{fig:map-resolve}.
  21368. The type of \code{map} is
  21369. %
  21370. {\if\edition\racketEd
  21371. \begin{lstlisting}
  21372. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21373. \end{lstlisting}
  21374. \fi}
  21375. {\if\edition\pythonEd\pythonColor
  21376. \begin{lstlisting}
  21377. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21378. \end{lstlisting}
  21379. \fi}
  21380. %
  21381. and it is instantiated to
  21382. %
  21383. {\if\edition\racketEd
  21384. \begin{lstlisting}
  21385. ((Integer -> Integer) (Vector Integer Integer)
  21386. -> (Vector Integer Integer))
  21387. \end{lstlisting}
  21388. \fi}
  21389. {\if\edition\pythonEd\pythonColor
  21390. \begin{lstlisting}
  21391. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21392. \end{lstlisting}
  21393. \fi}
  21394. %
  21395. After erasure, the type of \code{map} is
  21396. %
  21397. {\if\edition\racketEd
  21398. \begin{lstlisting}
  21399. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21400. \end{lstlisting}
  21401. \fi}
  21402. {\if\edition\pythonEd\pythonColor
  21403. \begin{lstlisting}
  21404. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21405. \end{lstlisting}
  21406. \fi}
  21407. %
  21408. but we need to convert it to the instantiated type. This is easy to
  21409. do in the language \LangCast{} with a single \code{cast}. In the
  21410. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21411. \code{map} has been compiled to a \code{cast} from the type of
  21412. \code{map} to the instantiated type. The source and the target type of a
  21413. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21414. the case because both the source and target are obtained from the same
  21415. generic type of \code{map}, replacing the type parameters with
  21416. \CANYTY{} in the former and with the deduced type arguments in the
  21417. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21418. To implement the \code{erase\_types} pass, we first recommend defining
  21419. a recursive function that translates types, named
  21420. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21421. follows.
  21422. %
  21423. {\if\edition\racketEd
  21424. \begin{lstlisting}
  21425. |$T$|
  21426. |$\Rightarrow$|
  21427. Any
  21428. \end{lstlisting}
  21429. \fi}
  21430. {\if\edition\pythonEd\pythonColor
  21431. \begin{lstlisting}
  21432. GenericVar(|$T$|)
  21433. |$\Rightarrow$|
  21434. Any
  21435. \end{lstlisting}
  21436. \fi}
  21437. %
  21438. \noindent The \code{erase\_type} function also removes the generic
  21439. \code{All} types.
  21440. %
  21441. {\if\edition\racketEd
  21442. \begin{lstlisting}
  21443. (All |$xs$| |$T_1$|)
  21444. |$\Rightarrow$|
  21445. |$T'_1$|
  21446. \end{lstlisting}
  21447. \fi}
  21448. {\if\edition\pythonEd\pythonColor
  21449. \begin{lstlisting}
  21450. AllType(|$xs$|, |$T_1$|)
  21451. |$\Rightarrow$|
  21452. |$T'_1$|
  21453. \end{lstlisting}
  21454. \fi}
  21455. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21456. %
  21457. In this compiler pass, apply the \code{erase\_type} function to all
  21458. the type annotations in the program.
  21459. Regarding the translation of expressions, the case for \code{Inst} is
  21460. the interesting one. We translate it into a \code{Cast}, as shown
  21461. next.
  21462. The type of the subexpression $e$ is a generic type of the form
  21463. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21464. The source type of the cast is the erasure of $T$, the type $T_s$.
  21465. %
  21466. {\if\edition\racketEd
  21467. %
  21468. The target type $T_t$ is the result of substituting the argument types
  21469. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21470. erasure.
  21471. %
  21472. \begin{lstlisting}
  21473. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21474. |$\Rightarrow$|
  21475. (Cast |$e'$| |$T_s$| |$T_t$|)
  21476. \end{lstlisting}
  21477. %
  21478. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21479. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21480. \fi}
  21481. {\if\edition\pythonEd\pythonColor
  21482. %
  21483. The target type $T_t$ is the result of substituting the deduced
  21484. argument types $d$ in $T$ and then performing type erasure.
  21485. %
  21486. \begin{lstlisting}
  21487. Inst(|$e$|, |$d$|)
  21488. |$\Rightarrow$|
  21489. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21490. \end{lstlisting}
  21491. %
  21492. where
  21493. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21494. \fi}
  21495. Finally, each generic function is translated to a regular
  21496. function in which type erasure has been applied to all the type
  21497. annotations and the body.
  21498. %% \begin{lstlisting}
  21499. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21500. %% |$\Rightarrow$|
  21501. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21502. %% \end{lstlisting}
  21503. \begin{exercise}\normalfont\normalsize
  21504. Implement a compiler for the polymorphic language \LangPoly{} by
  21505. extending and adapting your compiler for \LangGrad{}. Create six new
  21506. test programs that use polymorphic functions. Some of them should
  21507. make use of first-class generics.
  21508. \end{exercise}
  21509. \begin{figure}[tbp]
  21510. \begin{tcolorbox}[colback=white]
  21511. {\if\edition\racketEd
  21512. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21513. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21514. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21515. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21516. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21517. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21518. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21519. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21520. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21521. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21522. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21523. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21524. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21525. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21526. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21527. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21528. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21529. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21530. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21531. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21532. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21533. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21534. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21535. \path[->,bend left=15] (Lpoly) edge [above] node
  21536. {\ttfamily\footnotesize resolve} (Lpolyp);
  21537. \path[->,bend left=15] (Lpolyp) edge [above] node
  21538. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21539. \path[->,bend left=15] (Lgradualp) edge [above] node
  21540. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21541. \path[->,bend left=15] (Llambdapp) edge [left] node
  21542. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21543. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21544. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21545. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21546. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21547. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21548. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21549. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21550. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21551. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21552. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21553. \path[->,bend left=15] (F1-1) edge [above] node
  21554. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21555. \path[->,bend left=15] (F1-2) edge [above] node
  21556. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21557. \path[->,bend left=15] (F1-3) edge [left] node
  21558. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21559. \path[->,bend left=15] (F1-4) edge [below] node
  21560. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21561. \path[->,bend right=15] (F1-5) edge [above] node
  21562. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21563. \path[->,bend right=15] (F1-6) edge [above] node
  21564. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21565. \path[->,bend right=15] (C3-2) edge [right] node
  21566. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21567. \path[->,bend right=15] (x86-2) edge [right] node
  21568. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21569. \path[->,bend right=15] (x86-2-1) edge [below] node
  21570. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21571. \path[->,bend right=15] (x86-2-2) edge [right] node
  21572. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21573. \path[->,bend left=15] (x86-3) edge [above] node
  21574. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21575. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21576. \end{tikzpicture}
  21577. \fi}
  21578. {\if\edition\pythonEd\pythonColor
  21579. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21580. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21581. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21582. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21583. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21584. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21585. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21586. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21587. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21588. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21589. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21590. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21591. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21592. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21593. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21594. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21595. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21596. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21597. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21598. \path[->,bend left=15] (Lgradual) edge [above] node
  21599. {\ttfamily\footnotesize shrink} (Lgradual2);
  21600. \path[->,bend left=15] (Lgradual2) edge [above] node
  21601. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21602. \path[->,bend left=15] (Lgradual3) edge [above] node
  21603. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21604. \path[->,bend left=15] (Lgradual4) edge [left] node
  21605. {\ttfamily\footnotesize resolve} (Lgradualr);
  21606. \path[->,bend left=15] (Lgradualr) edge [below] node
  21607. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21608. \path[->,bend right=15] (Llambdapp) edge [above] node
  21609. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21610. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21611. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21612. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21613. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21614. \path[->,bend right=15] (F1-1) edge [below] node
  21615. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21616. \path[->,bend right=15] (F1-2) edge [below] node
  21617. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21618. \path[->,bend left=15] (F1-3) edge [above] node
  21619. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21620. \path[->,bend left=15] (F1-5) edge [left] node
  21621. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21622. \path[->,bend left=5] (F1-6) edge [below] node
  21623. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21624. \path[->,bend right=15] (C3-2) edge [right] node
  21625. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21626. \path[->,bend right=15] (x86-2) edge [below] node
  21627. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21628. \path[->,bend right=15] (x86-3) edge [below] node
  21629. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21630. \path[->,bend left=15] (x86-4) edge [above] node
  21631. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21632. \end{tikzpicture}
  21633. \fi}
  21634. \end{tcolorbox}
  21635. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21636. \label{fig:Lpoly-passes}
  21637. \end{figure}
  21638. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21639. needed to compile \LangPoly{}.
  21640. % TODO: challenge problem: specialization of instantiations
  21641. % Further Reading
  21642. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21643. \clearpage
  21644. \appendix
  21645. \chapter{Appendix}
  21646. \setcounter{footnote}{0}
  21647. {\if\edition\racketEd
  21648. \section{Interpreters}
  21649. \label{appendix:interp}
  21650. \index{subject}{interpreter}
  21651. We provide interpreters for each of the source languages \LangInt{},
  21652. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21653. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21654. intermediate languages \LangCVar{} and \LangCIf{} are in
  21655. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21656. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21657. \key{interp.rkt} file.
  21658. \section{Utility Functions}
  21659. \label{appendix:utilities}
  21660. The utility functions described in this section are in the
  21661. \key{utilities.rkt} file of the support code.
  21662. \paragraph{\code{interp-tests}}
  21663. This function runs the compiler passes and the interpreters on each of
  21664. the specified tests to check whether each pass is correct. The
  21665. \key{interp-tests} function has the following parameters:
  21666. \begin{description}
  21667. \item[name (a string)] A name to identify the compiler.
  21668. \item[typechecker] A function of exactly one argument that either
  21669. raises an error using the \code{error} function when it encounters a
  21670. type error, or returns \code{\#f} when it encounters a type
  21671. error. If there is no type error, the type checker returns the
  21672. program.
  21673. \item[passes] A list with one entry per pass. An entry is a list
  21674. consisting of four things:
  21675. \begin{enumerate}
  21676. \item a string giving the name of the pass;
  21677. \item the function that implements the pass (a translator from AST
  21678. to AST);
  21679. \item a function that implements the interpreter (a function from
  21680. AST to result value) for the output language; and,
  21681. \item a type checker for the output language. Type checkers for
  21682. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21683. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21684. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21685. type checker entry is optional. The support code does not provide
  21686. type checkers for the x86 languages.
  21687. \end{enumerate}
  21688. \item[source-interp] An interpreter for the source language. The
  21689. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21690. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21691. \item[tests] A list of test numbers that specifies which tests to
  21692. run (explained next).
  21693. \end{description}
  21694. %
  21695. The \key{interp-tests} function assumes that the subdirectory
  21696. \key{tests} has a collection of Racket programs whose names all start
  21697. with the family name, followed by an underscore and then the test
  21698. number, and ending with the file extension \key{.rkt}. Also, for each test
  21699. program that calls \code{read} one or more times, there is a file with
  21700. the same name except that the file extension is \key{.in}, which
  21701. provides the input for the Racket program. If the test program is
  21702. expected to fail type checking, then there should be an empty file of
  21703. the same name with extension \key{.tyerr}.
  21704. \paragraph{\code{compiler-tests}}
  21705. This function runs the compiler passes to generate x86 (a \key{.s}
  21706. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21707. It runs the machine code and checks that the output is $42$. The
  21708. parameters to the \code{compiler-tests} function are similar to those
  21709. of the \code{interp-tests} function, and they consist of
  21710. \begin{itemize}
  21711. \item a compiler name (a string),
  21712. \item a type checker,
  21713. \item description of the passes,
  21714. \item name of a test-family, and
  21715. \item a list of test numbers.
  21716. \end{itemize}
  21717. \paragraph{\code{compile-file}}
  21718. This function takes a description of the compiler passes (see the
  21719. comment for \key{interp-tests}) and returns a function that, given a
  21720. program file name (a string ending in \key{.rkt}), applies all the
  21721. passes and writes the output to a file whose name is the same as the
  21722. program file name with extension \key{.rkt} replaced by \key{.s}.
  21723. \paragraph{\code{read-program}}
  21724. This function takes a file path and parses that file (it must be a
  21725. Racket program) into an abstract syntax tree.
  21726. \paragraph{\code{parse-program}}
  21727. This function takes an S-expression representation of an abstract
  21728. syntax tree and converts it into the struct-based representation.
  21729. \paragraph{\code{assert}}
  21730. This function takes two parameters, a string (\code{msg}) and Boolean
  21731. (\code{bool}), and displays the message \key{msg} if the Boolean
  21732. \key{bool} is false.
  21733. \paragraph{\code{lookup}}
  21734. % remove discussion of lookup? -Jeremy
  21735. This function takes a key and an alist and returns the first value that is
  21736. associated with the given key, if there is one. If not, an error is
  21737. triggered. The alist may contain both immutable pairs (built with
  21738. \key{cons}) and mutable pairs (built with \key{mcons}).
  21739. %The \key{map2} function ...
  21740. \fi} %\racketEd
  21741. \section{x86 Instruction Set Quick Reference}
  21742. \label{sec:x86-quick-reference}
  21743. \index{subject}{x86}
  21744. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21745. do. We write $A \to B$ to mean that the value of $A$ is written into
  21746. location $B$. Address offsets are given in bytes. The instruction
  21747. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21748. registers (such as \code{\%rax}), or memory references (such as
  21749. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21750. reference per instruction. Other operands must be immediates or
  21751. registers.
  21752. \begin{table}[tbp]
  21753. \centering
  21754. \begin{tabular}{l|l}
  21755. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21756. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21757. \texttt{negq} $A$ & $- A \to A$ \\
  21758. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21759. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21760. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21761. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21762. \texttt{retq} & Pops the return address and jumps to it. \\
  21763. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21764. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21765. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21766. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21767. be an immediate). \\
  21768. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21769. matches the condition code of the instruction; otherwise go to the
  21770. next instructions. The condition codes are \key{e} for \emph{equal},
  21771. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21772. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21773. \texttt{jl} $L$ & \\
  21774. \texttt{jle} $L$ & \\
  21775. \texttt{jg} $L$ & \\
  21776. \texttt{jge} $L$ & \\
  21777. \texttt{jmp} $L$ & Jump to label $L$. \\
  21778. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21779. \texttt{movzbq} $A$, $B$ &
  21780. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21781. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21782. and the extra bytes of $B$ are set to zero.} \\
  21783. & \\
  21784. & \\
  21785. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21786. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21787. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21788. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21789. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21790. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21791. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21792. description of the condition codes. $A$ must be a single byte register
  21793. (e.g., \texttt{al} or \texttt{cl}).} \\
  21794. \texttt{setl} $A$ & \\
  21795. \texttt{setle} $A$ & \\
  21796. \texttt{setg} $A$ & \\
  21797. \texttt{setge} $A$ &
  21798. \end{tabular}
  21799. \vspace{5pt}
  21800. \caption{Quick reference for the x86 instructions used in this book.}
  21801. \label{tab:x86-instr}
  21802. \end{table}
  21803. \backmatter
  21804. \addtocontents{toc}{\vspace{11pt}}
  21805. \cleardoublepage % needed for right page number in TOC for References
  21806. %% \nocite{*} is a way to get all the entries in the .bib file to
  21807. %% print in the bibliography:
  21808. \nocite{*}\let\bibname\refname
  21809. \addcontentsline{toc}{fmbm}{\refname}
  21810. \printbibliography
  21811. %\printindex{authors}{Author Index}
  21812. \printindex{subject}{Index}
  21813. \end{document}
  21814. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21815. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21816. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21817. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21818. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21819. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21820. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21821. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21822. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21823. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21824. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21825. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21826. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21827. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21828. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21829. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21830. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21831. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21832. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21833. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21834. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21835. % LocalWords: eq prog rcl definitional Evaluator os
  21836. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21837. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21838. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21839. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21840. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21841. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21842. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21843. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21844. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21845. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21846. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21847. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21848. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21849. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21850. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21851. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21852. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21853. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21854. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21855. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21856. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21857. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21858. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21859. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21860. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21861. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21862. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21863. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21864. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21865. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21866. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21867. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21868. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21869. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21870. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21871. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21872. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21873. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21874. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21875. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21876. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21877. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21878. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21879. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21880. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21881. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21882. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21883. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21884. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21885. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21886. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21887. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21888. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21889. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21890. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21891. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21892. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21893. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21894. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21895. % LocalWords: pseudocode underapproximation underapproximations LALR
  21896. % LocalWords: semilattices overapproximate incrementing Earley docs
  21897. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21898. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21899. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21900. % LocalWords: LC partialevaluation pythonEd TOC TrappedError