book.tex 828 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784
  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{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. %% For multiple indices:
  35. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  36. \makeindex{subject}
  37. %\makeindex{authors}
  38. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  39. \if\edition\racketEd
  40. \lstset{%
  41. language=Lisp,
  42. basicstyle=\ttfamily\small,
  43. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  44. deletekeywords={read,mapping,vector},
  45. escapechar=|,
  46. columns=flexible,
  47. %moredelim=[is][\color{red}]{~}{~},
  48. showstringspaces=false
  49. }
  50. \fi
  51. \if\edition\pythonEd
  52. \lstset{%
  53. language=Python,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={match,case,bool,int,let,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. Library of Congress Cataloging-in-Publication Data\\
  118. \ \\
  119. Names: Siek, Jeremy, author. \\
  120. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  121. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  122. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  123. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  124. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  125. LC record available at https://lccn.loc.gov/2022015399\\
  126. LC ebook record available at https://lccn.loc.gov/2022015400\\
  127. \ \\
  128. 10 9 8 7 6 5 4 3 2 1
  129. %% Jeremy G. Siek. Available for free viewing
  130. %% or personal downloading under the
  131. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  132. %% license.
  133. %% Copyright in this monograph has been licensed exclusively to The MIT
  134. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  135. %% version to the public in 2022. All inquiries regarding rights should
  136. %% be addressed to The MIT Press, Rights and Permissions Department.
  137. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  138. %% All rights reserved. No part of this book may be reproduced in any
  139. %% form by any electronic or mechanical means (including photocopying,
  140. %% recording, or information storage and retrieval) without permission in
  141. %% writing from the publisher.
  142. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  143. %% United States of America.
  144. %% Library of Congress Cataloging-in-Publication Data is available.
  145. %% ISBN:
  146. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  147. \end{copyrightpage}
  148. \dedication{This book is dedicated to Katie, my partner in everything,
  149. my children, who grew up during the writing of this book, and the
  150. programming language students at Indiana University, whose
  151. thoughtful questions made this a better book.}
  152. %% \begin{epigraphpage}
  153. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  154. %% \textit{Book Name if any}}
  155. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  156. %% \end{epigraphpage}
  157. \tableofcontents
  158. %\listoffigures
  159. %\listoftables
  160. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  161. \chapter*{Preface}
  162. \addcontentsline{toc}{fmbm}{Preface}
  163. There is a magical moment when a programmer presses the \emph{run}
  164. button and the software begins to execute. Somehow a program written
  165. in a high-level language is running on a computer that is capable only
  166. of shuffling bits. Here we reveal the wizardry that makes that moment
  167. possible. Beginning with the groundbreaking work of Backus and
  168. colleagues in the 1950s, computer scientists developed techniques for
  169. constructing programs called \emph{compilers} that automatically
  170. translate high-level programs into machine code.
  171. We take you on a journey through constructing your own compiler for a
  172. small but powerful language. Along the way we explain the essential
  173. concepts, algorithms, and data structures that underlie compilers. We
  174. develop your understanding of how programs are mapped onto computer
  175. hardware, which is helpful in reasoning about properties at the
  176. junction of hardware and software, such as execution time, software
  177. errors, and security vulnerabilities. For those interested in
  178. pursuing compiler construction as a career, our goal is to provide a
  179. stepping-stone to advanced topics such as just-in-time compilation,
  180. program analysis, and program optimization. For those interested in
  181. designing and implementing programming languages, we connect language
  182. design choices to their impact on the compiler and the generated code.
  183. A compiler is typically organized as a sequence of stages that
  184. progressively translate a program to the code that runs on
  185. hardware. We take this approach to the extreme by partitioning our
  186. compiler into a large number of \emph{nanopasses}, each of which
  187. performs a single task. This enables the testing of each pass in
  188. isolation and focuses our attention, making the compiler far easier to
  189. understand.
  190. The most familiar approach to describing compilers is to dedicate each
  191. chapter to one pass. The problem with that approach is that it
  192. obfuscates how language features motivate design choices in a
  193. compiler. We instead take an \emph{incremental} approach in which we
  194. build a complete compiler in each chapter, starting with a small input
  195. language that includes only arithmetic and variables. We add new
  196. language features in subsequent chapters, extending the compiler as
  197. necessary.
  198. Our choice of language features is designed to elicit fundamental
  199. concepts and algorithms used in compilers.
  200. \begin{itemize}
  201. \item We begin with integer arithmetic and local variables in
  202. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  203. the fundamental tools of compiler construction: \emph{abstract
  204. syntax trees} and \emph{recursive functions}.
  205. {\if\edition\pythonEd\pythonColor
  206. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  207. parser framework to create a parser for the language of integer
  208. arithmetic and local variables. We learn about the parsing
  209. algorithms inside Lark, including Earley and LALR(1).
  210. %
  211. \fi}
  212. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  213. \emph{graph coloring} to assign variables to machine registers.
  214. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  215. motivates an elegant recursive algorithm for translating them into
  216. conditional \code{goto} statements.
  217. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  218. variables}. This elicits the need for \emph{dataflow
  219. analysis} in the register allocator.
  220. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  221. \emph{garbage collection}.
  222. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  223. without lexical scoping, similar to functions in the C programming
  224. language~\citep{Kernighan:1988nx}. The reader learns about the
  225. procedure call stack and \emph{calling conventions} and how they interact
  226. with register allocation and garbage collection. The chapter also
  227. describes how to generate efficient tail calls.
  228. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  229. scoping, that is, \emph{lambda} expressions. The reader learns about
  230. \emph{closure conversion}, in which lambdas are translated into a
  231. combination of functions and tuples.
  232. % Chapter about classes and objects?
  233. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  234. point the input languages are statically typed. The reader extends
  235. the statically typed language with an \code{Any} type that serves
  236. as a target for compiling the dynamically typed language.
  237. %% {\if\edition\pythonEd\pythonColor
  238. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  239. %% \emph{classes}.
  240. %% \fi}
  241. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  242. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  243. in which different regions of a program may be static or dynamically
  244. typed. The reader implements runtime support for \emph{proxies} that
  245. allow values to safely move between regions.
  246. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  247. leveraging the \code{Any} type and type casts developed in chapters
  248. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  249. \end{itemize}
  250. There are many language features that we do not include. Our choices
  251. balance the incidental complexity of a feature versus the fundamental
  252. concepts that it exposes. For example, we include tuples and not
  253. records because although they both elicit the study of heap allocation and
  254. garbage collection, records come with more incidental complexity.
  255. Since 2009, drafts of this book have served as the textbook for
  256. sixteen-week compiler courses for upper-level undergraduates and
  257. first-year graduate students at the University of Colorado and Indiana
  258. University.
  259. %
  260. Students come into the course having learned the basics of
  261. programming, data structures and algorithms, and discrete
  262. mathematics.
  263. %
  264. At the beginning of the course, students form groups of two to four
  265. people. The groups complete approximately one chapter every two
  266. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  267. according to the students interests while respecting the dependencies
  268. between chapters shown in
  269. Figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  270. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  271. implementation of efficient tail calls.
  272. %
  273. The last two weeks of the course involve a final project in which
  274. students design and implement a compiler extension of their choosing.
  275. The last few chapters can be used in support of these projects. Many
  276. chapters include a challenge problem that we assign to the graduate
  277. students.
  278. For compiler courses at universities on the quarter system
  279. (about ten weeks in length), we recommend completing the course
  280. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  281. some scaffolding code to the students for each compiler pass.
  282. %
  283. The course can be adapted to emphasize functional languages by
  284. skipping chapter~\ref{ch:Lwhile} (loops) and including
  285. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  286. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  287. %
  288. %% \python{A course that emphasizes object-oriented languages would
  289. %% include Chapter~\ref{ch:Lobject}.}
  290. This book has been used in compiler courses at California Polytechnic
  291. State University, Portland State University, Rose–Hulman Institute of
  292. Technology, University of Freiburg, University of Massachusetts
  293. Lowell, and the University of Vermont.
  294. \begin{figure}[tp]
  295. \begin{tcolorbox}[colback=white]
  296. {\if\edition\racketEd
  297. \begin{tikzpicture}[baseline=(current bounding box.center)]
  298. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  299. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  300. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  301. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  302. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  303. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  304. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  305. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  306. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  307. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  308. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  309. \path[->] (C1) edge [above] node {} (C2);
  310. \path[->] (C2) edge [above] node {} (C3);
  311. \path[->] (C3) edge [above] node {} (C4);
  312. \path[->] (C4) edge [above] node {} (C5);
  313. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  314. \path[->] (C5) edge [above] node {} (C7);
  315. \path[->] (C6) edge [above] node {} (C7);
  316. \path[->] (C4) edge [above] node {} (C8);
  317. \path[->] (C4) edge [above] node {} (C9);
  318. \path[->] (C7) edge [above] node {} (C10);
  319. \path[->] (C8) edge [above] node {} (C10);
  320. \path[->] (C10) edge [above] node {} (C11);
  321. \end{tikzpicture}
  322. \fi}
  323. {\if\edition\pythonEd\pythonColor
  324. \begin{tikzpicture}[baseline=(current bounding box.center)]
  325. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  326. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  327. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  328. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  329. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  330. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  331. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  332. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  333. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  334. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  335. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  336. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  337. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  338. \path[->] (Prelim) edge [above] node {} (Var);
  339. \path[->] (Var) edge [above] node {} (Reg);
  340. \path[->] (Var) edge [above] node {} (Parse);
  341. \path[->] (Reg) edge [above] node {} (Cond);
  342. \path[->] (Cond) edge [above] node {} (Tuple);
  343. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  344. \path[->] (Cond) edge [above] node {} (Fun);
  345. \path[->] (Tuple) edge [above] node {} (Lam);
  346. \path[->] (Fun) edge [above] node {} (Lam);
  347. \path[->] (Cond) edge [above] node {} (Dyn);
  348. \path[->] (Cond) edge [above] node {} (Loop);
  349. \path[->] (Lam) edge [above] node {} (Gradual);
  350. \path[->] (Dyn) edge [above] node {} (Gradual);
  351. % \path[->] (Dyn) edge [above] node {} (CO);
  352. \path[->] (Gradual) edge [above] node {} (Generic);
  353. \end{tikzpicture}
  354. \fi}
  355. \end{tcolorbox}
  356. \caption{Diagram of chapter dependencies.}
  357. \label{fig:chapter-dependences}
  358. \end{figure}
  359. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  360. the implementation of the compiler and for the input language, so the
  361. reader should be proficient with Racket or Scheme. There are many
  362. excellent resources for learning Scheme and
  363. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  364. %
  365. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  366. both for the implementation of the compiler and for the input language, so the
  367. reader should be proficient with Python. There are many
  368. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  369. %
  370. The support code for this book is in the GitHub repository at
  371. the following location:
  372. \begin{center}\small\texttt
  373. https://github.com/IUCompilerCourse/
  374. \end{center}
  375. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  376. is helpful but not necessary for the reader to have taken a computer
  377. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  378. assembly language that are needed in the compiler.
  379. %
  380. We follow the System V calling
  381. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  382. that we generate works with the runtime system (written in C) when it
  383. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  384. operating systems on Intel hardware.
  385. %
  386. On the Windows operating system, \code{gcc} uses the Microsoft x64
  387. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  388. assembly code that we generate does \emph{not} work with the runtime
  389. system on Windows. One workaround is to use a virtual machine with
  390. Linux as the guest operating system.
  391. \section*{Acknowledgments}
  392. The tradition of compiler construction at Indiana University goes back
  393. to research and courses on programming languages by Daniel Friedman in
  394. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  395. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  396. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  397. the compiler course and continued the development of Chez Scheme.
  398. %
  399. The compiler course evolved to incorporate novel pedagogical ideas
  400. while also including elements of real-world compilers. One of
  401. Friedman's ideas was to split the compiler into many small
  402. passes. Another idea, called ``the game,'' was to test the code
  403. generated by each pass using interpreters.
  404. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  405. developed infrastructure to support this approach and evolved the
  406. course to use even smaller
  407. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  408. design decisions in this book are inspired by the assignment
  409. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  410. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  411. organization of the course made it difficult for students to
  412. understand the rationale for the compiler design. Ghuloum proposed the
  413. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  414. based.
  415. I thank the many students who served as teaching assistants for the
  416. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  417. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  418. garbage collector and x86 interpreter, Michael Vollmer for work on
  419. efficient tail calls, and Michael Vitousek for help with the first
  420. offering of the incremental compiler course at IU.
  421. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  422. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  423. Michael Wollowski for teaching courses based on drafts of this book
  424. and for their feedback. I thank the National Science Foundation for
  425. the grants that helped to support this work: Grant Numbers 1518844,
  426. 1763922, and 1814460.
  427. I thank Ronald Garcia for helping me survive Dybvig's compiler
  428. course in the early 2000s and especially for finding the bug that
  429. sent our garbage collector on a wild goose chase!
  430. \mbox{}\\
  431. \noindent Jeremy G. Siek \\
  432. Bloomington, Indiana
  433. \mainmatter
  434. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  435. \chapter{Preliminaries}
  436. \label{ch:trees-recur}
  437. \setcounter{footnote}{0}
  438. In this chapter we review the basic tools needed to implement a
  439. compiler. Programs are typically input by a programmer as text, that
  440. is, a sequence of characters. The program-as-text representation is
  441. called \emph{concrete syntax}. We use concrete syntax to concisely
  442. write down and talk about programs. Inside the compiler, we use
  443. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  444. that efficiently supports the operations that the compiler needs to
  445. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  446. syntax}\index{subject}{abstract syntax
  447. tree}\index{subject}{AST}\index{subject}{program}
  448. The process of translating concrete syntax to abstract syntax is
  449. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  450. chapter~\ref{ch:parsing}}.
  451. \racket{This book does not cover the theory and implementation of parsing.
  452. We refer the readers interested in parsing to the thorough treatment
  453. of parsing by \citet{Aho:2006wb}.}%
  454. %
  455. \racket{A parser is provided in the support code for translating from
  456. concrete to abstract syntax.}%
  457. %
  458. \python{For now we use Python's \code{ast} module to translate from concrete
  459. to abstract syntax.}
  460. ASTs can be represented inside the compiler in many different ways,
  461. depending on the programming language used to write the compiler.
  462. %
  463. \racket{We use Racket's
  464. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  465. feature to represent ASTs (section~\ref{sec:ast}).}
  466. %
  467. \python{We use Python classes and objects to represent ASTs, especially the
  468. classes defined in the standard \code{ast} module for the Python
  469. source language.}
  470. %
  471. We use grammars to define the abstract syntax of programming languages
  472. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  473. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  474. recursive functions to construct and deconstruct ASTs
  475. (section~\ref{sec:recursion}). This chapter provides a brief
  476. introduction to these components.
  477. \racket{\index{subject}{struct}}
  478. \python{\index{subject}{class}\index{subject}{object}}
  479. \section{Abstract Syntax Trees}
  480. \label{sec:ast}
  481. Compilers use abstract syntax trees to represent programs because they
  482. often need to ask questions such as, for a given part of a program,
  483. what kind of language feature is it? What are its subparts? Consider
  484. the program on the left and the diagram of its AST on the
  485. right~\eqref{eq:arith-prog}. This program is an addition operation
  486. that has two subparts, a \racket{read}\python{input} operation and a
  487. negation. The negation has another subpart, the integer constant
  488. \code{8}. By using a tree to represent the program, we can easily
  489. follow the links to go from one part of a program to its subparts.
  490. \begin{center}
  491. \begin{minipage}{0.4\textwidth}
  492. {\if\edition\racketEd
  493. \begin{lstlisting}
  494. (+ (read) (- 8))
  495. \end{lstlisting}
  496. \fi}
  497. {\if\edition\pythonEd\pythonColor
  498. \begin{lstlisting}
  499. input_int() + -8
  500. \end{lstlisting}
  501. \fi}
  502. \end{minipage}
  503. \begin{minipage}{0.4\textwidth}
  504. \begin{equation}
  505. \begin{tikzpicture}
  506. \node[draw] (plus) at (0 , 0) {\key{+}};
  507. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  508. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  509. \node[draw] (8) at (1 , -2) {\key{8}};
  510. \draw[->] (plus) to (read);
  511. \draw[->] (plus) to (minus);
  512. \draw[->] (minus) to (8);
  513. \end{tikzpicture}
  514. \label{eq:arith-prog}
  515. \end{equation}
  516. \end{minipage}
  517. \end{center}
  518. We use the standard terminology for trees to describe ASTs: each
  519. rectangle above is called a \emph{node}. The arrows connect a node to its
  520. \emph{children}, which are also nodes. The top-most node is the
  521. \emph{root}. Every node except for the root has a \emph{parent} (the
  522. node of which it is the child). If a node has no children, it is a
  523. \emph{leaf} node; otherwise it is an \emph{internal} node.
  524. \index{subject}{node}
  525. \index{subject}{children}
  526. \index{subject}{root}
  527. \index{subject}{parent}
  528. \index{subject}{leaf}
  529. \index{subject}{internal node}
  530. %% Recall that an \emph{symbolic expression} (S-expression) is either
  531. %% \begin{enumerate}
  532. %% \item an atom, or
  533. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  534. %% where $e_1$ and $e_2$ are each an S-expression.
  535. %% \end{enumerate}
  536. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  537. %% null value \code{'()}, etc. We can create an S-expression in Racket
  538. %% simply by writing a backquote (called a quasi-quote in Racket)
  539. %% followed by the textual representation of the S-expression. It is
  540. %% quite common to use S-expressions to represent a list, such as $a, b
  541. %% ,c$ in the following way:
  542. %% \begin{lstlisting}
  543. %% `(a . (b . (c . ())))
  544. %% \end{lstlisting}
  545. %% Each element of the list is in the first slot of a pair, and the
  546. %% second slot is either the rest of the list or the null value, to mark
  547. %% the end of the list. Such lists are so common that Racket provides
  548. %% special notation for them that removes the need for the periods
  549. %% and so many parenthesis:
  550. %% \begin{lstlisting}
  551. %% `(a b c)
  552. %% \end{lstlisting}
  553. %% The following expression creates an S-expression that represents AST
  554. %% \eqref{eq:arith-prog}.
  555. %% \begin{lstlisting}
  556. %% `(+ (read) (- 8))
  557. %% \end{lstlisting}
  558. %% When using S-expressions to represent ASTs, the convention is to
  559. %% represent each AST node as a list and to put the operation symbol at
  560. %% the front of the list. The rest of the list contains the children. So
  561. %% in the above case, the root AST node has operation \code{`+} and its
  562. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  563. %% diagram \eqref{eq:arith-prog}.
  564. %% To build larger S-expressions one often needs to splice together
  565. %% several smaller S-expressions. Racket provides the comma operator to
  566. %% splice an S-expression into a larger one. For example, instead of
  567. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  568. %% we could have first created an S-expression for AST
  569. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  570. %% S-expression.
  571. %% \begin{lstlisting}
  572. %% (define ast1.4 `(- 8))
  573. %% (define ast1_1 `(+ (read) ,ast1.4))
  574. %% \end{lstlisting}
  575. %% In general, the Racket expression that follows the comma (splice)
  576. %% can be any expression that produces an S-expression.
  577. {\if\edition\racketEd
  578. We define a Racket \code{struct} for each kind of node. For this
  579. chapter we require just two kinds of nodes: one for integer constants
  580. (aka literals\index{subject}{literals})
  581. and one for primitive operations. The following is the \code{struct}
  582. definition for integer constants.\footnote{All the AST structures are
  583. defined in the file \code{utilities.rkt} in the support code.}
  584. \begin{lstlisting}
  585. (struct Int (value))
  586. \end{lstlisting}
  587. An integer node contains just one thing: the integer value.
  588. We establish the convention that \code{struct} names, such
  589. as \code{Int}, are capitalized.
  590. To create an AST node for the integer $8$, we write \INT{8}.
  591. \begin{lstlisting}
  592. (define eight (Int 8))
  593. \end{lstlisting}
  594. We say that the value created by \INT{8} is an
  595. \emph{instance} of the
  596. \code{Int} structure.
  597. The following is the \code{struct} definition for primitive operations.
  598. \begin{lstlisting}
  599. (struct Prim (op args))
  600. \end{lstlisting}
  601. A primitive operation node includes an operator symbol \code{op} and a
  602. list of child arguments called \code{args}. For example, to create an
  603. AST that negates the number $8$, we write the following.
  604. \begin{lstlisting}
  605. (define neg-eight (Prim '- (list eight)))
  606. \end{lstlisting}
  607. Primitive operations may have zero or more children. The \code{read}
  608. operator has zero:
  609. \begin{lstlisting}
  610. (define rd (Prim 'read '()))
  611. \end{lstlisting}
  612. The addition operator has two children:
  613. \begin{lstlisting}
  614. (define ast1_1 (Prim '+ (list rd neg-eight)))
  615. \end{lstlisting}
  616. We have made a design choice regarding the \code{Prim} structure.
  617. Instead of using one structure for many different operations
  618. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  619. structure for each operation, as follows:
  620. \begin{lstlisting}
  621. (struct Read ())
  622. (struct Add (left right))
  623. (struct Neg (value))
  624. \end{lstlisting}
  625. The reason that we choose to use just one structure is that many parts
  626. of the compiler can use the same code for the different primitive
  627. operators, so we might as well just write that code once by using a
  628. single structure.
  629. %
  630. \fi}
  631. {\if\edition\pythonEd\pythonColor
  632. We use a Python \code{class} for each kind of node.
  633. The following is the class definition for
  634. constants (aka literals\index{subject}{literals})
  635. from the Python \code{ast} module.
  636. \begin{lstlisting}
  637. class Constant:
  638. def __init__(self, value):
  639. self.value = value
  640. \end{lstlisting}
  641. An integer constant node includes just one thing: the integer value.
  642. To create an AST node for the integer $8$, we write \INT{8}.
  643. \begin{lstlisting}
  644. eight = Constant(8)
  645. \end{lstlisting}
  646. We say that the value created by \INT{8} is an
  647. \emph{instance} of the \code{Constant} class.
  648. The following is the class definition for unary operators.
  649. \begin{lstlisting}
  650. class UnaryOp:
  651. def __init__(self, op, operand):
  652. self.op = op
  653. self.operand = operand
  654. \end{lstlisting}
  655. The specific operation is specified by the \code{op} parameter. For
  656. example, the class \code{USub} is for unary subtraction.
  657. (More unary operators are introduced in later chapters.) To create an AST that
  658. negates the number $8$, we write the following.
  659. \begin{lstlisting}
  660. neg_eight = UnaryOp(USub(), eight)
  661. \end{lstlisting}
  662. The call to the \code{input\_int} function is represented by the
  663. \code{Call} and \code{Name} classes.
  664. \begin{lstlisting}
  665. class Call:
  666. def __init__(self, func, args):
  667. self.func = func
  668. self.args = args
  669. class Name:
  670. def __init__(self, id):
  671. self.id = id
  672. \end{lstlisting}
  673. To create an AST node that calls \code{input\_int}, we write
  674. \begin{lstlisting}
  675. read = Call(Name('input_int'), [])
  676. \end{lstlisting}
  677. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  678. the \code{BinOp} class for binary operators.
  679. \begin{lstlisting}
  680. class BinOp:
  681. def __init__(self, left, op, right):
  682. self.op = op
  683. self.left = left
  684. self.right = right
  685. \end{lstlisting}
  686. Similar to \code{UnaryOp}, the specific operation is specified by the
  687. \code{op} parameter, which for now is just an instance of the
  688. \code{Add} class. So to create the AST
  689. node that adds negative eight to some user input, we write the following.
  690. \begin{lstlisting}
  691. ast1_1 = BinOp(read, Add(), neg_eight)
  692. \end{lstlisting}
  693. \fi}
  694. To compile a program such as \eqref{eq:arith-prog}, we need to know
  695. that the operation associated with the root node is addition and we
  696. need to be able to access its two
  697. children. \racket{Racket}\python{Python} provides pattern matching to
  698. support these kinds of queries, as we see in
  699. section~\ref{sec:pattern-matching}.
  700. We often write down the concrete syntax of a program even when we
  701. actually have in mind the AST, because the concrete syntax is more
  702. concise. We recommend that you always think of programs as abstract
  703. syntax trees.
  704. \section{Grammars}
  705. \label{sec:grammar}
  706. \index{subject}{integer}
  707. %\index{subject}{constant}
  708. A programming language can be thought of as a \emph{set} of programs.
  709. The set is infinite (that is, one can always create larger programs),
  710. so one cannot simply describe a language by listing all the
  711. programs in the language. Instead we write down a set of rules, a
  712. \emph{context-free grammar}, for building programs. Grammars are often used to
  713. define the concrete syntax of a language, but they can also be used to
  714. describe the abstract syntax. We write our rules in a variant of
  715. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  716. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  717. we describe a small language, named \LangInt{}, that consists of
  718. integers and arithmetic operations.\index{subject}{grammar}
  719. \index{subject}{context-free grammar}
  720. The first grammar rule for the abstract syntax of \LangInt{} says that an
  721. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  722. \begin{equation}
  723. \Exp ::= \INT{\Int} \label{eq:arith-int}
  724. \end{equation}
  725. %
  726. Each rule has a left-hand side and a right-hand side.
  727. If you have an AST node that matches the
  728. right-hand side, then you can categorize it according to the
  729. left-hand side.
  730. %
  731. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  732. are \emph{terminal} symbols and must literally appear in the program for the
  733. rule to be applicable.\index{subject}{terminal}
  734. %
  735. Our grammars do not mention \emph{white space}, that is, delimiter
  736. characters like spaces, tabs, and new lines. White space may be
  737. inserted between symbols for disambiguation and to improve
  738. readability. \index{subject}{white space}
  739. %
  740. A name such as $\Exp$ that is defined by the grammar rules is a
  741. \emph{nonterminal}. \index{subject}{nonterminal}
  742. %
  743. The name $\Int$ is also a nonterminal, but instead of defining it with
  744. a grammar rule, we define it with the following explanation. An
  745. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  746. $-$ (for negative integers), such that the sequence of decimals
  747. %
  748. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  749. enables the representation of integers using 63 bits, which simplifies
  750. several aspects of compilation.
  751. %
  752. Thus, these integers correspond to the Racket \texttt{fixnum}
  753. datatype on a 64-bit machine.}
  754. %
  755. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  756. enables the representation of integers using 64 bits, which simplifies
  757. several aspects of compilation. In contrast, integers in Python have
  758. unlimited precision, but the techniques needed to handle unlimited
  759. precision fall outside the scope of this book.}
  760. The second grammar rule is the \READOP{} operation, which receives an
  761. input integer from the user of the program.
  762. \begin{equation}
  763. \Exp ::= \READ{} \label{eq:arith-read}
  764. \end{equation}
  765. The third rule categorizes the negation of an $\Exp$ node as an
  766. $\Exp$.
  767. \begin{equation}
  768. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  769. \end{equation}
  770. We can apply these rules to categorize the ASTs that are in the
  771. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  772. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  773. following AST is an $\Exp$.
  774. \begin{center}
  775. \begin{minipage}{0.5\textwidth}
  776. \NEG{\INT{\code{8}}}
  777. \end{minipage}
  778. \begin{minipage}{0.25\textwidth}
  779. \begin{equation}
  780. \begin{tikzpicture}
  781. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  782. \node[draw, circle] (8) at (0, -1.2) {$8$};
  783. \draw[->] (minus) to (8);
  784. \end{tikzpicture}
  785. \label{eq:arith-neg8}
  786. \end{equation}
  787. \end{minipage}
  788. \end{center}
  789. The next two grammar rules are for addition and subtraction expressions:
  790. \begin{align}
  791. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  792. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  793. \end{align}
  794. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  795. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  796. \eqref{eq:arith-read}, and we have already categorized
  797. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  798. to show that
  799. \[
  800. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  801. \]
  802. is an $\Exp$ in the \LangInt{} language.
  803. If you have an AST for which these rules do not apply, then the
  804. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  805. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  806. because there is no rule for the \key{*} operator. Whenever we
  807. define a language with a grammar, the language includes only those
  808. programs that are justified by the grammar rules.
  809. {\if\edition\pythonEd\pythonColor
  810. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  811. There is a statement for printing the value of an expression
  812. \[
  813. \Stmt{} ::= \PRINT{\Exp}
  814. \]
  815. and a statement that evaluates an expression but ignores the result.
  816. \[
  817. \Stmt{} ::= \EXPR{\Exp}
  818. \]
  819. \fi}
  820. {\if\edition\racketEd
  821. The last grammar rule for \LangInt{} states that there is a
  822. \code{Program} node to mark the top of the whole program:
  823. \[
  824. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  825. \]
  826. The \code{Program} structure is defined as follows:
  827. \begin{lstlisting}
  828. (struct Program (info body))
  829. \end{lstlisting}
  830. where \code{body} is an expression. In further chapters, the \code{info}
  831. part is used to store auxiliary information, but for now it is
  832. just the empty list.
  833. \fi}
  834. {\if\edition\pythonEd\pythonColor
  835. The last grammar rule for \LangInt{} states that there is a
  836. \code{Module} node to mark the top of the whole program:
  837. \[
  838. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  839. \]
  840. The asterisk $*$ indicates a list of the preceding grammar item, in
  841. this case a list of statements.
  842. %
  843. The \code{Module} class is defined as follows:
  844. \begin{lstlisting}
  845. class Module:
  846. def __init__(self, body):
  847. self.body = body
  848. \end{lstlisting}
  849. where \code{body} is a list of statements.
  850. \fi}
  851. It is common to have many grammar rules with the same left-hand side
  852. but different right-hand sides, such as the rules for $\Exp$ in the
  853. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  854. combine several right-hand sides into a single rule.
  855. The concrete syntax for \LangInt{} is shown in
  856. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  857. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  858. %
  859. \racket{The \code{read-program} function provided in
  860. \code{utilities.rkt} of the support code reads a program from a file
  861. (the sequence of characters in the concrete syntax of Racket) and
  862. parses it into an abstract syntax tree. Refer to the description of
  863. \code{read-program} in appendix~\ref{appendix:utilities} for more
  864. details.}
  865. %
  866. \python{The \code{parse} function in Python's \code{ast} module
  867. converts the concrete syntax (represented as a string) into an
  868. abstract syntax tree.}
  869. \newcommand{\LintGrammarRacket}{
  870. \begin{array}{rcl}
  871. \Type &::=& \key{Integer} \\
  872. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  873. \MID \CSUB{\Exp}{\Exp}
  874. \end{array}
  875. }
  876. \newcommand{\LintASTRacket}{
  877. \begin{array}{rcl}
  878. \Type &::=& \key{Integer} \\
  879. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  880. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  881. \end{array}
  882. }
  883. \newcommand{\LintGrammarPython}{
  884. \begin{array}{rcl}
  885. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  886. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  887. \end{array}
  888. }
  889. \newcommand{\LintASTPython}{
  890. \begin{array}{rcl}
  891. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  892. \itm{unaryop} &::= & \code{USub()} \\
  893. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  894. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp} \\
  895. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  896. \end{array}
  897. }
  898. \begin{figure}[tp]
  899. \begin{tcolorbox}[colback=white]
  900. {\if\edition\racketEd
  901. \[
  902. \begin{array}{l}
  903. \LintGrammarRacket \\
  904. \begin{array}{rcl}
  905. \LangInt{} &::=& \Exp
  906. \end{array}
  907. \end{array}
  908. \]
  909. \fi}
  910. {\if\edition\pythonEd\pythonColor
  911. \[
  912. \begin{array}{l}
  913. \LintGrammarPython \\
  914. \begin{array}{rcl}
  915. \LangInt{} &::=& \Stmt^{*}
  916. \end{array}
  917. \end{array}
  918. \]
  919. \fi}
  920. \end{tcolorbox}
  921. \caption{The concrete syntax of \LangInt{}.}
  922. \label{fig:r0-concrete-syntax}
  923. \end{figure}
  924. \begin{figure}[tp]
  925. \begin{tcolorbox}[colback=white]
  926. {\if\edition\racketEd
  927. \[
  928. \begin{array}{l}
  929. \LintASTRacket{} \\
  930. \begin{array}{rcl}
  931. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  932. \end{array}
  933. \end{array}
  934. \]
  935. \fi}
  936. {\if\edition\pythonEd\pythonColor
  937. \[
  938. \begin{array}{l}
  939. \LintASTPython\\
  940. \begin{array}{rcl}
  941. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  942. \end{array}
  943. \end{array}
  944. \]
  945. \fi}
  946. \end{tcolorbox}
  947. \python{
  948. \index{subject}{Constant@\texttt{Constant}}
  949. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  950. \index{subject}{USub@\texttt{USub}}
  951. \index{subject}{inputint@\texttt{input\_int}}
  952. \index{subject}{Call@\texttt{Call}}
  953. \index{subject}{Name@\texttt{Name}}
  954. \index{subject}{BinOp@\texttt{BinOp}}
  955. \index{subject}{Add@\texttt{Add}}
  956. \index{subject}{Sub@\texttt{Sub}}
  957. \index{subject}{print@\texttt{print}}
  958. \index{subject}{Expr@\texttt{Expr}}
  959. \index{subject}{Module@\texttt{Module}}
  960. }
  961. \caption{The abstract syntax of \LangInt{}.}
  962. \label{fig:r0-syntax}
  963. \end{figure}
  964. \section{Pattern Matching}
  965. \label{sec:pattern-matching}
  966. As mentioned in section~\ref{sec:ast}, compilers often need to access
  967. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  968. provides the \texttt{match} feature to access the parts of a value.
  969. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  970. \begin{center}
  971. \begin{minipage}{1.0\textwidth}
  972. {\if\edition\racketEd
  973. \begin{lstlisting}
  974. (match ast1_1
  975. [(Prim op (list child1 child2))
  976. (print op)])
  977. \end{lstlisting}
  978. \fi}
  979. {\if\edition\pythonEd\pythonColor
  980. \begin{lstlisting}
  981. match ast1_1:
  982. case BinOp(child1, op, child2):
  983. print(op)
  984. \end{lstlisting}
  985. \fi}
  986. \end{minipage}
  987. \end{center}
  988. {\if\edition\racketEd
  989. %
  990. In this example, the \texttt{match} form checks whether the AST
  991. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  992. three pattern variables \texttt{op}, \texttt{child1}, and
  993. \texttt{child2}. In general, a match clause consists of a
  994. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  995. recursively defined to be a pattern variable, a structure name
  996. followed by a pattern for each of the structure's arguments, or an
  997. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  998. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  999. and chapter 9 of The Racket
  1000. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1001. for complete descriptions of \code{match}.)
  1002. %
  1003. The body of a match clause may contain arbitrary Racket code. The
  1004. pattern variables can be used in the scope of the body, such as
  1005. \code{op} in \code{(print op)}.
  1006. %
  1007. \fi}
  1008. %
  1009. %
  1010. {\if\edition\pythonEd\pythonColor
  1011. %
  1012. In the example above, the \texttt{match} form checks whether the AST
  1013. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1014. three pattern variables (\texttt{child1}, \texttt{op}, and
  1015. \texttt{child2}). In general, each \code{case} consists of a
  1016. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1017. recursively defined to be one of the following: a pattern variable, a
  1018. class name followed by a pattern for each of its constructor's
  1019. arguments, or other literals\index{subject}{literals} such as strings
  1020. or lists.
  1021. %
  1022. The body of each \code{case} may contain arbitrary Python code. The
  1023. pattern variables can be used in the body, such as \code{op} in
  1024. \code{print(op)}.
  1025. %
  1026. \fi}
  1027. A \code{match} form may contain several clauses, as in the following
  1028. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1029. the AST. The \code{match} proceeds through the clauses in order,
  1030. checking whether the pattern can match the input AST. The body of the
  1031. first clause that matches is executed. The output of \code{leaf} for
  1032. several ASTs is shown on the right side of the following:
  1033. \begin{center}
  1034. \begin{minipage}{0.6\textwidth}
  1035. {\if\edition\racketEd
  1036. \begin{lstlisting}
  1037. (define (leaf arith)
  1038. (match arith
  1039. [(Int n) #t]
  1040. [(Prim 'read '()) #t]
  1041. [(Prim '- (list e1)) #f]
  1042. [(Prim '+ (list e1 e2)) #f]
  1043. [(Prim '- (list e1 e2)) #f]))
  1044. (leaf (Prim 'read '()))
  1045. (leaf (Prim '- (list (Int 8))))
  1046. (leaf (Int 8))
  1047. \end{lstlisting}
  1048. \fi}
  1049. {\if\edition\pythonEd\pythonColor
  1050. \begin{lstlisting}
  1051. def leaf(arith):
  1052. match arith:
  1053. case Constant(n):
  1054. return True
  1055. case Call(Name('input_int'), []):
  1056. return True
  1057. case UnaryOp(USub(), e1):
  1058. return False
  1059. case BinOp(e1, Add(), e2):
  1060. return False
  1061. case BinOp(e1, Sub(), e2):
  1062. return False
  1063. print(leaf(Call(Name('input_int'), [])))
  1064. print(leaf(UnaryOp(USub(), eight)))
  1065. print(leaf(Constant(8)))
  1066. \end{lstlisting}
  1067. \fi}
  1068. \end{minipage}
  1069. \vrule
  1070. \begin{minipage}{0.25\textwidth}
  1071. {\if\edition\racketEd
  1072. \begin{lstlisting}
  1073. #t
  1074. #f
  1075. #t
  1076. \end{lstlisting}
  1077. \fi}
  1078. {\if\edition\pythonEd\pythonColor
  1079. \begin{lstlisting}
  1080. True
  1081. False
  1082. True
  1083. \end{lstlisting}
  1084. \fi}
  1085. \end{minipage}
  1086. \index{subject}{True@\TRUE{}}
  1087. \index{subject}{False@\FALSE{}}
  1088. \end{center}
  1089. When constructing a \code{match} expression, we refer to the grammar
  1090. definition to identify which nonterminal we are expecting to match
  1091. against, and then we make sure that (1) we have one
  1092. \racket{clause}\python{case} for each alternative of that nonterminal
  1093. and (2) the pattern in each \racket{clause}\python{case}
  1094. corresponds to the corresponding right-hand side of a grammar
  1095. rule. For the \code{match} in the \code{leaf} function, we refer to
  1096. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1097. nonterminal has four alternatives, so the \code{match} has four
  1098. \racket{clauses}\python{cases}. The pattern in each
  1099. \racket{clause}\python{case} corresponds to the right-hand side of a
  1100. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1101. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1102. translating from grammars to patterns, replace nonterminals such as
  1103. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1104. \code{e2}).
  1105. \section{Recursive Functions}
  1106. \label{sec:recursion}
  1107. \index{subject}{recursive function}
  1108. Programs are inherently recursive. For example, an expression is often
  1109. made of smaller expressions. Thus, the natural way to process an
  1110. entire program is to use a recursive function. As a first example of
  1111. such a recursive function, we define the function \code{is\_exp} as
  1112. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1113. value and determine whether or not it is an expression in \LangInt{}.
  1114. %
  1115. We say that a function is defined by \emph{structural recursion} if
  1116. it is defined using a sequence of match \racket{clauses}\python{cases}
  1117. that correspond to a grammar and the body of each
  1118. \racket{clause}\python{case} makes a recursive call on each child
  1119. node.\footnote{This principle of structuring code according to the
  1120. data definition is advocated in the book \emph{How to Design
  1121. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1122. second function, named \code{stmt}, that recognizes whether a value
  1123. is a \LangInt{} statement.} \python{Finally, }
  1124. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1125. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1126. In general, we can write one recursive function to handle each
  1127. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1128. two examples at the bottom of the figure, the first is in
  1129. \LangInt{} and the second is not.
  1130. \begin{figure}[tp]
  1131. \begin{tcolorbox}[colback=white]
  1132. {\if\edition\racketEd
  1133. \begin{lstlisting}
  1134. (define (is_exp ast)
  1135. (match ast
  1136. [(Int n) #t]
  1137. [(Prim 'read '()) #t]
  1138. [(Prim '- (list e)) (is_exp e)]
  1139. [(Prim '+ (list e1 e2))
  1140. (and (is_exp e1) (is_exp e2))]
  1141. [(Prim '- (list e1 e2))
  1142. (and (is_exp e1) (is_exp e2))]
  1143. [else #f]))
  1144. (define (is_Lint ast)
  1145. (match ast
  1146. [(Program '() e) (is_exp e)]
  1147. [else #f]))
  1148. (is_Lint (Program '() ast1_1)
  1149. (is_Lint (Program '()
  1150. (Prim '* (list (Prim 'read '())
  1151. (Prim '+ (list (Int 8)))))))
  1152. \end{lstlisting}
  1153. \fi}
  1154. {\if\edition\pythonEd\pythonColor
  1155. \begin{lstlisting}
  1156. def is_exp(e):
  1157. match e:
  1158. case Constant(n):
  1159. return True
  1160. case Call(Name('input_int'), []):
  1161. return True
  1162. case UnaryOp(USub(), e1):
  1163. return is_exp(e1)
  1164. case BinOp(e1, Add(), e2):
  1165. return is_exp(e1) and is_exp(e2)
  1166. case BinOp(e1, Sub(), e2):
  1167. return is_exp(e1) and is_exp(e2)
  1168. case _:
  1169. return False
  1170. def stmt(s):
  1171. match s:
  1172. case Expr(Call(Name('print'), [e])):
  1173. return is_exp(e)
  1174. case Expr(e):
  1175. return is_exp(e)
  1176. case _:
  1177. return False
  1178. def is_Lint(p):
  1179. match p:
  1180. case Module(body):
  1181. return all([stmt(s) for s in body])
  1182. case _:
  1183. return False
  1184. print(is_Lint(Module([Expr(ast1_1)])))
  1185. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1186. UnaryOp(Add(), Constant(8))))])))
  1187. \end{lstlisting}
  1188. \fi}
  1189. \end{tcolorbox}
  1190. \caption{Example of recursive functions for \LangInt{}. These functions
  1191. recognize whether an AST is in \LangInt{}.}
  1192. \label{fig:exp-predicate}
  1193. \end{figure}
  1194. %% You may be tempted to merge the two functions into one, like this:
  1195. %% \begin{center}
  1196. %% \begin{minipage}{0.5\textwidth}
  1197. %% \begin{lstlisting}
  1198. %% (define (Lint ast)
  1199. %% (match ast
  1200. %% [(Int n) #t]
  1201. %% [(Prim 'read '()) #t]
  1202. %% [(Prim '- (list e)) (Lint e)]
  1203. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1204. %% [(Program '() e) (Lint e)]
  1205. %% [else #f]))
  1206. %% \end{lstlisting}
  1207. %% \end{minipage}
  1208. %% \end{center}
  1209. %% %
  1210. %% Sometimes such a trick will save a few lines of code, especially when
  1211. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1212. %% \emph{not} recommended because it can get you into trouble.
  1213. %% %
  1214. %% For example, the above function is subtly wrong:
  1215. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1216. %% returns true when it should return false.
  1217. \section{Interpreters}
  1218. \label{sec:interp_Lint}
  1219. \index{subject}{interpreter}
  1220. The behavior of a program is defined by the specification of the
  1221. programming language.
  1222. %
  1223. \racket{For example, the Scheme language is defined in the report by
  1224. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1225. reference manual~\citep{plt-tr}.}
  1226. %
  1227. \python{For example, the Python language is defined in the Python
  1228. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1229. %
  1230. In this book we use interpreters to specify each language that we
  1231. consider. An interpreter that is designated as the definition of a
  1232. language is called a \emph{definitional
  1233. interpreter}~\citep{reynolds72:_def_interp}.
  1234. \index{subject}{definitional interpreter} We warm up by creating a
  1235. definitional interpreter for the \LangInt{} language. This interpreter
  1236. serves as a second example of structural recursion. The definition of the
  1237. \code{interp\_Lint} function is shown in
  1238. figure~\ref{fig:interp_Lint}.
  1239. %
  1240. \racket{The body of the function is a match on the input program
  1241. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1242. which in turn has one match clause per grammar rule for \LangInt{}
  1243. expressions.}
  1244. %
  1245. \python{The body of the function matches on the \code{Module} AST node
  1246. and then invokes \code{interp\_stmt} on each statement in the
  1247. module. The \code{interp\_stmt} function includes a case for each
  1248. grammar rule of the \Stmt{} nonterminal, and it calls
  1249. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1250. function includes a case for each grammar rule of the \Exp{}
  1251. nonterminal. We use several auxiliary functions such as \code{add64}
  1252. and \code{input\_int} that are defined in the support code for this book.}
  1253. \begin{figure}[tp]
  1254. \begin{tcolorbox}[colback=white]
  1255. {\if\edition\racketEd
  1256. \begin{lstlisting}
  1257. (define (interp_exp e)
  1258. (match e
  1259. [(Int n) n]
  1260. [(Prim 'read '())
  1261. (define r (read))
  1262. (cond [(fixnum? r) r]
  1263. [else (error 'interp_exp "read expected an integer" r)])]
  1264. [(Prim '- (list e))
  1265. (define v (interp_exp e))
  1266. (fx- 0 v)]
  1267. [(Prim '+ (list e1 e2))
  1268. (define v1 (interp_exp e1))
  1269. (define v2 (interp_exp e2))
  1270. (fx+ v1 v2)]
  1271. [(Prim '- (list e1 e2))
  1272. (define v1 (interp_exp e1))
  1273. (define v2 (interp_exp e2))
  1274. (fx- v1 v2)]))
  1275. (define (interp_Lint p)
  1276. (match p
  1277. [(Program '() e) (interp_exp e)]))
  1278. \end{lstlisting}
  1279. \fi}
  1280. {\if\edition\pythonEd\pythonColor
  1281. \begin{lstlisting}
  1282. def interp_exp(e):
  1283. match e:
  1284. case BinOp(left, Add(), right):
  1285. l = interp_exp(left); r = interp_exp(right)
  1286. return add64(l, r)
  1287. case BinOp(left, Sub(), right):
  1288. l = interp_exp(left); r = interp_exp(right)
  1289. return sub64(l, r)
  1290. case UnaryOp(USub(), v):
  1291. return neg64(interp_exp(v))
  1292. case Constant(value):
  1293. return value
  1294. case Call(Name('input_int'), []):
  1295. return input_int()
  1296. def interp_stmt(s):
  1297. match s:
  1298. case Expr(Call(Name('print'), [arg])):
  1299. print(interp_exp(arg))
  1300. case Expr(value):
  1301. interp_exp(value)
  1302. def interp_Lint(p):
  1303. match p:
  1304. case Module(body):
  1305. for s in body:
  1306. interp_stmt(s)
  1307. \end{lstlisting}
  1308. \fi}
  1309. \end{tcolorbox}
  1310. \caption{Interpreter for the \LangInt{} language.}
  1311. \label{fig:interp_Lint}
  1312. \end{figure}
  1313. Let us consider the result of interpreting a few \LangInt{} programs. The
  1314. following program adds two integers:
  1315. {\if\edition\racketEd
  1316. \begin{lstlisting}
  1317. (+ 10 32)
  1318. \end{lstlisting}
  1319. \fi}
  1320. {\if\edition\pythonEd\pythonColor
  1321. \begin{lstlisting}
  1322. print(10 + 32)
  1323. \end{lstlisting}
  1324. \fi}
  1325. %
  1326. \noindent The result is \key{42}, the answer to life, the universe,
  1327. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1328. the Galaxy} by Douglas Adams.}
  1329. %
  1330. We wrote this program in concrete syntax, whereas the parsed
  1331. abstract syntax is
  1332. {\if\edition\racketEd
  1333. \begin{lstlisting}
  1334. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1335. \end{lstlisting}
  1336. \fi}
  1337. {\if\edition\pythonEd\pythonColor
  1338. \begin{lstlisting}
  1339. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1340. \end{lstlisting}
  1341. \fi}
  1342. The following program demonstrates that expressions may be nested within
  1343. each other, in this case nesting several additions and negations.
  1344. {\if\edition\racketEd
  1345. \begin{lstlisting}
  1346. (+ 10 (- (+ 12 20)))
  1347. \end{lstlisting}
  1348. \fi}
  1349. {\if\edition\pythonEd\pythonColor
  1350. \begin{lstlisting}
  1351. print(10 + -(12 + 20))
  1352. \end{lstlisting}
  1353. \fi}
  1354. %
  1355. \noindent What is the result of this program?
  1356. {\if\edition\racketEd
  1357. As mentioned previously, the \LangInt{} language does not support
  1358. arbitrarily large integers but only $63$-bit integers, so we
  1359. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1360. in Racket.
  1361. Suppose that
  1362. \[
  1363. n = 999999999999999999
  1364. \]
  1365. which indeed fits in $63$ bits. What happens when we run the
  1366. following program in our interpreter?
  1367. \begin{lstlisting}
  1368. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1369. \end{lstlisting}
  1370. It produces the following error:
  1371. \begin{lstlisting}
  1372. fx+: result is not a fixnum
  1373. \end{lstlisting}
  1374. We establish the convention that if running the definitional
  1375. interpreter on a program produces an error, then the meaning of that
  1376. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1377. error is a \code{trapped-error}. A compiler for the language is under
  1378. no obligation regarding programs with unspecified behavior; it does
  1379. not have to produce an executable, and if it does, that executable can
  1380. do anything. On the other hand, if the error is a
  1381. \code{trapped-error}, then the compiler must produce an executable and
  1382. it is required to report that an error occurred. To signal an error,
  1383. exit with a return code of \code{255}. The interpreters in chapters
  1384. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1385. \code{trapped-error}.
  1386. \fi}
  1387. % TODO: how to deal with too-large integers in the Python interpreter?
  1388. %% This convention applies to the languages defined in this
  1389. %% book, as a way to simplify the student's task of implementing them,
  1390. %% but this convention is not applicable to all programming languages.
  1391. %%
  1392. The last feature of the \LangInt{} language, the \READOP{} operation,
  1393. prompts the user of the program for an integer. Recall that program
  1394. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1395. \code{8}. So, if we run {\if\edition\racketEd
  1396. \begin{lstlisting}
  1397. (interp_Lint (Program '() ast1_1))
  1398. \end{lstlisting}
  1399. \fi}
  1400. {\if\edition\pythonEd\pythonColor
  1401. \begin{lstlisting}
  1402. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1403. \end{lstlisting}
  1404. \fi}
  1405. \noindent and if the input is \code{50}, the result is \code{42}.
  1406. We include the \READOP{} operation in \LangInt{} so that a clever
  1407. student cannot implement a compiler for \LangInt{} that simply runs
  1408. the interpreter during compilation to obtain the output and then
  1409. generates the trivial code to produce the output.\footnote{Yes, a
  1410. clever student did this in the first instance of this course!}
  1411. The job of a compiler is to translate a program in one language into a
  1412. program in another language so that the output program behaves the
  1413. same way as the input program. This idea is depicted in the
  1414. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1415. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1416. Given a compiler that translates from language $\mathcal{L}_1$ to
  1417. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1418. compiler must translate it into some program $P_2$ such that
  1419. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1420. same input $i$ yields the same output $o$.
  1421. \begin{equation} \label{eq:compile-correct}
  1422. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1423. \node (p1) at (0, 0) {$P_1$};
  1424. \node (p2) at (3, 0) {$P_2$};
  1425. \node (o) at (3, -2.5) {$o$};
  1426. \path[->] (p1) edge [above] node {compile} (p2);
  1427. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1428. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1429. \end{tikzpicture}
  1430. \end{equation}
  1431. \python{We establish the convention that if running the definitional
  1432. interpreter on a program produces an error, then the meaning of that
  1433. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1434. unless the exception raised is a \code{TrappedError}. A compiler for
  1435. the language is under no obligation regarding programs with
  1436. unspecified behavior; it does not have to produce an executable, and
  1437. if it does, that executable can do anything. On the other hand, if
  1438. the error is a \code{TrappedError}, then the compiler must produce
  1439. an executable and it is required to report that an error
  1440. occurred. To signal an error, exit with a return code of \code{255}.
  1441. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1442. section \ref{sec:arrays} use \code{TrappedError}.}
  1443. In the next section we see our first example of a compiler.
  1444. \section{Example Compiler: A Partial Evaluator}
  1445. \label{sec:partial-evaluation}
  1446. In this section we consider a compiler that translates \LangInt{}
  1447. programs into \LangInt{} programs that may be more efficient. The
  1448. compiler eagerly computes the parts of the program that do not depend
  1449. on any inputs, a process known as \emph{partial
  1450. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1451. For example, given the following program
  1452. {\if\edition\racketEd
  1453. \begin{lstlisting}
  1454. (+ (read) (- (+ 5 3)))
  1455. \end{lstlisting}
  1456. \fi}
  1457. {\if\edition\pythonEd\pythonColor
  1458. \begin{lstlisting}
  1459. print(input_int() + -(5 + 3) )
  1460. \end{lstlisting}
  1461. \fi}
  1462. \noindent our compiler translates it into the program
  1463. {\if\edition\racketEd
  1464. \begin{lstlisting}
  1465. (+ (read) -8)
  1466. \end{lstlisting}
  1467. \fi}
  1468. {\if\edition\pythonEd\pythonColor
  1469. \begin{lstlisting}
  1470. print(input_int() + -8)
  1471. \end{lstlisting}
  1472. \fi}
  1473. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1474. evaluator for the \LangInt{} language. The output of the partial evaluator
  1475. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1476. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1477. whereas the code for partially evaluating the negation and addition
  1478. operations is factored into three auxiliary functions:
  1479. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1480. functions is the output of partially evaluating the children.
  1481. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1482. arguments are integers and if they are, perform the appropriate
  1483. arithmetic. Otherwise, they create an AST node for the arithmetic
  1484. operation.
  1485. \begin{figure}[tp]
  1486. \begin{tcolorbox}[colback=white]
  1487. {\if\edition\racketEd
  1488. \begin{lstlisting}
  1489. (define (pe_neg r)
  1490. (match r
  1491. [(Int n) (Int (fx- 0 n))]
  1492. [else (Prim '- (list r))]))
  1493. (define (pe_add r1 r2)
  1494. (match* (r1 r2)
  1495. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1496. [(_ _) (Prim '+ (list r1 r2))]))
  1497. (define (pe_sub r1 r2)
  1498. (match* (r1 r2)
  1499. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1500. [(_ _) (Prim '- (list r1 r2))]))
  1501. (define (pe_exp e)
  1502. (match e
  1503. [(Int n) (Int n)]
  1504. [(Prim 'read '()) (Prim 'read '())]
  1505. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1506. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1507. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1508. (define (pe_Lint p)
  1509. (match p
  1510. [(Program '() e) (Program '() (pe_exp e))]))
  1511. \end{lstlisting}
  1512. \fi}
  1513. {\if\edition\pythonEd\pythonColor
  1514. \begin{lstlisting}
  1515. def pe_neg(r):
  1516. match r:
  1517. case Constant(n):
  1518. return Constant(neg64(n))
  1519. case _:
  1520. return UnaryOp(USub(), r)
  1521. def pe_add(r1, r2):
  1522. match (r1, r2):
  1523. case (Constant(n1), Constant(n2)):
  1524. return Constant(add64(n1, n2))
  1525. case _:
  1526. return BinOp(r1, Add(), r2)
  1527. def pe_sub(r1, r2):
  1528. match (r1, r2):
  1529. case (Constant(n1), Constant(n2)):
  1530. return Constant(sub64(n1, n2))
  1531. case _:
  1532. return BinOp(r1, Sub(), r2)
  1533. def pe_exp(e):
  1534. match e:
  1535. case BinOp(left, Add(), right):
  1536. return pe_add(pe_exp(left), pe_exp(right))
  1537. case BinOp(left, Sub(), right):
  1538. return pe_sub(pe_exp(left), pe_exp(right))
  1539. case UnaryOp(USub(), v):
  1540. return pe_neg(pe_exp(v))
  1541. case Constant(value):
  1542. return e
  1543. case Call(Name('input_int'), []):
  1544. return e
  1545. def pe_stmt(s):
  1546. match s:
  1547. case Expr(Call(Name('print'), [arg])):
  1548. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1549. case Expr(value):
  1550. return Expr(pe_exp(value))
  1551. def pe_P_int(p):
  1552. match p:
  1553. case Module(body):
  1554. new_body = [pe_stmt(s) for s in body]
  1555. return Module(new_body)
  1556. \end{lstlisting}
  1557. \fi}
  1558. \end{tcolorbox}
  1559. \caption{A partial evaluator for \LangInt{}.}
  1560. \label{fig:pe-arith}
  1561. \end{figure}
  1562. To gain some confidence that the partial evaluator is correct, we can
  1563. test whether it produces programs that produce the same result as the
  1564. input programs. That is, we can test whether it satisfies the diagram
  1565. of \eqref{eq:compile-correct}.
  1566. %
  1567. {\if\edition\racketEd
  1568. The following code runs the partial evaluator on several examples and
  1569. tests the output program. The \texttt{parse-program} and
  1570. \texttt{assert} functions are defined in
  1571. appendix~\ref{appendix:utilities}.\\
  1572. \begin{minipage}{1.0\textwidth}
  1573. \begin{lstlisting}
  1574. (define (test_pe p)
  1575. (assert "testing pe_Lint"
  1576. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1577. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1578. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1579. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1580. \end{lstlisting}
  1581. \end{minipage}
  1582. \fi}
  1583. % TODO: python version of testing the PE
  1584. \begin{exercise}\normalfont\normalsize
  1585. Create three programs in the \LangInt{} language and test whether
  1586. partially evaluating them with \code{pe\_Lint} and then
  1587. interpreting them with \code{interp\_Lint} gives the same result
  1588. as directly interpreting them with \code{interp\_Lint}.
  1589. \end{exercise}
  1590. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1591. \chapter{Integers and Variables}
  1592. \label{ch:Lvar}
  1593. \setcounter{footnote}{0}
  1594. This chapter covers compiling a subset of
  1595. \racket{Racket}\python{Python} to x86-64 assembly
  1596. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1597. integer arithmetic and local variables. We often refer to x86-64
  1598. simply as x86. The chapter first describes the \LangVar{} language
  1599. (section~\ref{sec:s0}) and then introduces x86 assembly
  1600. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1601. discuss only the instructions needed for compiling \LangVar{}. We
  1602. introduce more x86 instructions in subsequent chapters. After
  1603. introducing \LangVar{} and x86, we reflect on their differences and
  1604. create a plan to break down the translation from \LangVar{} to x86
  1605. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1606. the chapter gives detailed hints regarding each step. We aim to give
  1607. enough hints that the well-prepared reader, together with a few
  1608. friends, can implement a compiler from \LangVar{} to x86 in a short
  1609. time. To suggest the scale of this first compiler, we note that the
  1610. instructor solution for the \LangVar{} compiler is approximately
  1611. \racket{500}\python{300} lines of code.
  1612. \section{The \LangVar{} Language}
  1613. \label{sec:s0}
  1614. \index{subject}{variable}
  1615. The \LangVar{} language extends the \LangInt{} language with
  1616. variables. The concrete syntax of the \LangVar{} language is defined
  1617. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1618. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1619. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1620. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1621. \key{-} is a unary operator, and \key{+} is a binary operator.
  1622. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1623. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1624. the top of the program.
  1625. %% The $\itm{info}$
  1626. %% field of the \key{Program} structure contains an \emph{association
  1627. %% list} (a list of key-value pairs) that is used to communicate
  1628. %% auxiliary data from one compiler pass the next.
  1629. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1630. exhibit several compilation techniques.
  1631. \newcommand{\LvarGrammarRacket}{
  1632. \begin{array}{rcl}
  1633. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1634. \end{array}
  1635. }
  1636. \newcommand{\LvarASTRacket}{
  1637. \begin{array}{rcl}
  1638. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1639. \end{array}
  1640. }
  1641. \newcommand{\LvarGrammarPython}{
  1642. \begin{array}{rcl}
  1643. \Exp &::=& \Var{} \\
  1644. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1645. \end{array}
  1646. }
  1647. \newcommand{\LvarASTPython}{
  1648. \begin{array}{rcl}
  1649. \Exp{} &::=& \VAR{\Var{}} \\
  1650. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1651. \end{array}
  1652. }
  1653. \begin{figure}[tp]
  1654. \centering
  1655. \begin{tcolorbox}[colback=white]
  1656. {\if\edition\racketEd
  1657. \[
  1658. \begin{array}{l}
  1659. \gray{\LintGrammarRacket{}} \\ \hline
  1660. \LvarGrammarRacket{} \\
  1661. \begin{array}{rcl}
  1662. \LangVarM{} &::=& \Exp
  1663. \end{array}
  1664. \end{array}
  1665. \]
  1666. \fi}
  1667. {\if\edition\pythonEd\pythonColor
  1668. \[
  1669. \begin{array}{l}
  1670. \gray{\LintGrammarPython} \\ \hline
  1671. \LvarGrammarPython \\
  1672. \begin{array}{rcl}
  1673. \LangVarM{} &::=& \Stmt^{*}
  1674. \end{array}
  1675. \end{array}
  1676. \]
  1677. \fi}
  1678. \end{tcolorbox}
  1679. \caption{The concrete syntax of \LangVar{}.}
  1680. \label{fig:Lvar-concrete-syntax}
  1681. \end{figure}
  1682. \begin{figure}[tp]
  1683. \centering
  1684. \begin{tcolorbox}[colback=white]
  1685. {\if\edition\racketEd
  1686. \[
  1687. \begin{array}{l}
  1688. \gray{\LintASTRacket{}} \\ \hline
  1689. \LvarASTRacket \\
  1690. \begin{array}{rcl}
  1691. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1692. \end{array}
  1693. \end{array}
  1694. \]
  1695. \fi}
  1696. {\if\edition\pythonEd\pythonColor
  1697. \[
  1698. \begin{array}{l}
  1699. \gray{\LintASTPython}\\ \hline
  1700. \LvarASTPython \\
  1701. \begin{array}{rcl}
  1702. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1703. \end{array}
  1704. \end{array}
  1705. \]
  1706. \fi}
  1707. \end{tcolorbox}
  1708. \caption{The abstract syntax of \LangVar{}.}
  1709. \label{fig:Lvar-syntax}
  1710. \end{figure}
  1711. {\if\edition\racketEd
  1712. Let us dive further into the syntax and semantics of the \LangVar{}
  1713. language. The \key{let} feature defines a variable for use within its
  1714. body and initializes the variable with the value of an expression.
  1715. The abstract syntax for \key{let} is shown in
  1716. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1717. \begin{lstlisting}
  1718. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1719. \end{lstlisting}
  1720. For example, the following program initializes \code{x} to $32$ and then
  1721. evaluates the body \code{(+ 10 x)}, producing $42$.
  1722. \begin{lstlisting}
  1723. (let ([x (+ 12 20)]) (+ 10 x))
  1724. \end{lstlisting}
  1725. \fi}
  1726. %
  1727. {\if\edition\pythonEd\pythonColor
  1728. %
  1729. The \LangVar{} language includes an assignment statement, which defines a
  1730. variable for use in later statements and initializes the variable with
  1731. the value of an expression. The abstract syntax for assignment is
  1732. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1733. assignment is \index{subject}{Assign@\texttt{Assign}}
  1734. \begin{lstlisting}
  1735. |$\itm{var}$| = |$\itm{exp}$|
  1736. \end{lstlisting}
  1737. For example, the following program initializes the variable \code{x}
  1738. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1739. \begin{lstlisting}
  1740. x = 12 + 20
  1741. print(10 + x)
  1742. \end{lstlisting}
  1743. \fi}
  1744. {\if\edition\racketEd
  1745. %
  1746. When there are multiple \key{let}s for the same variable, the closest
  1747. enclosing \key{let} is used. That is, variable definitions overshadow
  1748. prior definitions. Consider the following program with two \key{let}s
  1749. that define two variables named \code{x}. Can you figure out the
  1750. result?
  1751. \begin{lstlisting}
  1752. (let ([x 32]) (+ (let ([x 10]) x) x))
  1753. \end{lstlisting}
  1754. For the purposes of depicting which variable occurrences correspond to
  1755. which definitions, the following shows the \code{x}'s annotated with
  1756. subscripts to distinguish them. Double-check that your answer for the
  1757. previous program is the same as your answer for this annotated version
  1758. of the program.
  1759. \begin{lstlisting}
  1760. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1761. \end{lstlisting}
  1762. The initializing expression is always evaluated before the body of the
  1763. \key{let}, so in the following, the \key{read} for \code{x} is
  1764. performed before the \key{read} for \code{y}. Given the input
  1765. $52$ then $10$, the following produces $42$ (not $-42$).
  1766. \begin{lstlisting}
  1767. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1768. \end{lstlisting}
  1769. \fi}
  1770. \subsection{Extensible Interpreters via Method Overriding}
  1771. \label{sec:extensible-interp}
  1772. \index{subject}{method overriding}
  1773. To prepare for discussing the interpreter of \LangVar{}, we explain
  1774. why we implement it in an object-oriented style. Throughout this book
  1775. we define many interpreters, one for each language that we
  1776. study. Because each language builds on the prior one, there is a lot
  1777. of commonality between these interpreters. We want to write down the
  1778. common parts just once instead of many times. A naive interpreter for
  1779. \LangVar{} would handle the \racket{cases for variables and
  1780. \code{let}} \python{case for variables} but dispatch to an
  1781. interpreter for \LangInt{} in the rest of the cases. The following
  1782. code sketches this idea. (We explain the \code{env} parameter in
  1783. section~\ref{sec:interp-Lvar}.)
  1784. \begin{center}
  1785. {\if\edition\racketEd
  1786. \begin{minipage}{0.45\textwidth}
  1787. \begin{lstlisting}
  1788. (define ((interp_Lint env) e)
  1789. (match e
  1790. [(Prim '- (list e1))
  1791. (fx- 0 ((interp_Lint env) e1))]
  1792. ...))
  1793. \end{lstlisting}
  1794. \end{minipage}
  1795. \begin{minipage}{0.45\textwidth}
  1796. \begin{lstlisting}
  1797. (define ((interp_Lvar env) e)
  1798. (match e
  1799. [(Var x)
  1800. (dict-ref env x)]
  1801. [(Let x e body)
  1802. (define v ((interp_Lvar env) e))
  1803. (define env^ (dict-set env x v))
  1804. ((interp_Lvar env^) body)]
  1805. [else ((interp_Lint env) e)]))
  1806. \end{lstlisting}
  1807. \end{minipage}
  1808. \fi}
  1809. {\if\edition\pythonEd\pythonColor
  1810. \begin{minipage}{0.45\textwidth}
  1811. \begin{lstlisting}
  1812. def interp_Lint(e, env):
  1813. match e:
  1814. case UnaryOp(USub(), e1):
  1815. return - interp_Lint(e1, env)
  1816. ...
  1817. \end{lstlisting}
  1818. \end{minipage}
  1819. \begin{minipage}{0.45\textwidth}
  1820. \begin{lstlisting}
  1821. def interp_Lvar(e, env):
  1822. match e:
  1823. case Name(id):
  1824. return env[id]
  1825. case _:
  1826. return interp_Lint(e, env)
  1827. \end{lstlisting}
  1828. \end{minipage}
  1829. \fi}
  1830. \end{center}
  1831. The problem with this naive approach is that it does not handle
  1832. situations in which an \LangVar{} feature, such as a variable, is
  1833. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1834. in the following program.
  1835. {\if\edition\racketEd
  1836. \begin{lstlisting}
  1837. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1838. \end{lstlisting}
  1839. \fi}
  1840. {\if\edition\pythonEd\pythonColor
  1841. \begin{minipage}{1.0\textwidth}
  1842. \begin{lstlisting}
  1843. y = 10
  1844. print(-y)
  1845. \end{lstlisting}
  1846. \end{minipage}
  1847. \fi}
  1848. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1849. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1850. then it recursively calls \code{interp\_Lint} again on its argument.
  1851. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1852. an error!
  1853. To make our interpreters extensible we need something called
  1854. \emph{open recursion}\index{subject}{open recursion}, in which the
  1855. tying of the recursive knot is delayed until the functions are
  1856. composed. Object-oriented languages provide open recursion via method
  1857. overriding. The following code uses
  1858. method overriding to interpret \LangInt{} and \LangVar{} using
  1859. %
  1860. \racket{the
  1861. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1862. \index{subject}{class} feature of Racket.}%
  1863. %
  1864. \python{a Python \code{class} definition.}
  1865. %
  1866. We define one class for each language and define a method for
  1867. interpreting expressions inside each class. The class for \LangVar{}
  1868. inherits from the class for \LangInt{}, and the method
  1869. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1870. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1871. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1872. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1873. \code{interp\_exp} in \LangInt{}.
  1874. \begin{center}
  1875. \hspace{-20pt}
  1876. {\if\edition\racketEd
  1877. \begin{minipage}{0.45\textwidth}
  1878. \begin{lstlisting}
  1879. (define interp-Lint-class
  1880. (class object%
  1881. (define/public ((interp_exp env) e)
  1882. (match e
  1883. [(Prim '- (list e))
  1884. (fx- 0 ((interp_exp env) e))]
  1885. ...))
  1886. ...))
  1887. \end{lstlisting}
  1888. \end{minipage}
  1889. \begin{minipage}{0.45\textwidth}
  1890. \begin{lstlisting}
  1891. (define interp-Lvar-class
  1892. (class interp-Lint-class
  1893. (define/override ((interp_exp env) e)
  1894. (match e
  1895. [(Var x)
  1896. (dict-ref env x)]
  1897. [(Let x e body)
  1898. (define v ((interp_exp env) e))
  1899. (define env^ (dict-set env x v))
  1900. ((interp_exp env^) body)]
  1901. [else
  1902. (super (interp_exp env) e)]))
  1903. ...
  1904. ))
  1905. \end{lstlisting}
  1906. \end{minipage}
  1907. \fi}
  1908. {\if\edition\pythonEd\pythonColor
  1909. \begin{minipage}{0.45\textwidth}
  1910. \begin{lstlisting}
  1911. class InterpLint:
  1912. def interp_exp(e):
  1913. match e:
  1914. case UnaryOp(USub(), e1):
  1915. return neg64(self.interp_exp(e1))
  1916. ...
  1917. ...
  1918. \end{lstlisting}
  1919. \end{minipage}
  1920. \begin{minipage}{0.45\textwidth}
  1921. \begin{lstlisting}
  1922. def InterpLvar(InterpLint):
  1923. def interp_exp(e):
  1924. match e:
  1925. case Name(id):
  1926. return env[id]
  1927. case _:
  1928. return super().interp_exp(e)
  1929. ...
  1930. \end{lstlisting}
  1931. \end{minipage}
  1932. \fi}
  1933. \end{center}
  1934. We return to the troublesome example, repeated here:
  1935. {\if\edition\racketEd
  1936. \begin{lstlisting}
  1937. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1938. \end{lstlisting}
  1939. \fi}
  1940. {\if\edition\pythonEd\pythonColor
  1941. \begin{lstlisting}
  1942. y = 10
  1943. print(-y)
  1944. \end{lstlisting}
  1945. \fi}
  1946. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1947. \racket{on this expression,}
  1948. \python{on the \code{-y} expression,}
  1949. %
  1950. which we call \code{e0}, by creating an object of the \LangVar{} class
  1951. and calling the \code{interp\_exp} method
  1952. {\if\edition\racketEd
  1953. \begin{lstlisting}
  1954. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1955. \end{lstlisting}
  1956. \fi}
  1957. {\if\edition\pythonEd\pythonColor
  1958. \begin{lstlisting}
  1959. InterpLvar().interp_exp(e0)
  1960. \end{lstlisting}
  1961. \fi}
  1962. \noindent To process the \code{-} operator, the default case of
  1963. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1964. method in \LangInt{}. But then for the recursive method call, it
  1965. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1966. \code{Var} node is handled correctly. Thus, method overriding gives us
  1967. the open recursion that we need to implement our interpreters in an
  1968. extensible way.
  1969. \subsection{Definitional Interpreter for \LangVar{}}
  1970. \label{sec:interp-Lvar}
  1971. Having justified the use of classes and methods to implement
  1972. interpreters, we revisit the definitional interpreter for \LangInt{}
  1973. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1974. create an interpreter for \LangVar{}, shown in
  1975. figure~\ref{fig:interp-Lvar}.
  1976. %
  1977. \python{We change the \code{interp\_stmt} method in the interpreter
  1978. for \LangInt{} to take two extra parameters named \code{env}, which
  1979. we discuss in the next paragraph, and \code{cont} for
  1980. \emph{continuation}, which is the technical name for what comes
  1981. after a particular point in a program. The \code{cont} parameter is
  1982. the list of statements that that follow the current statement. Note
  1983. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  1984. statement and passes the rest of the statements as the argument for
  1985. \code{cont}. This organization enables each statement to decide what
  1986. if anything should be evaluated after it, for example, allowing a
  1987. \code{return} statement to exit early from a function (see
  1988. Chapter~\ref{ch:Lfun}).}
  1989. The interpreter for \LangVar{} adds two new cases for
  1990. variables and \racket{\key{let}}\python{assignment}. For
  1991. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1992. value bound to a variable to all the uses of the variable. To
  1993. accomplish this, we maintain a mapping from variables to values called
  1994. an \emph{environment}\index{subject}{environment}.
  1995. %
  1996. We use
  1997. %
  1998. \racket{an association list (alist) }%
  1999. %
  2000. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2001. %
  2002. to represent the environment.
  2003. %
  2004. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2005. and the \code{racket/dict} package.}
  2006. %
  2007. The \code{interp\_exp} function takes the current environment,
  2008. \code{env}, as an extra parameter. When the interpreter encounters a
  2009. variable, it looks up the corresponding value in the environment. If
  2010. the variable is not in the environment (because the variable was not
  2011. defined) then the lookup will fail and the interpreter will
  2012. halt with an error. Recall that the compiler is not obligated to
  2013. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2014. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2015. prohibit access to undefined variables.}
  2016. %
  2017. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2018. initializing expression, extends the environment with the result
  2019. value bound to the variable, using \code{dict-set}, then evaluates
  2020. the body of the \key{Let}.}
  2021. %
  2022. \python{When the interpreter encounters an assignment, it evaluates
  2023. the initializing expression and then associates the resulting value
  2024. with the variable in the environment.}
  2025. \begin{figure}[tp]
  2026. \begin{tcolorbox}[colback=white]
  2027. {\if\edition\racketEd
  2028. \begin{lstlisting}
  2029. (define interp-Lint-class
  2030. (class object%
  2031. (super-new)
  2032. (define/public ((interp_exp env) e)
  2033. (match e
  2034. [(Int n) n]
  2035. [(Prim 'read '())
  2036. (define r (read))
  2037. (cond [(fixnum? r) r]
  2038. [else (error 'interp_exp "expected an integer" r)])]
  2039. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2040. [(Prim '+ (list e1 e2))
  2041. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2042. [(Prim '- (list e1 e2))
  2043. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2044. (define/public (interp_program p)
  2045. (match p
  2046. [(Program '() e) ((interp_exp '()) e)]))
  2047. ))
  2048. \end{lstlisting}
  2049. \fi}
  2050. {\if\edition\pythonEd\pythonColor
  2051. \begin{lstlisting}
  2052. class InterpLint:
  2053. def interp_exp(self, e, env):
  2054. match e:
  2055. case BinOp(left, Add(), right):
  2056. l = self.interp_exp(left, env)
  2057. r = self.interp_exp(right, env)
  2058. return add64(l, r)
  2059. case BinOp(left, Sub(), right):
  2060. l = self.interp_exp(left, env)
  2061. r = self.interp_exp(right, env)
  2062. return sub64(l, r)
  2063. case UnaryOp(USub(), v):
  2064. return neg64(self.interp_exp(v, env))
  2065. case Constant(value):
  2066. return value
  2067. case Call(Name('input_int'), []):
  2068. return int(input())
  2069. def interp_stmt(self, s, env, cont):
  2070. match s:
  2071. case Expr(Call(Name('print'), [arg])):
  2072. val = self.interp_exp(arg, env)
  2073. print(val, end='')
  2074. return self.interp_stmts(cont, env)
  2075. case Expr(value):
  2076. self.interp_exp(value, env)
  2077. return self.interp_stmts(cont, env)
  2078. case _:
  2079. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2080. def interp_stmts(self, ss, env):
  2081. match ss:
  2082. case []:
  2083. return 0
  2084. case [s, *ss]:
  2085. return self.interp_stmt(s, env, ss)
  2086. def interp(self, p):
  2087. match p:
  2088. case Module(body):
  2089. self.interp_stmts(body, {})
  2090. def interp_Lint(p):
  2091. return InterpLint().interp(p)
  2092. \end{lstlisting}
  2093. \fi}
  2094. \end{tcolorbox}
  2095. \caption{Interpreter for \LangInt{} as a class.}
  2096. \label{fig:interp-Lint-class}
  2097. \end{figure}
  2098. \begin{figure}[tp]
  2099. \begin{tcolorbox}[colback=white]
  2100. {\if\edition\racketEd
  2101. \begin{lstlisting}
  2102. (define interp-Lvar-class
  2103. (class interp-Lint-class
  2104. (super-new)
  2105. (define/override ((interp_exp env) e)
  2106. (match e
  2107. [(Var x) (dict-ref env x)]
  2108. [(Let x e body)
  2109. (define new-env (dict-set env x ((interp_exp env) e)))
  2110. ((interp_exp new-env) body)]
  2111. [else ((super interp_exp env) e)]))
  2112. ))
  2113. (define (interp_Lvar p)
  2114. (send (new interp-Lvar-class) interp_program p))
  2115. \end{lstlisting}
  2116. \fi}
  2117. {\if\edition\pythonEd\pythonColor
  2118. \begin{lstlisting}
  2119. class InterpLvar(InterpLint):
  2120. def interp_exp(self, e, env):
  2121. match e:
  2122. case Name(id):
  2123. return env[id]
  2124. case _:
  2125. return super().interp_exp(e, env)
  2126. def interp_stmt(self, s, env, cont):
  2127. match s:
  2128. case Assign([lhs], value):
  2129. env[lhs.id] = self.interp_exp(value, env)
  2130. return self.interp_stmts(cont, env)
  2131. case _:
  2132. return super().interp_stmt(s, env, cont)
  2133. def interp_Lvar(p):
  2134. return InterpLvar().interp(p)
  2135. \end{lstlisting}
  2136. \fi}
  2137. \end{tcolorbox}
  2138. \caption{Interpreter for the \LangVar{} language.}
  2139. \label{fig:interp-Lvar}
  2140. \end{figure}
  2141. {\if\edition\racketEd
  2142. \begin{figure}[tp]
  2143. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2144. \small
  2145. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2146. An \emph{association list} (called an alist) is a list of key-value pairs.
  2147. For example, we can map people to their ages with an alist
  2148. \index{subject}{alist}\index{subject}{association list}
  2149. \begin{lstlisting}[basicstyle=\ttfamily]
  2150. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2151. \end{lstlisting}
  2152. The \emph{dictionary} interface is for mapping keys to values.
  2153. Every alist implements this interface. \index{subject}{dictionary}
  2154. The package
  2155. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2156. provides many functions for working with dictionaries, such as
  2157. \begin{description}
  2158. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2159. returns the value associated with the given $\itm{key}$.
  2160. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2161. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2162. and otherwise is the same as $\itm{dict}$.
  2163. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2164. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2165. of keys and values in $\itm{dict}$. For example, the following
  2166. creates a new alist in which the ages are incremented:
  2167. \end{description}
  2168. \vspace{-10pt}
  2169. \begin{lstlisting}[basicstyle=\ttfamily]
  2170. (for/list ([(k v) (in-dict ages)])
  2171. (cons k (add1 v)))
  2172. \end{lstlisting}
  2173. \end{tcolorbox}
  2174. %\end{wrapfigure}
  2175. \caption{Association lists implement the dictionary interface.}
  2176. \label{fig:alist}
  2177. \end{figure}
  2178. \fi}
  2179. The goal for this chapter is to implement a compiler that translates
  2180. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2181. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2182. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2183. That is, they output the same integer $n$. We depict this correctness
  2184. criteria in the following diagram:
  2185. \[
  2186. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2187. \node (p1) at (0, 0) {$P_1$};
  2188. \node (p2) at (4, 0) {$P_2$};
  2189. \node (o) at (4, -2) {$n$};
  2190. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2191. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2192. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2193. \end{tikzpicture}
  2194. \]
  2195. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2196. compiling \LangVar{}.
  2197. \section{The \LangXInt{} Assembly Language}
  2198. \label{sec:x86}
  2199. \index{subject}{x86}
  2200. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2201. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2202. assembler.
  2203. %
  2204. A program begins with a \code{main} label followed by a sequence of
  2205. instructions. The \key{globl} directive makes the \key{main} procedure
  2206. externally visible so that the operating system can call it.
  2207. %
  2208. An x86 program is stored in the computer's memory. For our purposes,
  2209. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2210. values. The computer has a \emph{program counter}
  2211. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2212. \code{rip} register that points to the address of the next instruction
  2213. to be executed. For most instructions, the program counter is
  2214. incremented after the instruction is executed so that it points to the
  2215. next instruction in memory. Most x86 instructions take two operands,
  2216. each of which is an integer constant (called an \emph{immediate
  2217. value}\index{subject}{immediate value}), a
  2218. \emph{register}\index{subject}{register}, or a memory location.
  2219. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2220. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2221. && \key{r8} \MID \key{r9} \MID \key{r10}
  2222. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2223. \MID \key{r14} \MID \key{r15}}
  2224. \newcommand{\GrammarXInt}{
  2225. \begin{array}{rcl}
  2226. \Reg &::=& \allregisters{} \\
  2227. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2228. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2229. \key{subq} \; \Arg\key{,} \Arg \MID
  2230. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2231. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2232. \key{callq} \; \mathit{label} \MID
  2233. \key{retq} \MID
  2234. \key{jmp}\,\itm{label} \MID \\
  2235. && \itm{label}\key{:}\; \Instr
  2236. \end{array}
  2237. }
  2238. \begin{figure}[tp]
  2239. \begin{tcolorbox}[colback=white]
  2240. {\if\edition\racketEd
  2241. \[
  2242. \begin{array}{l}
  2243. \GrammarXInt \\
  2244. \begin{array}{lcl}
  2245. \LangXIntM{} &::= & \key{.globl main}\\
  2246. & & \key{main:} \; \Instr\ldots
  2247. \end{array}
  2248. \end{array}
  2249. \]
  2250. \fi}
  2251. {\if\edition\pythonEd\pythonColor
  2252. \[
  2253. \begin{array}{lcl}
  2254. \Reg &::=& \allregisters{} \\
  2255. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2256. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2257. \key{subq} \; \Arg\key{,} \Arg \MID
  2258. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2259. && \key{callq} \; \mathit{label} \MID
  2260. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2261. \LangXIntM{} &::= & \key{.globl main}\\
  2262. & & \key{main:} \; \Instr^{*}
  2263. \end{array}
  2264. \]
  2265. \fi}
  2266. \end{tcolorbox}
  2267. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2268. \label{fig:x86-int-concrete}
  2269. \end{figure}
  2270. A register is a special kind of variable that holds a 64-bit
  2271. value. There are 16 general-purpose registers in the computer; their
  2272. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2273. written with a percent sign, \key{\%}, followed by the register name,
  2274. for example \key{\%rax}.
  2275. An immediate value is written using the notation \key{\$}$n$ where $n$
  2276. is an integer.
  2277. %
  2278. %
  2279. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2280. which obtains the address stored in register $r$ and then adds $n$
  2281. bytes to the address. The resulting address is used to load or to store
  2282. to memory depending on whether it occurs as a source or destination
  2283. argument of an instruction.
  2284. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2285. the source $s$ and destination $d$, applies the arithmetic operation,
  2286. and then writes the result to the destination $d$. \index{subject}{instruction}
  2287. %
  2288. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2289. stores the result in $d$.
  2290. %
  2291. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2292. specified by the label, and $\key{retq}$ returns from a procedure to
  2293. its caller.
  2294. %
  2295. We discuss procedure calls in more detail further in this chapter and
  2296. in chapter~\ref{ch:Lfun}.
  2297. %
  2298. The last letter \key{q} indicates that these instructions operate on
  2299. quadwords, which are 64-bit values.
  2300. %
  2301. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2302. counter to the address of the instruction immediately after the
  2303. specified label.}
  2304. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2305. all the x86 instructions used in this book.
  2306. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2307. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2308. \lstinline{movq $10, %rax}
  2309. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2310. adds $32$ to the $10$ in \key{rax} and
  2311. puts the result, $42$, into \key{rax}.
  2312. %
  2313. The last instruction \key{retq} finishes the \key{main} function by
  2314. returning the integer in \key{rax} to the operating system. The
  2315. operating system interprets this integer as the program's exit
  2316. code. By convention, an exit code of 0 indicates that a program has
  2317. completed successfully, and all other exit codes indicate various
  2318. errors.
  2319. %
  2320. \racket{However, in this book we return the result of the program
  2321. as the exit code.}
  2322. \begin{figure}[tbp]
  2323. \begin{minipage}{0.45\textwidth}
  2324. \begin{tcolorbox}[colback=white]
  2325. \begin{lstlisting}
  2326. .globl main
  2327. main:
  2328. movq $10, %rax
  2329. addq $32, %rax
  2330. retq
  2331. \end{lstlisting}
  2332. \end{tcolorbox}
  2333. \end{minipage}
  2334. \caption{An x86 program that computes
  2335. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2336. \label{fig:p0-x86}
  2337. \end{figure}
  2338. We exhibit the use of memory for storing intermediate results in the
  2339. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2340. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2341. uses a region of memory called the \emph{procedure call stack}
  2342. (\emph{stack} for
  2343. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2344. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2345. for each procedure call. The memory layout for an individual frame is
  2346. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2347. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2348. address of the item at the top of the stack. In general, we use the
  2349. term \emph{pointer}\index{subject}{pointer} for something that
  2350. contains an address. The stack grows downward in memory, so we
  2351. increase the size of the stack by subtracting from the stack pointer.
  2352. In the context of a procedure call, the \emph{return
  2353. address}\index{subject}{return address} is the location of the
  2354. instruction that immediately follows the call instruction on the
  2355. caller side. The function call instruction, \code{callq}, pushes the
  2356. return address onto the stack prior to jumping to the procedure. The
  2357. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2358. pointer} and is used to access variables that are stored in the
  2359. frame of the current procedure call. The base pointer of the caller
  2360. is stored immediately after the return address.
  2361. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2362. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2363. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2364. $-16\key{(\%rbp)}$, and so on.
  2365. \begin{figure}[tbp]
  2366. \begin{minipage}{0.66\textwidth}
  2367. \begin{tcolorbox}[colback=white]
  2368. {\if\edition\racketEd
  2369. \begin{lstlisting}
  2370. start:
  2371. movq $10, -8(%rbp)
  2372. negq -8(%rbp)
  2373. movq -8(%rbp), %rax
  2374. addq $52, %rax
  2375. jmp conclusion
  2376. .globl main
  2377. main:
  2378. pushq %rbp
  2379. movq %rsp, %rbp
  2380. subq $16, %rsp
  2381. jmp start
  2382. conclusion:
  2383. addq $16, %rsp
  2384. popq %rbp
  2385. retq
  2386. \end{lstlisting}
  2387. \fi}
  2388. {\if\edition\pythonEd\pythonColor
  2389. \begin{lstlisting}
  2390. .globl main
  2391. main:
  2392. pushq %rbp
  2393. movq %rsp, %rbp
  2394. subq $16, %rsp
  2395. movq $10, -8(%rbp)
  2396. negq -8(%rbp)
  2397. movq -8(%rbp), %rax
  2398. addq $52, %rax
  2399. addq $16, %rsp
  2400. popq %rbp
  2401. retq
  2402. \end{lstlisting}
  2403. \fi}
  2404. \end{tcolorbox}
  2405. \end{minipage}
  2406. \caption{An x86 program that computes
  2407. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2408. \label{fig:p1-x86}
  2409. \end{figure}
  2410. \begin{figure}[tbp]
  2411. \begin{minipage}{0.66\textwidth}
  2412. \begin{tcolorbox}[colback=white]
  2413. \centering
  2414. \begin{tabular}{|r|l|} \hline
  2415. Position & Contents \\ \hline
  2416. $8$(\key{\%rbp}) & return address \\
  2417. $0$(\key{\%rbp}) & old \key{rbp} \\
  2418. $-8$(\key{\%rbp}) & variable $1$ \\
  2419. $-16$(\key{\%rbp}) & variable $2$ \\
  2420. \ldots & \ldots \\
  2421. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2422. \end{tabular}
  2423. \end{tcolorbox}
  2424. \end{minipage}
  2425. \caption{Memory layout of a frame.}
  2426. \label{fig:frame}
  2427. \end{figure}
  2428. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2429. is transferred from the operating system to the \code{main} function.
  2430. The operating system issues a \code{callq main} instruction that
  2431. pushes its return address on the stack and then jumps to
  2432. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2433. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2434. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2435. out of alignment (because the \code{callq} pushed the return address).
  2436. The first three instructions are the typical
  2437. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2438. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2439. pointer \code{rsp} and then saves the base pointer of the caller at
  2440. address \code{rsp} on the stack. The next instruction \code{movq
  2441. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2442. which is pointing to the location of the old base pointer. The
  2443. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2444. make enough room for storing variables. This program needs one
  2445. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2446. 16-byte-aligned, and then we are ready to make calls to other functions.
  2447. \racket{The last instruction of the prelude is \code{jmp start}, which
  2448. transfers control to the instructions that were generated from the
  2449. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2450. \racket{The first instruction under the \code{start} label is}
  2451. %
  2452. \python{The first instruction after the prelude is}
  2453. %
  2454. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2455. %
  2456. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2457. $1$ to $-10$.
  2458. %
  2459. The next instruction moves the $-10$ from variable $1$ into the
  2460. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2461. the value in \code{rax}, updating its contents to $42$.
  2462. \racket{The three instructions under the label \code{conclusion} are the
  2463. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2464. %
  2465. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2466. \code{main} function consists of the last three instructions.}
  2467. %
  2468. The first two restore the \code{rsp} and \code{rbp} registers to their
  2469. states at the beginning of the procedure. In particular,
  2470. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2471. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2472. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2473. \key{retq}, jumps back to the procedure that called this one and adds
  2474. $8$ to the stack pointer.
  2475. Our compiler needs a convenient representation for manipulating x86
  2476. programs, so we define an abstract syntax for x86, shown in
  2477. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2478. \LangXInt{}.
  2479. %
  2480. {\if\edition\pythonEd\pythonColor%
  2481. The main difference between this and the concrete syntax of \LangXInt{}
  2482. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2483. names, and register names are explicitly represented by strings.
  2484. \fi} %
  2485. {\if\edition\racketEd
  2486. The main difference between this and the concrete syntax of \LangXInt{}
  2487. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2488. front of every instruction. Instead instructions are grouped into
  2489. \emph{basic blocks}\index{subject}{basic block} with a
  2490. label associated with every basic block; this is why the \key{X86Program}
  2491. struct includes an alist mapping labels to basic blocks. The reason for this
  2492. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2493. introduce conditional branching. The \code{Block} structure includes
  2494. an $\itm{info}$ field that is not needed in this chapter but becomes
  2495. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2496. $\itm{info}$ field should contain an empty list.
  2497. \fi}
  2498. %
  2499. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2500. node includes an integer for representing the arity of the function,
  2501. that is, the number of arguments, which is helpful to know during
  2502. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2503. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2504. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2505. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2506. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2507. \MID \skey{r14} \MID \skey{r15}}
  2508. \newcommand{\ASTXIntRacket}{
  2509. \begin{array}{lcl}
  2510. \Reg &::=& \allregisters{} \\
  2511. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2512. \MID \DEREF{\Reg}{\Int} \\
  2513. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2514. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2515. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2516. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2517. &\MID& \PUSHQ{\Arg}
  2518. \MID \POPQ{\Arg} \\
  2519. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2520. \MID \RETQ{}
  2521. \MID \JMP{\itm{label}} \\
  2522. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2523. \end{array}
  2524. }
  2525. \newcommand{\ASTXIntPython}{
  2526. \begin{array}{lcl}
  2527. \Reg &::=& \allregisters{} \\
  2528. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2529. \MID \DEREF{\Reg}{\Int} \\
  2530. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2531. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2532. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2533. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2534. &\MID& \PUSHQ{\Arg}
  2535. \MID \POPQ{\Arg} \\
  2536. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2537. \MID \RETQ{}
  2538. \MID \JMP{\itm{label}} \\
  2539. \Block &::= & \Instr^{+}
  2540. \end{array}
  2541. }
  2542. \begin{figure}[tp]
  2543. \begin{tcolorbox}[colback=white]
  2544. \small
  2545. {\if\edition\racketEd
  2546. \[\arraycolsep=3pt
  2547. \begin{array}{l}
  2548. \ASTXIntRacket \\
  2549. \begin{array}{lcl}
  2550. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2551. \end{array}
  2552. \end{array}
  2553. \]
  2554. \fi}
  2555. {\if\edition\pythonEd\pythonColor
  2556. \[
  2557. \begin{array}{lcl}
  2558. \Reg &::=& \allastregisters{} \\
  2559. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2560. \MID \DEREF{\Reg}{\Int} \\
  2561. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2562. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2563. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2564. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2565. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2566. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2567. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2568. \end{array}
  2569. \]
  2570. \fi}
  2571. \end{tcolorbox}
  2572. \caption{The abstract syntax of \LangXInt{} assembly.}
  2573. \label{fig:x86-int-ast}
  2574. \end{figure}
  2575. \section{Planning the Trip to x86}
  2576. \label{sec:plan-s0-x86}
  2577. To compile one language to another, it helps to focus on the
  2578. differences between the two languages because the compiler will need
  2579. to bridge those differences. What are the differences between \LangVar{}
  2580. and x86 assembly? Here are some of the most important ones:
  2581. \begin{enumerate}
  2582. \item x86 arithmetic instructions typically have two arguments and
  2583. update the second argument in place. In contrast, \LangVar{}
  2584. arithmetic operations take two arguments and produce a new value.
  2585. An x86 instruction may have at most one memory-accessing argument.
  2586. Furthermore, some x86 instructions place special restrictions on
  2587. their arguments.
  2588. \item An argument of an \LangVar{} operator can be a deeply nested
  2589. expression, whereas x86 instructions restrict their arguments to be
  2590. integer constants, registers, and memory locations.
  2591. {\if\edition\racketEd
  2592. \item The order of execution in x86 is explicit in the syntax, which
  2593. is a sequence of instructions and jumps to labeled positions,
  2594. whereas in \LangVar{} the order of evaluation is a left-to-right
  2595. depth-first traversal of the abstract syntax tree. \fi}
  2596. \item A program in \LangVar{} can have any number of variables,
  2597. whereas x86 has 16 registers and the procedure call stack.
  2598. {\if\edition\racketEd
  2599. \item Variables in \LangVar{} can shadow other variables with the
  2600. same name. In x86, registers have unique names, and memory locations
  2601. have unique addresses.
  2602. \fi}
  2603. \end{enumerate}
  2604. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2605. down the problem into several steps, which deal with these differences
  2606. one at a time. Each of these steps is called a \emph{pass} of the
  2607. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2608. %
  2609. This term indicates that each step passes over, or traverses, the AST
  2610. of the program.
  2611. %
  2612. Furthermore, we follow the nanopass approach, which means that we
  2613. strive for each pass to accomplish one clear objective rather than two
  2614. or three at the same time.
  2615. %
  2616. We begin by sketching how we might implement each pass and give each
  2617. pass a name. We then figure out an ordering of the passes and the
  2618. input/output language for each pass. The very first pass has
  2619. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2620. its output language. In between these two passes, we can choose
  2621. whichever language is most convenient for expressing the output of
  2622. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2623. \emph{intermediate language} of our own design. Finally, to
  2624. implement each pass we write one recursive function per nonterminal in
  2625. the grammar of the input language of the pass.
  2626. \index{subject}{intermediate language}
  2627. Our compiler for \LangVar{} consists of the following passes:
  2628. %
  2629. \begin{description}
  2630. {\if\edition\racketEd
  2631. \item[\key{uniquify}] deals with the shadowing of variables by
  2632. renaming every variable to a unique name.
  2633. \fi}
  2634. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2635. of a primitive operation or function call is a variable or integer,
  2636. that is, an \emph{atomic} expression. We refer to nonatomic
  2637. expressions as \emph{complex}. This pass introduces temporary
  2638. variables to hold the results of complex
  2639. subexpressions.\index{subject}{atomic
  2640. expression}\index{subject}{complex expression}%
  2641. {\if\edition\racketEd
  2642. \item[\key{explicate\_control}] makes the execution order of the
  2643. program explicit. It converts the abstract syntax tree
  2644. representation into a graph in which each node is a labeled sequence
  2645. of statements and the edges are \code{goto} statements.
  2646. \fi}
  2647. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2648. handles the difference between
  2649. \LangVar{} operations and x86 instructions. This pass converts each
  2650. \LangVar{} operation to a short sequence of instructions that
  2651. accomplishes the same task.
  2652. \item[\key{assign\_homes}] replaces variables with registers or stack
  2653. locations.
  2654. \end{description}
  2655. %
  2656. {\if\edition\racketEd
  2657. %
  2658. Our treatment of \code{remove\_complex\_operands} and
  2659. \code{explicate\_control} as separate passes is an example of the
  2660. nanopass approach.\footnote{For analogous decompositions of the
  2661. translation into continuation passing style, see the work of
  2662. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2663. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2664. %
  2665. \fi}
  2666. The next question is, in what order should we apply these passes? This
  2667. question can be challenging because it is difficult to know ahead of
  2668. time which orderings will be better (that is, will be easier to
  2669. implement, produce more efficient code, and so on), and therefore
  2670. ordering often involves trial and error. Nevertheless, we can plan
  2671. ahead and make educated choices regarding the ordering.
  2672. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2673. \key{uniquify}? The \key{uniquify} pass should come first because
  2674. \key{explicate\_control} changes all the \key{let}-bound variables to
  2675. become local variables whose scope is the entire program, which would
  2676. confuse variables with the same name.}
  2677. %
  2678. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2679. because the later removes the \key{let} form, but it is convenient to
  2680. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2681. %
  2682. \racket{The ordering of \key{uniquify} with respect to
  2683. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2684. \key{uniquify} to come first.}
  2685. The \key{select\_instructions} and \key{assign\_homes} passes are
  2686. intertwined.
  2687. %
  2688. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2689. passing arguments to functions and that it is preferable to assign
  2690. parameters to their corresponding registers. This suggests that it
  2691. would be better to start with the \key{select\_instructions} pass,
  2692. which generates the instructions for argument passing, before
  2693. performing register allocation.
  2694. %
  2695. On the other hand, by selecting instructions first we may run into a
  2696. dead end in \key{assign\_homes}. Recall that only one argument of an
  2697. x86 instruction may be a memory access, but \key{assign\_homes} might
  2698. be forced to assign both arguments to memory locations.
  2699. %
  2700. A sophisticated approach is to repeat the two passes until a solution
  2701. is found. However, to reduce implementation complexity we recommend
  2702. placing \key{select\_instructions} first, followed by the
  2703. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2704. that uses a reserved register to fix outstanding problems.
  2705. \begin{figure}[tbp]
  2706. \begin{tcolorbox}[colback=white]
  2707. {\if\edition\racketEd
  2708. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2709. \node (Lvar) at (0,2) {\large \LangVar{}};
  2710. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2711. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2712. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2713. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2714. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2715. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2716. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2717. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2718. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2719. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2720. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2721. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2722. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2723. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2724. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2725. \end{tikzpicture}
  2726. \fi}
  2727. {\if\edition\pythonEd\pythonColor
  2728. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2729. \node (Lvar) at (0,2) {\large \LangVar{}};
  2730. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2731. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2732. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2733. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2734. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2735. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2736. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2737. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2738. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2739. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2740. \end{tikzpicture}
  2741. \fi}
  2742. \end{tcolorbox}
  2743. \caption{Diagram of the passes for compiling \LangVar{}. }
  2744. \label{fig:Lvar-passes}
  2745. \end{figure}
  2746. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2747. passes and identifies the input and output language of each pass.
  2748. %
  2749. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2750. language, which extends \LangXInt{} with an unbounded number of
  2751. program-scope variables and removes the restrictions regarding
  2752. instruction arguments.
  2753. %
  2754. The last pass, \key{prelude\_and\_conclusion}, places the program
  2755. instructions inside a \code{main} function with instructions for the
  2756. prelude and conclusion.
  2757. %
  2758. \racket{In the next section we discuss the \LangCVar{} intermediate
  2759. language that serves as the output of \code{explicate\_control}.}
  2760. %
  2761. The remainder of this chapter provides guidance on the implementation
  2762. of each of the compiler passes represented in
  2763. figure~\ref{fig:Lvar-passes}.
  2764. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2765. %% are programs that are still in the \LangVar{} language, though the
  2766. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2767. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2768. %% %
  2769. %% The output of \code{explicate\_control} is in an intermediate language
  2770. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2771. %% syntax, which we introduce in the next section. The
  2772. %% \key{select-instruction} pass translates from \LangCVar{} to
  2773. %% \LangXVar{}. The \key{assign-homes} and
  2774. %% \key{patch-instructions}
  2775. %% passes input and output variants of x86 assembly.
  2776. \newcommand{\CvarGrammarRacket}{
  2777. \begin{array}{lcl}
  2778. \Atm &::=& \Int \MID \Var \\
  2779. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2780. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2781. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2782. \end{array}
  2783. }
  2784. \newcommand{\CvarASTRacket}{
  2785. \begin{array}{lcl}
  2786. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2787. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2788. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2789. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2790. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2791. \end{array}
  2792. }
  2793. {\if\edition\racketEd
  2794. \subsection{The \LangCVar{} Intermediate Language}
  2795. The output of \code{explicate\_control} is similar to the C
  2796. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2797. categories for expressions and statements, so we name it \LangCVar{}.
  2798. This style of intermediate language is also known as
  2799. \emph{three-address code}, to emphasize that the typical form of a
  2800. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2801. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2802. The concrete syntax for \LangCVar{} is shown in
  2803. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2804. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2805. %
  2806. The \LangCVar{} language supports the same operators as \LangVar{} but
  2807. the arguments of operators are restricted to atomic
  2808. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2809. assignment statements that can be executed in sequence using the
  2810. \key{Seq} form. A sequence of statements always ends with
  2811. \key{Return}, a guarantee that is baked into the grammar rules for
  2812. \itm{tail}. The naming of this nonterminal comes from the term
  2813. \emph{tail position}\index{subject}{tail position}, which refers to an
  2814. expression that is the last one to execute within a function or
  2815. program.
  2816. A \LangCVar{} program consists of an alist mapping labels to
  2817. tails. This is more general than necessary for the present chapter, as
  2818. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2819. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2820. there is just one label, \key{start}, and the whole program is
  2821. its tail.
  2822. %
  2823. The $\itm{info}$ field of the \key{CProgram} form, after the
  2824. \code{explicate\_control} pass, contains an alist that associates the
  2825. symbol \key{locals} with a list of all the variables used in the
  2826. program. At the start of the program, these variables are
  2827. uninitialized; they become initialized on their first assignment.
  2828. \begin{figure}[tbp]
  2829. \begin{tcolorbox}[colback=white]
  2830. \[
  2831. \begin{array}{l}
  2832. \CvarGrammarRacket \\
  2833. \begin{array}{lcl}
  2834. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2835. \end{array}
  2836. \end{array}
  2837. \]
  2838. \end{tcolorbox}
  2839. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2840. \label{fig:c0-concrete-syntax}
  2841. \end{figure}
  2842. \begin{figure}[tbp]
  2843. \begin{tcolorbox}[colback=white]
  2844. \[
  2845. \begin{array}{l}
  2846. \CvarASTRacket \\
  2847. \begin{array}{lcl}
  2848. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2849. \end{array}
  2850. \end{array}
  2851. \]
  2852. \end{tcolorbox}
  2853. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2854. \label{fig:c0-syntax}
  2855. \end{figure}
  2856. The definitional interpreter for \LangCVar{} is in the support code,
  2857. in the file \code{interp-Cvar.rkt}.
  2858. \fi}
  2859. {\if\edition\racketEd
  2860. \section{Uniquify Variables}
  2861. \label{sec:uniquify-Lvar}
  2862. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2863. with a unique name. Both the input and output of the \code{uniquify}
  2864. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2865. should translate the program on the left into the program on the
  2866. right.
  2867. \begin{transformation}
  2868. \begin{lstlisting}
  2869. (let ([x 32])
  2870. (+ (let ([x 10]) x) x))
  2871. \end{lstlisting}
  2872. \compilesto
  2873. \begin{lstlisting}
  2874. (let ([x.1 32])
  2875. (+ (let ([x.2 10]) x.2) x.1))
  2876. \end{lstlisting}
  2877. \end{transformation}
  2878. The following is another example translation, this time of a program
  2879. with a \key{let} nested inside the initializing expression of another
  2880. \key{let}.
  2881. \begin{transformation}
  2882. \begin{lstlisting}
  2883. (let ([x (let ([x 4])
  2884. (+ x 1))])
  2885. (+ x 2))
  2886. \end{lstlisting}
  2887. \compilesto
  2888. \begin{lstlisting}
  2889. (let ([x.2 (let ([x.1 4])
  2890. (+ x.1 1))])
  2891. (+ x.2 2))
  2892. \end{lstlisting}
  2893. \end{transformation}
  2894. We recommend implementing \code{uniquify} by creating a structurally
  2895. recursive function named \code{uniquify\_exp} that does little other
  2896. than copy an expression. However, when encountering a \key{let}, it
  2897. should generate a unique name for the variable and associate the old
  2898. name with the new name in an alist.\footnote{The Racket function
  2899. \code{gensym} is handy for generating unique variable names.} The
  2900. \code{uniquify\_exp} function needs to access this alist when it gets
  2901. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2902. for the alist.
  2903. The skeleton of the \code{uniquify\_exp} function is shown in
  2904. figure~\ref{fig:uniquify-Lvar}.
  2905. %% The function is curried so that it is
  2906. %% convenient to partially apply it to an alist and then apply it to
  2907. %% different expressions, as in the last case for primitive operations in
  2908. %% figure~\ref{fig:uniquify-Lvar}.
  2909. The
  2910. %
  2911. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2912. %
  2913. form of Racket is useful for transforming the element of a list to
  2914. produce a new list.\index{subject}{for/list}
  2915. \begin{figure}[tbp]
  2916. \begin{tcolorbox}[colback=white]
  2917. \begin{lstlisting}
  2918. (define (uniquify_exp env)
  2919. (lambda (e)
  2920. (match e
  2921. [(Var x) ___]
  2922. [(Int n) (Int n)]
  2923. [(Let x e body) ___]
  2924. [(Prim op es)
  2925. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2926. (define (uniquify p)
  2927. (match p
  2928. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2929. \end{lstlisting}
  2930. \end{tcolorbox}
  2931. \caption{Skeleton for the \key{uniquify} pass.}
  2932. \label{fig:uniquify-Lvar}
  2933. \end{figure}
  2934. \begin{exercise}
  2935. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2936. Complete the \code{uniquify} pass by filling in the blanks in
  2937. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2938. variables and for the \key{let} form in the file \code{compiler.rkt}
  2939. in the support code.
  2940. \end{exercise}
  2941. \begin{exercise}
  2942. \normalfont\normalsize
  2943. \label{ex:Lvar}
  2944. Create five \LangVar{} programs that exercise the most interesting
  2945. parts of the \key{uniquify} pass; that is, the programs should include
  2946. \key{let} forms, variables, and variables that shadow each other.
  2947. The five programs should be placed in the subdirectory named
  2948. \key{tests}, and the file names should start with \code{var\_test\_}
  2949. followed by a unique integer and end with the file extension
  2950. \key{.rkt}.
  2951. %
  2952. The \key{run-tests.rkt} script in the support code checks whether the
  2953. output programs produce the same result as the input programs. The
  2954. script uses the \key{interp-tests} function
  2955. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2956. your \key{uniquify} pass on the example programs. The \code{passes}
  2957. parameter of \key{interp-tests} is a list that should have one entry
  2958. for each pass in your compiler. For now, define \code{passes} to
  2959. contain just one entry for \code{uniquify} as follows:
  2960. \begin{lstlisting}
  2961. (define passes
  2962. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2963. \end{lstlisting}
  2964. Run the \key{run-tests.rkt} script in the support code to check
  2965. whether the output programs produce the same result as the input
  2966. programs.
  2967. \end{exercise}
  2968. \fi}
  2969. \section{Remove Complex Operands}
  2970. \label{sec:remove-complex-opera-Lvar}
  2971. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2972. into a restricted form in which the arguments of operations are atomic
  2973. expressions. Put another way, this pass removes complex
  2974. operands\index{subject}{complex operand}, such as the expression
  2975. \racket{\code{(- 10)}}\python{\code{-10}}
  2976. in the following program. This is accomplished by introducing a new
  2977. temporary variable, assigning the complex operand to the new
  2978. variable, and then using the new variable in place of the complex
  2979. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2980. right.
  2981. {\if\edition\racketEd
  2982. \begin{transformation}
  2983. % var_test_19.rkt
  2984. \begin{lstlisting}
  2985. (let ([x (+ 42 (- 10))])
  2986. (+ x 10))
  2987. \end{lstlisting}
  2988. \compilesto
  2989. \begin{lstlisting}
  2990. (let ([x (let ([tmp.1 (- 10)])
  2991. (+ 42 tmp.1))])
  2992. (+ x 10))
  2993. \end{lstlisting}
  2994. \end{transformation}
  2995. \fi}
  2996. {\if\edition\pythonEd\pythonColor
  2997. \begin{transformation}
  2998. \begin{lstlisting}
  2999. x = 42 + -10
  3000. print(x + 10)
  3001. \end{lstlisting}
  3002. \compilesto
  3003. \begin{lstlisting}
  3004. tmp_0 = -10
  3005. x = 42 + tmp_0
  3006. tmp_1 = x + 10
  3007. print(tmp_1)
  3008. \end{lstlisting}
  3009. \end{transformation}
  3010. \fi}
  3011. \newcommand{\LvarMonadASTRacket}{
  3012. \begin{array}{rcl}
  3013. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3014. \Exp &::=& \Atm \MID \READ{} \\
  3015. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3016. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3017. \end{array}
  3018. }
  3019. \newcommand{\LvarMonadASTPython}{
  3020. \begin{array}{rcl}
  3021. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3022. \Exp{} &::=& \Atm \MID \READ{} \\
  3023. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  3024. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3025. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3026. \end{array}
  3027. }
  3028. \begin{figure}[tp]
  3029. \centering
  3030. \begin{tcolorbox}[colback=white]
  3031. {\if\edition\racketEd
  3032. \[
  3033. \begin{array}{l}
  3034. \LvarMonadASTRacket \\
  3035. \begin{array}{rcl}
  3036. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3037. \end{array}
  3038. \end{array}
  3039. \]
  3040. \fi}
  3041. {\if\edition\pythonEd\pythonColor
  3042. \[
  3043. \begin{array}{l}
  3044. \LvarMonadASTPython \\
  3045. \begin{array}{rcl}
  3046. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3047. \end{array}
  3048. \end{array}
  3049. \]
  3050. \fi}
  3051. \end{tcolorbox}
  3052. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3053. atomic expressions.}
  3054. \label{fig:Lvar-anf-syntax}
  3055. \end{figure}
  3056. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3057. of this pass, the language \LangVarANF{}. The only difference is that
  3058. operator arguments are restricted to be atomic expressions that are
  3059. defined by the \Atm{} nonterminal. In particular, integer constants
  3060. and variables are atomic.
  3061. The atomic expressions are pure (they do not cause or depend on side
  3062. effects) whereas complex expressions may have side effects, such as
  3063. \READ{}. A language with this separation between pure expressions
  3064. versus expressions with side effects is said to be in monadic normal
  3065. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3066. in the name \LangVarANF{}. An important invariant of the
  3067. \code{remove\_complex\_operands} pass is that the relative ordering
  3068. among complex expressions is not changed, but the relative ordering
  3069. between atomic expressions and complex expressions can change and
  3070. often does. The reason that these changes are behavior preserving is
  3071. that the atomic expressions are pure.
  3072. {\if\edition\racketEd
  3073. Another well-known form for intermediate languages is the
  3074. \emph{administrative normal form}
  3075. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3076. \index{subject}{administrative normal form} \index{subject}{ANF}
  3077. %
  3078. The \LangVarANF{} language is not quite in ANF because it allows the
  3079. right-hand side of a \code{let} to be a complex expression, such as
  3080. another \code{let}. The flattening of nested \code{let} expressions is
  3081. instead one of the responsibilities of the \code{explicate\_control}
  3082. pass.
  3083. \fi}
  3084. {\if\edition\racketEd
  3085. We recommend implementing this pass with two mutually recursive
  3086. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3087. \code{rco\_atom} to subexpressions that need to become atomic and to
  3088. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3089. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3090. returns an expression. The \code{rco\_atom} function returns two
  3091. things: an atomic expression and an alist mapping temporary variables to
  3092. complex subexpressions. You can return multiple things from a function
  3093. using Racket's \key{values} form, and you can receive multiple things
  3094. from a function call using the \key{define-values} form.
  3095. \fi}
  3096. %
  3097. {\if\edition\pythonEd\pythonColor
  3098. %
  3099. We recommend implementing this pass with an auxiliary method named
  3100. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3101. Boolean that specifies whether the expression needs to become atomic
  3102. or not. The \code{rco\_exp} method should return a pair consisting of
  3103. the new expression and a list of pairs, associating new temporary
  3104. variables with their initializing expressions.
  3105. %
  3106. \fi}
  3107. {\if\edition\racketEd
  3108. %
  3109. In the example program with the expression \code{(+ 42 (-
  3110. 10))}, the subexpression \code{(- 10)} should be processed using the
  3111. \code{rco\_atom} function because it is an argument of the \code{+}
  3112. operator and therefore needs to become atomic. The output of
  3113. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3114. \begin{transformation}
  3115. \begin{lstlisting}
  3116. (- 10)
  3117. \end{lstlisting}
  3118. \compilesto
  3119. \begin{lstlisting}
  3120. tmp.1
  3121. ((tmp.1 . (- 10)))
  3122. \end{lstlisting}
  3123. \end{transformation}
  3124. \fi}
  3125. %
  3126. {\if\edition\pythonEd\pythonColor
  3127. %
  3128. Returning to the example program with the expression \code{42 + -10},
  3129. the subexpression \code{-10} should be processed using the
  3130. \code{rco\_exp} function with \code{True} as the second argument,
  3131. because \code{-10} is an argument of the \code{+} operator and
  3132. therefore needs to become atomic. The output of \code{rco\_exp}
  3133. applied to \code{-10} is as follows.
  3134. \begin{transformation}
  3135. \begin{lstlisting}
  3136. -10
  3137. \end{lstlisting}
  3138. \compilesto
  3139. \begin{lstlisting}
  3140. tmp_1
  3141. [(tmp_1, -10)]
  3142. \end{lstlisting}
  3143. \end{transformation}
  3144. %
  3145. \fi}
  3146. Take special care of programs, such as the following, that
  3147. %
  3148. \racket{bind a variable to an atomic expression.}
  3149. %
  3150. \python{assign an atomic expression to a variable.}
  3151. %
  3152. You should leave such \racket{variable bindings}\python{assignments}
  3153. unchanged, as shown in the program on the right:\\
  3154. %
  3155. {\if\edition\racketEd
  3156. \begin{transformation}
  3157. % var_test_20.rkt
  3158. \begin{lstlisting}
  3159. (let ([a 42])
  3160. (let ([b a])
  3161. b))
  3162. \end{lstlisting}
  3163. \compilesto
  3164. \begin{lstlisting}
  3165. (let ([a 42])
  3166. (let ([b a])
  3167. b))
  3168. \end{lstlisting}
  3169. \end{transformation}
  3170. \fi}
  3171. {\if\edition\pythonEd\pythonColor
  3172. \begin{transformation}
  3173. \begin{lstlisting}
  3174. a = 42
  3175. b = a
  3176. print(b)
  3177. \end{lstlisting}
  3178. \compilesto
  3179. \begin{lstlisting}
  3180. a = 42
  3181. b = a
  3182. print(b)
  3183. \end{lstlisting}
  3184. \end{transformation}
  3185. \fi}
  3186. %
  3187. \noindent A careless implementation might produce the following output with
  3188. unnecessary temporary variables.
  3189. \begin{center}
  3190. \begin{minipage}{0.4\textwidth}
  3191. {\if\edition\racketEd
  3192. \begin{lstlisting}
  3193. (let ([tmp.1 42])
  3194. (let ([a tmp.1])
  3195. (let ([tmp.2 a])
  3196. (let ([b tmp.2])
  3197. b))))
  3198. \end{lstlisting}
  3199. \fi}
  3200. {\if\edition\pythonEd\pythonColor
  3201. \begin{lstlisting}
  3202. tmp_1 = 42
  3203. a = tmp_1
  3204. tmp_2 = a
  3205. b = tmp_2
  3206. print(b)
  3207. \end{lstlisting}
  3208. \fi}
  3209. \end{minipage}
  3210. \end{center}
  3211. \begin{exercise}
  3212. \normalfont\normalsize
  3213. {\if\edition\racketEd
  3214. Implement the \code{remove\_complex\_operands} function in
  3215. \code{compiler.rkt}.
  3216. %
  3217. Create three new \LangVar{} programs that exercise the interesting
  3218. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3219. regarding file names described in exercise~\ref{ex:Lvar}.
  3220. %
  3221. In the \code{run-tests.rkt} script, add the following entry to the
  3222. list of \code{passes}, and then run the script to test your compiler.
  3223. \begin{lstlisting}
  3224. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3225. \end{lstlisting}
  3226. In debugging your compiler, it is often useful to see the intermediate
  3227. programs that are output from each pass. To print the intermediate
  3228. programs, place \lstinline{(debug-level 1)} before the call to
  3229. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3230. %
  3231. {\if\edition\pythonEd\pythonColor
  3232. Implement the \code{remove\_complex\_operands} pass in
  3233. \code{compiler.py}, creating auxiliary functions for each
  3234. nonterminal in the grammar, that is, \code{rco\_exp}
  3235. and \code{rco\_stmt}. We recommend that you use the function
  3236. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3237. \fi}
  3238. \end{exercise}
  3239. {\if\edition\pythonEd\pythonColor
  3240. \begin{exercise}
  3241. \normalfont\normalsize
  3242. \label{ex:Lvar}
  3243. Create five \LangVar{} programs that exercise the most interesting
  3244. parts of the \code{remove\_complex\_operands} pass. The five programs
  3245. should be placed in the subdirectory named \key{tests}, and the file
  3246. names should start with \code{var\_test\_} followed by a unique
  3247. integer and end with the file extension \key{.py}.
  3248. %% The \key{run-tests.rkt} script in the support code checks whether the
  3249. %% output programs produce the same result as the input programs. The
  3250. %% script uses the \key{interp-tests} function
  3251. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3252. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3253. %% parameter of \key{interp-tests} is a list that should have one entry
  3254. %% for each pass in your compiler. For now, define \code{passes} to
  3255. %% contain just one entry for \code{uniquify} as shown below.
  3256. %% \begin{lstlisting}
  3257. %% (define passes
  3258. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3259. %% \end{lstlisting}
  3260. Run the \key{run-tests.py} script in the support code to check
  3261. whether the output programs produce the same result as the input
  3262. programs.
  3263. \end{exercise}
  3264. \fi}
  3265. {\if\edition\racketEd
  3266. \section{Explicate Control}
  3267. \label{sec:explicate-control-Lvar}
  3268. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3269. programs that make the order of execution explicit in their
  3270. syntax. For now this amounts to flattening \key{let} constructs into a
  3271. sequence of assignment statements. For example, consider the following
  3272. \LangVar{} program:\\
  3273. % var_test_11.rkt
  3274. \begin{minipage}{0.96\textwidth}
  3275. \begin{lstlisting}
  3276. (let ([y (let ([x 20])
  3277. (+ x (let ([x 22]) x)))])
  3278. y)
  3279. \end{lstlisting}
  3280. \end{minipage}\\
  3281. %
  3282. The output of the previous pass is shown next, on the left, and the
  3283. output of \code{explicate\_control} is on the right. Recall that the
  3284. right-hand side of a \key{let} executes before its body, so that the order
  3285. of evaluation for this program is to assign \code{20} to \code{x.1},
  3286. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3287. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3288. this ordering explicit.
  3289. \begin{transformation}
  3290. \begin{lstlisting}
  3291. (let ([y (let ([x.1 20])
  3292. (let ([x.2 22])
  3293. (+ x.1 x.2)))])
  3294. y)
  3295. \end{lstlisting}
  3296. \compilesto
  3297. \begin{lstlisting}[language=C]
  3298. start:
  3299. x.1 = 20;
  3300. x.2 = 22;
  3301. y = (+ x.1 x.2);
  3302. return y;
  3303. \end{lstlisting}
  3304. \end{transformation}
  3305. \begin{figure}[tbp]
  3306. \begin{tcolorbox}[colback=white]
  3307. \begin{lstlisting}
  3308. (define (explicate_tail e)
  3309. (match e
  3310. [(Var x) ___]
  3311. [(Int n) (Return (Int n))]
  3312. [(Let x rhs body) ___]
  3313. [(Prim op es) ___]
  3314. [else (error "explicate_tail unhandled case" e)]))
  3315. (define (explicate_assign e x cont)
  3316. (match e
  3317. [(Var x) ___]
  3318. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3319. [(Let y rhs body) ___]
  3320. [(Prim op es) ___]
  3321. [else (error "explicate_assign unhandled case" e)]))
  3322. (define (explicate_control p)
  3323. (match p
  3324. [(Program info body) ___]))
  3325. \end{lstlisting}
  3326. \end{tcolorbox}
  3327. \caption{Skeleton for the \code{explicate\_control} pass.}
  3328. \label{fig:explicate-control-Lvar}
  3329. \end{figure}
  3330. The organization of this pass depends on the notion of tail position
  3331. to which we have alluded. Here is the definition.
  3332. \begin{definition}\normalfont
  3333. The following rules define when an expression is in \emph{tail
  3334. position}\index{subject}{tail position} for the language \LangVar{}.
  3335. \begin{enumerate}
  3336. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3337. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3338. \end{enumerate}
  3339. \end{definition}
  3340. We recommend implementing \code{explicate\_control} using two
  3341. recursive functions, \code{explicate\_tail} and
  3342. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3343. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3344. function should be applied to expressions in tail position, whereas the
  3345. \code{explicate\_assign} should be applied to expressions that occur on
  3346. the right-hand side of a \key{let}.
  3347. %
  3348. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3349. input and produces a \Tail{} in \LangCVar{} (see
  3350. figure~\ref{fig:c0-syntax}).
  3351. %
  3352. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3353. the variable to which it is to be assigned, and a \Tail{} in
  3354. \LangCVar{} for the code that comes after the assignment. The
  3355. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3356. The \code{explicate\_assign} function is in accumulator-passing style:
  3357. the \code{cont} parameter is used for accumulating the output. This
  3358. accumulator-passing style plays an important role in the way that we
  3359. generate high-quality code for conditional expressions in
  3360. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3361. continuation because it contains the generated code that should come
  3362. after the current assignment. This code organization is also related
  3363. to continuation-passing style, except that \code{cont} is not what
  3364. happens next during compilation but is what happens next in the
  3365. generated code.
  3366. \begin{exercise}\normalfont\normalsize
  3367. %
  3368. Implement the \code{explicate\_control} function in
  3369. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3370. exercise the code in \code{explicate\_control}.
  3371. %
  3372. In the \code{run-tests.rkt} script, add the following entry to the
  3373. list of \code{passes} and then run the script to test your compiler.
  3374. \begin{lstlisting}
  3375. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3376. \end{lstlisting}
  3377. \end{exercise}
  3378. \fi}
  3379. \section{Select Instructions}
  3380. \label{sec:select-Lvar}
  3381. \index{subject}{select instructions}
  3382. In the \code{select\_instructions} pass we begin the work of
  3383. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3384. language of this pass is a variant of x86 that still uses variables,
  3385. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3386. nonterminal of the \LangXInt{} abstract syntax
  3387. (figure~\ref{fig:x86-int-ast}).
  3388. \racket{We recommend implementing the
  3389. \code{select\_instructions} with three auxiliary functions, one for
  3390. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3391. $\Tail$.}
  3392. \python{We recommend implementing an auxiliary function
  3393. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3394. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3395. same and integer constants change to immediates; that is, $\INT{n}$
  3396. changes to $\IMM{n}$.}
  3397. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3398. arithmetic operations. For example, consider the following addition
  3399. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3400. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3401. \key{addq} instruction in x86, but it performs an in-place update.
  3402. %
  3403. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3404. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into the
  3405. left-hand \itm{var}.
  3406. \begin{transformation}
  3407. {\if\edition\racketEd
  3408. \begin{lstlisting}
  3409. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3410. \end{lstlisting}
  3411. \fi}
  3412. {\if\edition\pythonEd\pythonColor
  3413. \begin{lstlisting}
  3414. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3415. \end{lstlisting}
  3416. \fi}
  3417. \compilesto
  3418. \begin{lstlisting}
  3419. movq |$\Arg_1$|, %rax
  3420. addq |$\Arg_2$|, %rax
  3421. movq %rax, |$\itm{var}$|
  3422. \end{lstlisting}
  3423. \end{transformation}
  3424. %
  3425. However, with some care we can generate shorter sequences of
  3426. instructions. Suppose that one or more of the arguments of the
  3427. addition is the same variable as the left-hand side of the assignment.
  3428. Then the assignment statement can be translated into a single
  3429. \key{addq} instruction, as follows.
  3430. \begin{transformation}
  3431. {\if\edition\racketEd
  3432. \begin{lstlisting}
  3433. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3434. \end{lstlisting}
  3435. \fi}
  3436. {\if\edition\pythonEd\pythonColor
  3437. \begin{lstlisting}
  3438. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3439. \end{lstlisting}
  3440. \fi}
  3441. \compilesto
  3442. \begin{lstlisting}
  3443. addq |$\Arg_1$|, |$\itm{var}$|
  3444. \end{lstlisting}
  3445. \end{transformation}
  3446. %
  3447. On the other hand, if $\Atm_1$ is not the same variable as the
  3448. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3449. and then add $\Arg_2$ to \itm{var}.
  3450. %
  3451. \begin{transformation}
  3452. {\if\edition\racketEd
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3455. \end{lstlisting}
  3456. \fi}
  3457. {\if\edition\pythonEd\pythonColor
  3458. \begin{lstlisting}
  3459. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3460. \end{lstlisting}
  3461. \fi}
  3462. \compilesto
  3463. \begin{lstlisting}
  3464. movq |$\Arg_1$|, |$\itm{var}$|
  3465. addq |$\Arg_2$|, |$\itm{var}$|
  3466. \end{lstlisting}
  3467. \end{transformation}
  3468. The \READOP{} operation does not have a direct counterpart in x86
  3469. assembly, so we provide this functionality with the function
  3470. \code{read\_int} in the file \code{runtime.c}, written in
  3471. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3472. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3473. system}, or simply the \emph{runtime} for short. When compiling your
  3474. generated x86 assembly code, you need to compile \code{runtime.c} to
  3475. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3476. \code{-c}) and link it into the executable. For our purposes of code
  3477. generation, all you need to do is translate an assignment of
  3478. \READOP{} into a call to the \code{read\_int} function followed by a
  3479. move from \code{rax} to the left-hand side variable. (Recall that the
  3480. return value of a function goes into \code{rax}.)
  3481. \begin{transformation}
  3482. {\if\edition\racketEd
  3483. \begin{lstlisting}
  3484. |$\itm{var}$| = (read);
  3485. \end{lstlisting}
  3486. \fi}
  3487. {\if\edition\pythonEd\pythonColor
  3488. \begin{lstlisting}
  3489. |$\itm{var}$| = input_int();
  3490. \end{lstlisting}
  3491. \fi}
  3492. \compilesto
  3493. \begin{lstlisting}
  3494. callq read_int
  3495. movq %rax, |$\itm{var}$|
  3496. \end{lstlisting}
  3497. \end{transformation}
  3498. {\if\edition\pythonEd\pythonColor
  3499. %
  3500. Similarly, we translate the \code{print} operation, shown below, into
  3501. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3502. In x86, the first six arguments to functions are passed in registers,
  3503. with the first argument passed in register \code{rdi}. So we move the
  3504. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3505. \code{callq} instruction.
  3506. \begin{transformation}
  3507. \begin{lstlisting}
  3508. print(|$\Atm$|)
  3509. \end{lstlisting}
  3510. \compilesto
  3511. \begin{lstlisting}
  3512. movq |$\Arg$|, %rdi
  3513. callq print_int
  3514. \end{lstlisting}
  3515. \end{transformation}
  3516. %
  3517. \fi}
  3518. {\if\edition\racketEd
  3519. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3520. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3521. assignment to the \key{rax} register followed by a jump to the
  3522. conclusion of the program (so the conclusion needs to be labeled).
  3523. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3524. recursively and then append the resulting instructions.
  3525. \fi}
  3526. {\if\edition\pythonEd\pythonColor
  3527. We recommend that you use the function \code{utils.label\_name()} to
  3528. transform strings into labels, for example, in
  3529. the target of the \code{callq} instruction. This practice makes your
  3530. compiler portable across Linux and Mac OS X, which requires an underscore
  3531. prefixed to all labels.
  3532. \fi}
  3533. \begin{exercise}
  3534. \normalfont\normalsize
  3535. {\if\edition\racketEd
  3536. Implement the \code{select\_instructions} pass in
  3537. \code{compiler.rkt}. Create three new example programs that are
  3538. designed to exercise all the interesting cases in this pass.
  3539. %
  3540. In the \code{run-tests.rkt} script, add the following entry to the
  3541. list of \code{passes} and then run the script to test your compiler.
  3542. \begin{lstlisting}
  3543. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3544. \end{lstlisting}
  3545. \fi}
  3546. {\if\edition\pythonEd\pythonColor
  3547. Implement the \key{select\_instructions} pass in
  3548. \code{compiler.py}. Create three new example programs that are
  3549. designed to exercise all the interesting cases in this pass.
  3550. Run the \code{run-tests.py} script to check
  3551. whether the output programs produce the same result as the input
  3552. programs.
  3553. \fi}
  3554. \end{exercise}
  3555. \section{Assign Homes}
  3556. \label{sec:assign-Lvar}
  3557. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3558. \LangXVar{} programs that no longer use program variables. Thus, the
  3559. \code{assign\_homes} pass is responsible for placing all the program
  3560. variables in registers or on the stack. For runtime efficiency, it is
  3561. better to place variables in registers, but because there are only
  3562. sixteen registers, some programs must necessarily resort to placing
  3563. some variables on the stack. In this chapter we focus on the mechanics
  3564. of placing variables on the stack. We study an algorithm for placing
  3565. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3566. Consider again the following \LangVar{} program from
  3567. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3568. % var_test_20.rkt
  3569. \begin{minipage}{0.96\textwidth}
  3570. {\if\edition\racketEd
  3571. \begin{lstlisting}
  3572. (let ([a 42])
  3573. (let ([b a])
  3574. b))
  3575. \end{lstlisting}
  3576. \fi}
  3577. {\if\edition\pythonEd\pythonColor
  3578. \begin{lstlisting}
  3579. a = 42
  3580. b = a
  3581. print(b)
  3582. \end{lstlisting}
  3583. \fi}
  3584. \end{minipage}\\
  3585. %
  3586. The output of \code{select\_instructions} is shown next, on the left,
  3587. and the output of \code{assign\_homes} is on the right. In this
  3588. example, we assign variable \code{a} to stack location
  3589. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3590. \begin{transformation}
  3591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3592. movq $42, a
  3593. movq a, b
  3594. movq b, %rax
  3595. \end{lstlisting}
  3596. \compilesto
  3597. %stack-space: 16
  3598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3599. movq $42, -8(%rbp)
  3600. movq -8(%rbp), -16(%rbp)
  3601. movq -16(%rbp), %rax
  3602. \end{lstlisting}
  3603. \end{transformation}
  3604. \racket{
  3605. The \code{assign\_homes} pass should replace all variables
  3606. with stack locations.
  3607. The list of variables can be obtained from
  3608. the \code{locals-types} entry in the $\itm{info}$ of the
  3609. \code{X86Program} node. The \code{locals-types} entry is an alist
  3610. mapping all the variables in the program to their types
  3611. (for now, just \code{Integer}).
  3612. As an aside, the \code{locals-types} entry is
  3613. computed by \code{type-check-Cvar} in the support code, which
  3614. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3615. which you should propagate to the \code{X86Program} node.}
  3616. %
  3617. \python{The \code{assign\_homes} pass should replace all uses of
  3618. variables with stack locations.}
  3619. %
  3620. In the process of assigning variables to stack locations, it is
  3621. convenient for you to compute and store the size of the frame (in
  3622. bytes) in
  3623. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3624. %
  3625. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3626. %
  3627. which is needed later to generate the conclusion of the \code{main}
  3628. procedure. The x86-64 standard requires the frame size to be a
  3629. multiple of 16 bytes.\index{subject}{frame}
  3630. % TODO: store the number of variables instead? -Jeremy
  3631. \begin{exercise}\normalfont\normalsize
  3632. Implement the \code{assign\_homes} pass in
  3633. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3634. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3635. grammar. We recommend that the auxiliary functions take an extra
  3636. parameter that maps variable names to homes (stack locations for now).
  3637. %
  3638. {\if\edition\racketEd
  3639. In the \code{run-tests.rkt} script, add the following entry to the
  3640. list of \code{passes} and then run the script to test your compiler.
  3641. \begin{lstlisting}
  3642. (list "assign homes" assign-homes interp_x86-0)
  3643. \end{lstlisting}
  3644. \fi}
  3645. {\if\edition\pythonEd\pythonColor
  3646. Run the \code{run-tests.py} script to check
  3647. whether the output programs produce the same result as the input
  3648. programs.
  3649. \fi}
  3650. \end{exercise}
  3651. \section{Patch Instructions}
  3652. \label{sec:patch-s0}
  3653. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3654. \LangXInt{} by making sure that each instruction adheres to the
  3655. restriction that at most one argument of an instruction may be a
  3656. memory reference.
  3657. We return to the following example.\\
  3658. \begin{minipage}{0.5\textwidth}
  3659. % var_test_20.rkt
  3660. {\if\edition\racketEd
  3661. \begin{lstlisting}
  3662. (let ([a 42])
  3663. (let ([b a])
  3664. b))
  3665. \end{lstlisting}
  3666. \fi}
  3667. {\if\edition\pythonEd\pythonColor
  3668. \begin{lstlisting}
  3669. a = 42
  3670. b = a
  3671. print(b)
  3672. \end{lstlisting}
  3673. \fi}
  3674. \end{minipage}\\
  3675. The \code{assign\_homes} pass produces the following translation. \\
  3676. \begin{minipage}{0.5\textwidth}
  3677. {\if\edition\racketEd
  3678. \begin{lstlisting}
  3679. movq $42, -8(%rbp)
  3680. movq -8(%rbp), -16(%rbp)
  3681. movq -16(%rbp), %rax
  3682. \end{lstlisting}
  3683. \fi}
  3684. {\if\edition\pythonEd\pythonColor
  3685. \begin{lstlisting}
  3686. movq $42, -8(%rbp)
  3687. movq -8(%rbp), -16(%rbp)
  3688. movq -16(%rbp), %rdi
  3689. callq print_int
  3690. \end{lstlisting}
  3691. \fi}
  3692. \end{minipage}\\
  3693. The second \key{movq} instruction is problematic because both
  3694. arguments are stack locations. We suggest fixing this problem by
  3695. moving from the source location to the register \key{rax} and then
  3696. from \key{rax} to the destination location, as follows.
  3697. \begin{lstlisting}
  3698. movq -8(%rbp), %rax
  3699. movq %rax, -16(%rbp)
  3700. \end{lstlisting}
  3701. There is a similar corner case that also needs to be dealt with. If
  3702. one argument is an immediate integer larger than $2^{16}$ and the
  3703. other is a memory reference, then the instruction is invalid. One can
  3704. fix this, for example, by first moving the immediate integer into
  3705. \key{rax} and then using \key{rax} in place of the integer.
  3706. \begin{exercise}
  3707. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3708. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3709. Create three new example programs that are
  3710. designed to exercise all the interesting cases in this pass.
  3711. %
  3712. {\if\edition\racketEd
  3713. In the \code{run-tests.rkt} script, add the following entry to the
  3714. list of \code{passes} and then run the script to test your compiler.
  3715. \begin{lstlisting}
  3716. (list "patch instructions" patch_instructions interp_x86-0)
  3717. \end{lstlisting}
  3718. \fi}
  3719. {\if\edition\pythonEd\pythonColor
  3720. Run the \code{run-tests.py} script to check
  3721. whether the output programs produce the same result as the input
  3722. programs.
  3723. \fi}
  3724. \end{exercise}
  3725. \section{Generate Prelude and Conclusion}
  3726. \label{sec:print-x86}
  3727. \index{subject}{prelude}\index{subject}{conclusion}
  3728. The last step of the compiler from \LangVar{} to x86 is to generate
  3729. the \code{main} function with a prelude and conclusion wrapped around
  3730. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3731. discussed in section~\ref{sec:x86}.
  3732. When running on Mac OS X, your compiler should prefix an underscore to
  3733. all labels (for example, changing \key{main} to \key{\_main}).
  3734. %
  3735. \racket{The Racket call \code{(system-type 'os)} is useful for
  3736. determining which operating system the compiler is running on. It
  3737. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3738. %
  3739. \python{The Python \code{platform} library includes a \code{system()}
  3740. function that returns \code{\textquotesingle Linux\textquotesingle},
  3741. \code{\textquotesingle Windows\textquotesingle}, or
  3742. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3743. \begin{exercise}\normalfont\normalsize
  3744. %
  3745. Implement the \key{prelude\_and\_conclusion} pass in
  3746. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3747. %
  3748. {\if\edition\racketEd
  3749. In the \code{run-tests.rkt} script, add the following entry to the
  3750. list of \code{passes} and then run the script to test your compiler.
  3751. \begin{lstlisting}
  3752. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3753. \end{lstlisting}
  3754. %
  3755. Uncomment the call to the \key{compiler-tests} function
  3756. (appendix~\ref{appendix:utilities}), which tests your complete
  3757. compiler by executing the generated x86 code. It translates the x86
  3758. AST that you produce into a string by invoking the \code{print-x86}
  3759. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3760. the provided \key{runtime.c} file to \key{runtime.o} using
  3761. \key{gcc}. Run the script to test your compiler.
  3762. %
  3763. \fi}
  3764. {\if\edition\pythonEd\pythonColor
  3765. %
  3766. Run the \code{run-tests.py} script to check whether the output
  3767. programs produce the same result as the input programs. That script
  3768. translates the x86 AST that you produce into a string by invoking the
  3769. \code{repr} method that is implemented by the x86 AST classes in
  3770. \code{x86\_ast.py}.
  3771. %
  3772. \fi}
  3773. \end{exercise}
  3774. \section{Challenge: Partial Evaluator for \LangVar{}}
  3775. \label{sec:pe-Lvar}
  3776. \index{subject}{partialevaluation@partial evaluation}
  3777. This section describes two optional challenge exercises that involve
  3778. adapting and improving the partial evaluator for \LangInt{} that was
  3779. introduced in section~\ref{sec:partial-evaluation}.
  3780. \begin{exercise}\label{ex:pe-Lvar}
  3781. \normalfont\normalsize
  3782. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3783. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3784. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3785. %
  3786. \racket{\key{let} binding}\python{assignment}
  3787. %
  3788. to the \LangInt{} language, so you will need to add cases for them in
  3789. the \code{pe\_exp}
  3790. %
  3791. \racket{function.}
  3792. %
  3793. \python{and \code{pe\_stmt} functions.}
  3794. %
  3795. Once complete, add the partial evaluation pass to the front of your
  3796. compiler, and make sure that your compiler still passes all the
  3797. tests.
  3798. \end{exercise}
  3799. \begin{exercise}
  3800. \normalfont\normalsize
  3801. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3802. \code{pe\_add} auxiliary functions with functions that know more about
  3803. arithmetic. For example, your partial evaluator should translate
  3804. {\if\edition\racketEd
  3805. \[
  3806. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3807. \code{(+ 2 (read))}
  3808. \]
  3809. \fi}
  3810. {\if\edition\pythonEd\pythonColor
  3811. \[
  3812. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3813. \code{2 + input\_int()}
  3814. \]
  3815. \fi}
  3816. %
  3817. To accomplish this, the \code{pe\_exp} function should produce output
  3818. in the form of the $\itm{residual}$ nonterminal of the following
  3819. grammar. The idea is that when processing an addition expression, we
  3820. can always produce one of the following: (1) an integer constant, (2)
  3821. an addition expression with an integer constant on the left-hand side
  3822. but not the right-hand side, or (3) an addition expression in which
  3823. neither subexpression is a constant.
  3824. %
  3825. {\if\edition\racketEd
  3826. \[
  3827. \begin{array}{lcl}
  3828. \itm{inert} &::=& \Var
  3829. \MID \LP\key{read}\RP
  3830. \MID \LP\key{-} ~\Var\RP
  3831. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3832. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3833. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3834. \itm{residual} &::=& \Int
  3835. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3836. \MID \itm{inert}
  3837. \end{array}
  3838. \]
  3839. \fi}
  3840. {\if\edition\pythonEd\pythonColor
  3841. \[
  3842. \begin{array}{lcl}
  3843. \itm{inert} &::=& \Var
  3844. \MID \key{input\_int}\LP\RP
  3845. \MID \key{-} \Var
  3846. \MID \key{-} \key{input\_int}\LP\RP
  3847. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3848. \itm{residual} &::=& \Int
  3849. \MID \Int ~ \key{+} ~ \itm{inert}
  3850. \MID \itm{inert}
  3851. \end{array}
  3852. \]
  3853. \fi}
  3854. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3855. inputs are $\itm{residual}$ expressions and they should return
  3856. $\itm{residual}$ expressions. Once the improvements are complete,
  3857. make sure that your compiler still passes all the tests. After
  3858. all, fast code is useless if it produces incorrect results!
  3859. \end{exercise}
  3860. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3861. {\if\edition\pythonEd\pythonColor
  3862. \chapter{Parsing}
  3863. \label{ch:parsing}
  3864. \setcounter{footnote}{0}
  3865. \index{subject}{parsing}
  3866. In this chapter we learn how to use the Lark parser
  3867. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3868. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3869. You will then be asked to use Lark to create a parser for \LangVar{}.
  3870. We also describe the parsing algorithms used inside Lark, studying the
  3871. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3872. A parser framework such as Lark takes in a specification of the
  3873. concrete syntax and an input program and produces a parse tree. Even
  3874. though a parser framework does most of the work for us, using one
  3875. properly requires some knowledge. In particular, we must learn about
  3876. its specification languages and we must learn how to deal with
  3877. ambiguity in our language specifications. Also, some algorithms, such
  3878. as LALR(1), place restrictions on the grammars they can handle, in
  3879. which case knowing the algorithm help with trying to decipher the
  3880. error messages.
  3881. The process of parsing is traditionally subdivided into two phases:
  3882. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3883. analysis} (also called parsing). The lexical analysis phase
  3884. translates the sequence of characters into a sequence of
  3885. \emph{tokens}, that is, words consisting of several characters. The
  3886. parsing phase organizes the tokens into a \emph{parse tree} that
  3887. captures how the tokens were matched by rules in the grammar of the
  3888. language. The reason for the subdivision into two phases is to enable
  3889. the use of a faster but less powerful algorithm for lexical analysis
  3890. and the use of a slower but more powerful algorithm for parsing.
  3891. %
  3892. %% Likewise, parser generators typical come in pairs, with separate
  3893. %% generators for the lexical analyzer (or lexer for short) and for the
  3894. %% parser. A particularly influential pair of generators were
  3895. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3896. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3897. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3898. %% Compiler Compiler.
  3899. %
  3900. The Lark parser framework that we use in this chapter includes both
  3901. lexical analyzers and parsers. The next section discusses lexical
  3902. analysis, and the remainder of the chapter discusses parsing.
  3903. \section{Lexical Analysis and Regular Expressions}
  3904. \label{sec:lex}
  3905. The lexical analyzers produced by Lark turn a sequence of characters
  3906. (a string) into a sequence of token objects. For example, a Lark
  3907. generated lexer for \LangInt{} converts the string
  3908. \begin{lstlisting}
  3909. 'print(1 + 3)'
  3910. \end{lstlisting}
  3911. \noindent into the following sequence of token objects:
  3912. \begin{center}
  3913. \begin{minipage}{0.95\textwidth}
  3914. \begin{lstlisting}
  3915. Token('PRINT', 'print')
  3916. Token('LPAR', '(')
  3917. Token('INT', '1')
  3918. Token('PLUS', '+')
  3919. Token('INT', '3')
  3920. Token('RPAR', ')')
  3921. Token('NEWLINE', '\n')
  3922. \end{lstlisting}
  3923. \end{minipage}
  3924. \end{center}
  3925. Each token includes a field for its \code{type}, such as \skey{INT},
  3926. and a field for its \code{value}, such as \skey{1}.
  3927. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3928. specification language for Lark's lexer is one regular expression for
  3929. each type of token. The term \emph{regular} comes from the term
  3930. \emph{regular languages}, which are the languages that can be
  3931. recognized by a finite state machine. A \emph{regular expression} is a
  3932. pattern formed of the following core elements:\index{subject}{regular
  3933. expression}\footnote{Regular expressions traditionally include the
  3934. empty regular expression that matches any zero-length part of a
  3935. string, but Lark does not support the empty regular expression.}
  3936. \begin{itemize}
  3937. \item A single character $c$ is a regular expression, and it matches
  3938. only itself. For example, the regular expression \code{a} matches
  3939. only the string \skey{a}.
  3940. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3941. R_2$ form a regular expression that matches any string that matches
  3942. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3943. matches the string \skey{a} and the string \skey{c}.
  3944. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3945. expression that matches any string that can be formed by
  3946. concatenating two strings, where the first string matches $R_1$ and
  3947. the second string matches $R_2$. For example, the regular expression
  3948. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3949. (Parentheses can be used to control the grouping of operators within
  3950. a regular expression.)
  3951. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3952. Kleene closure) is a regular expression that matches any string that
  3953. can be formed by concatenating zero or more strings that each match
  3954. the regular expression $R$. For example, the regular expression
  3955. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3956. \skey{abc}.
  3957. \end{itemize}
  3958. For our convenience, Lark also accepts the following extended set of
  3959. regular expressions that are automatically translated into the core
  3960. regular expressions.
  3961. \begin{itemize}
  3962. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3963. c_n]$ is a regular expression that matches any one of the
  3964. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3965. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3966. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3967. a regular expression that matches any character between $c_1$ and
  3968. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3969. letter in the alphabet.
  3970. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3971. is a regular expression that matches any string that can
  3972. be formed by concatenating one or more strings that each match $R$.
  3973. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3974. matches \skey{b} and \skey{bzca}.
  3975. \item A regular expression followed by a question mark $R\ttm{?}$
  3976. is a regular expression that matches any string that either
  3977. matches $R$ or is the empty string.
  3978. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3979. \end{itemize}
  3980. In a Lark grammar file, each kind of token is specified by a
  3981. \emph{terminal}\index{subject}{terminal} which is defined by a rule
  3982. that consists of the name of the terminal followed by a colon followed
  3983. by a sequence of literals. The literals include strings such as
  3984. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  3985. terminal names, and literals composed using the regular expression
  3986. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  3987. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  3988. \begin{center}
  3989. \begin{minipage}{0.95\textwidth}
  3990. \begin{lstlisting}
  3991. DIGIT: /[0-9]/
  3992. INT: "-"? DIGIT+
  3993. NEWLINE: (/\r/? /\n/)+
  3994. \end{lstlisting}
  3995. \end{minipage}
  3996. \end{center}
  3997. \section{Grammars and Parse Trees}
  3998. \label{sec:CFG}
  3999. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4000. specify the abstract syntax of a language. We now take a closer look
  4001. at using grammar rules to specify the concrete syntax. Recall that
  4002. each rule has a left-hand side and a right-hand side where the
  4003. left-hand side is a nonterminal and the right-hand side is a pattern
  4004. that defines what can be parsed as that nonterminal. For concrete
  4005. syntax, each right-hand side expresses a pattern for a string, instead
  4006. of a pattern for an abstract syntax tree. In particular, each
  4007. right-hand side is a sequence of
  4008. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4009. terminal or a nonterminal. The nonterminals play the same role as in
  4010. the abstract syntax, defining categories of syntax. The nonterminals
  4011. of a grammar include the tokens defined in the lexer and all the
  4012. nonterminals defined by the grammar rules.
  4013. As an example, let us take a closer look at the concrete syntax of the
  4014. \LangInt{} language, repeated here.
  4015. \[
  4016. \begin{array}{l}
  4017. \LintGrammarPython \\
  4018. \begin{array}{rcl}
  4019. \LangInt{} &::=& \Stmt^{*}
  4020. \end{array}
  4021. \end{array}
  4022. \]
  4023. The Lark syntax for grammar rules differs slightly from the variant of
  4024. BNF that we use in this book. In particular, the notation $::=$ is
  4025. replaced by a single colon, and the use of typewriter font for string
  4026. literals is replaced by quotation marks. The following grammar serves
  4027. as a first draft of a Lark grammar for \LangInt{}.
  4028. \begin{center}
  4029. \begin{minipage}{0.95\textwidth}
  4030. \begin{lstlisting}[escapechar=$]
  4031. exp: INT
  4032. | "input_int" "(" ")"
  4033. | "-" exp
  4034. | exp "+" exp
  4035. | exp "-" exp
  4036. | "(" exp ")"
  4037. stmt_list:
  4038. | stmt NEWLINE stmt_list
  4039. lang_int: stmt_list
  4040. \end{lstlisting}
  4041. \end{minipage}
  4042. \end{center}
  4043. Let us begin by discussing the rule \code{exp: INT}, which says that
  4044. if the lexer matches a string to \code{INT}, then the parser also
  4045. categorizes the string as an \code{exp}. Recall that in
  4046. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4047. nonterminal with a sentence in English. Here we specify \code{INT}
  4048. more formally using a type of token \code{INT} and its regular
  4049. expression \code{"-"? DIGIT+}.
  4050. The rule \code{exp: exp "+" exp} says that any string that matches
  4051. \code{exp}, followed by the \code{+} character, followed by another
  4052. string that matches \code{exp}, is itself an \code{exp}. For example,
  4053. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4054. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4055. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4056. \code{exp}. We can visualize the application of grammar rules to parse
  4057. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4058. internal node in the tree is an application of a grammar rule and is
  4059. labeled with its left-hand side nonterminal. Each leaf node is a
  4060. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4061. shown in figure~\ref{fig:simple-parse-tree}.
  4062. \begin{figure}[tbp]
  4063. \begin{tcolorbox}[colback=white]
  4064. \centering
  4065. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4066. \end{tcolorbox}
  4067. \caption{The parse tree for \lstinline{'1+3'}.}
  4068. \label{fig:simple-parse-tree}
  4069. \end{figure}
  4070. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4071. following parse tree as represented by \code{Tree} and \code{Token}
  4072. objects.
  4073. \begin{lstlisting}
  4074. Tree('lang_int',
  4075. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4076. Tree('exp', [Token('INT', '3')])])]),
  4077. Token('NEWLINE', '\n')])
  4078. \end{lstlisting}
  4079. The nodes that come from the lexer are \code{Token} objects, whereas
  4080. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4081. object has a \code{data} field containing the name of the nonterminal
  4082. for the grammar rule that was applied. Each \code{Tree} object also
  4083. has a \code{children} field that is a list containing trees and/or
  4084. tokens. Note that Lark does not produce nodes for string literals in
  4085. the grammar. For example, the \code{Tree} node for the addition
  4086. expression has only two children for the two integers but is missing
  4087. its middle child for the \code{"+"} terminal. This would be
  4088. problematic except that Lark provides a mechanism for customizing the
  4089. \code{data} field of each \code{Tree} node on the basis of which rule was
  4090. applied. Next to each alternative in a grammar rule, write \code{->}
  4091. followed by a string that you want to appear in the \code{data}
  4092. field. The following is a second draft of a Lark grammar for
  4093. \LangInt{}, this time with more specific labels on the \code{Tree}
  4094. nodes.
  4095. \begin{center}
  4096. \begin{minipage}{0.95\textwidth}
  4097. \begin{lstlisting}[escapechar=$]
  4098. exp: INT -> int
  4099. | "input_int" "(" ")" -> input_int
  4100. | "-" exp -> usub
  4101. | exp "+" exp -> add
  4102. | exp "-" exp -> sub
  4103. | "(" exp ")" -> paren
  4104. stmt: "print" "(" exp ")" -> print
  4105. | exp -> expr
  4106. stmt_list: -> empty_stmt
  4107. | stmt NEWLINE stmt_list -> add_stmt
  4108. lang_int: stmt_list -> module
  4109. \end{lstlisting}
  4110. \end{minipage}
  4111. \end{center}
  4112. Here is the resulting parse tree.
  4113. \begin{lstlisting}
  4114. Tree('module',
  4115. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4116. Tree('int', [Token('INT', '3')])])]),
  4117. Token('NEWLINE', '\n')])
  4118. \end{lstlisting}
  4119. \section{Ambiguous Grammars}
  4120. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4121. can be parsed in more than one way. For example, consider the string
  4122. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4123. our draft grammar, resulting in the two parse trees shown in
  4124. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4125. interpreting the second parse tree would yield \code{-4} even through
  4126. the correct answer is \code{2}.
  4127. \begin{figure}[tbp]
  4128. \begin{tcolorbox}[colback=white]
  4129. \centering
  4130. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4131. \end{tcolorbox}
  4132. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4133. \label{fig:ambig-parse-tree}
  4134. \end{figure}
  4135. To deal with this problem we can change the grammar by categorizing
  4136. the syntax in a more fine-grained fashion. In this case we want to
  4137. disallow the application of the rule \code{exp: exp "-" exp} when the
  4138. child on the right is an addition. To do this we can replace the
  4139. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4140. the expressions except for addition, as in the following.
  4141. \begin{center}
  4142. \begin{minipage}{0.95\textwidth}
  4143. \begin{lstlisting}[escapechar=$]
  4144. exp: exp "-" exp_no_add -> sub
  4145. | exp "+" exp -> add
  4146. | exp_no_add
  4147. exp_no_add: INT -> int
  4148. | "input_int" "(" ")" -> input_int
  4149. | "-" exp -> usub
  4150. | exp "-" exp_no_add -> sub
  4151. | "(" exp ")" -> paren
  4152. \end{lstlisting}
  4153. \end{minipage}
  4154. \end{center}
  4155. However, there remains some ambiguity in the grammar. For example, the
  4156. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4157. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4158. (incorrect). That is, subtraction is left associative. Likewise,
  4159. addition in Python is left associative. We also need to consider the
  4160. interaction of unary subtraction with both addition and
  4161. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4162. has higher \emph{precedence}\index{subject}{precedence} than addition
  4163. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4164. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4165. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4166. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4167. all the other expressions, and it uses \code{exp\_hi} for the second
  4168. child in the rules for addition and subtraction. Furthermore, unary
  4169. subtraction uses \code{exp\_hi} for its child.
  4170. For languages with more operators and more precedence levels, one must
  4171. refine the \code{exp} nonterminal into several nonterminals, one for
  4172. each precedence level.
  4173. \begin{figure}[tbp]
  4174. \begin{tcolorbox}[colback=white]
  4175. \centering
  4176. \begin{lstlisting}[escapechar=$]
  4177. exp: exp "+" exp_hi -> add
  4178. | exp "-" exp_hi -> sub
  4179. | exp_hi
  4180. exp_hi: INT -> int
  4181. | "input_int" "(" ")" -> input_int
  4182. | "-" exp_hi -> usub
  4183. | "(" exp ")" -> paren
  4184. stmt: "print" "(" exp ")" -> print
  4185. | exp -> expr
  4186. stmt_list: -> empty_stmt
  4187. | stmt NEWLINE stmt_list -> add_stmt
  4188. lang_int: stmt_list -> module
  4189. \end{lstlisting}
  4190. \end{tcolorbox}
  4191. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4192. \label{fig:Lint-lark-grammar}
  4193. \end{figure}
  4194. \section{From Parse Trees to Abstract Syntax Trees}
  4195. As we have seen, the output of a Lark parser is a parse tree, that is,
  4196. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4197. step is to convert the parse tree to an abstract syntax tree. This can
  4198. be accomplished with a recursive function that inspects the
  4199. \code{data} field of each node and then constructs the corresponding
  4200. AST node, using recursion to handle its children. The following is an
  4201. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4202. \begin{center}
  4203. \begin{minipage}{0.95\textwidth}
  4204. \begin{lstlisting}
  4205. def parse_tree_to_ast(e):
  4206. if e.data == 'int':
  4207. return Constant(int(e.children[0].value))
  4208. elif e.data == 'input_int':
  4209. return Call(Name('input_int'), [])
  4210. elif e.data == 'add':
  4211. e1, e2 = e.children
  4212. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4213. ...
  4214. else:
  4215. raise Exception('unhandled parse tree', e)
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. \end{center}
  4219. \begin{exercise}
  4220. \normalfont\normalsize
  4221. %
  4222. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4223. default parsing algorithm (Earley) with the \code{ambiguity} option
  4224. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4225. output will include multiple parse trees that will indicate to you
  4226. that there is a problem with your grammar. Your parser should ignore
  4227. white space, so we recommend using Lark's \code{\%ignore} directive
  4228. as follows.
  4229. \begin{lstlisting}
  4230. WS: /[ \t\f\r\n]/+
  4231. %ignore WS
  4232. \end{lstlisting}
  4233. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4234. Lark parser instead of using the \code{parse} function from
  4235. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4236. programs that you have created, and create four additional programs
  4237. that test for ambiguities in your grammar.
  4238. \end{exercise}
  4239. \section{Earley's Algorithm}
  4240. \label{sec:earley}
  4241. In this section we discuss the parsing algorithm of
  4242. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4243. algorithm is powerful in that it can handle any context-free grammar,
  4244. which makes it easy to use. However, it is not a particularly
  4245. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4246. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4247. the number of tokens in the input
  4248. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4249. learn about the LALR(1) algorithm, which is more efficient but cannot
  4250. handle all context-free grammars.
  4251. Earley's algorithm can be viewed as an interpreter; it treats the
  4252. grammar as the program being interpreted and it treats the concrete
  4253. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4254. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4255. keep track of its progress and to store its results. The chart is an
  4256. array with one slot for each position in the input string, where
  4257. position $0$ is before the first character and position $n$ is
  4258. immediately after the last character. So, the array has length $n+1$
  4259. for an input string of length $n$. Each slot in the chart contains a
  4260. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4261. with a period indicating how much of its right-hand side has already
  4262. been parsed. For example, the dotted rule
  4263. \begin{lstlisting}
  4264. exp: exp "+" . exp_hi
  4265. \end{lstlisting}
  4266. represents a partial parse that has matched an \code{exp} followed by
  4267. \code{+}, but has not yet parsed an \code{exp} to the right of
  4268. \code{+}.
  4269. %
  4270. Earley's algorithm starts with an initialization phase, and then
  4271. repeats three actions---prediction, scanning, and completion---for as
  4272. long as opportunities arise. We demonstrate Earley's algorithm on a
  4273. running example, parsing the following program:
  4274. \begin{lstlisting}
  4275. print(1 + 3)
  4276. \end{lstlisting}
  4277. The algorithm's initialization phase creates dotted rules for all the
  4278. grammar rules whose left-hand side is the start symbol and places them
  4279. in slot $0$ of the chart. We also record the starting position of the
  4280. dotted rule in parentheses on the right. For example, given the
  4281. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4282. \begin{lstlisting}
  4283. lang_int: . stmt_list (0)
  4284. \end{lstlisting}
  4285. in slot $0$ of the chart. The algorithm then proceeds with
  4286. \emph{prediction} actions in which it adds more dotted rules to the
  4287. chart based on the nonterminals that come immediately after a period. In
  4288. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4289. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4290. period at the beginning of their right-hand sides, as follows:
  4291. \begin{lstlisting}
  4292. stmt_list: . (0)
  4293. stmt_list: . stmt NEWLINE stmt_list (0)
  4294. \end{lstlisting}
  4295. We continue to perform prediction actions as more opportunities
  4296. arise. For example, the \code{stmt} nonterminal now appears after a
  4297. period, so we add all the rules for \code{stmt}.
  4298. \begin{lstlisting}
  4299. stmt: . "print" "(" exp ")" (0)
  4300. stmt: . exp (0)
  4301. \end{lstlisting}
  4302. This reveals yet more opportunities for prediction, so we add the grammar
  4303. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4304. \begin{lstlisting}[escapechar=$]
  4305. exp: . exp "+" exp_hi (0)
  4306. exp: . exp "-" exp_hi (0)
  4307. exp: . exp_hi (0)
  4308. exp_hi: . INT (0)
  4309. exp_hi: . "input_int" "(" ")" (0)
  4310. exp_hi: . "-" exp_hi (0)
  4311. exp_hi: . "(" exp ")" (0)
  4312. \end{lstlisting}
  4313. We have exhausted the opportunities for prediction, so the algorithm
  4314. proceeds to \emph{scanning}, in which we inspect the next input token
  4315. and look for a dotted rule at the current position that has a matching
  4316. terminal immediately following the period. In our running example, the
  4317. first input token is \code{"print"}, so we identify the rule in slot
  4318. $0$ of the chart where \code{"print"} follows the period:
  4319. \begin{lstlisting}
  4320. stmt: . "print" "(" exp ")" (0)
  4321. \end{lstlisting}
  4322. We advance the period past \code{"print"} and add the resulting rule
  4323. to slot $1$ of the chart:
  4324. \begin{lstlisting}
  4325. stmt: "print" . "(" exp ")" (0)
  4326. \end{lstlisting}
  4327. If the new dotted rule had a nonterminal after the period, we would
  4328. need to carry out a prediction action, adding more dotted rules to
  4329. slot $1$. That is not the case, so we continue scanning. The next
  4330. input token is \code{"("}, so we add the following to slot $2$ of the
  4331. chart.
  4332. \begin{lstlisting}
  4333. stmt: "print" "(" . exp ")" (0)
  4334. \end{lstlisting}
  4335. Now we have a nonterminal after the period, so we carry out several
  4336. prediction actions, adding dotted rules for \code{exp} and
  4337. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4338. starting position $2$.
  4339. \begin{lstlisting}[escapechar=$]
  4340. exp: . exp "+" exp_hi (2)
  4341. exp: . exp "-" exp_hi (2)
  4342. exp: . exp_hi (2)
  4343. exp_hi: . INT (2)
  4344. exp_hi: . "input_int" "(" ")" (2)
  4345. exp_hi: . "-" exp_hi (2)
  4346. exp_hi: . "(" exp ")" (2)
  4347. \end{lstlisting}
  4348. With this prediction complete, we return to scanning, noting that the
  4349. next input token is \code{"1"}, which the lexer parses as an
  4350. \code{INT}. There is a matching rule in slot $2$:
  4351. \begin{lstlisting}
  4352. exp_hi: . INT (2)
  4353. \end{lstlisting}
  4354. so we advance the period and put the following rule into slot $3$.
  4355. \begin{lstlisting}
  4356. exp_hi: INT . (2)
  4357. \end{lstlisting}
  4358. This brings us to \emph{completion} actions. When the period reaches
  4359. the end of a dotted rule, we recognize that the substring
  4360. has matched the nonterminal on the left-hand side of the rule, in this case
  4361. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4362. rules into slot $2$ (the starting position for the finished rule) if
  4363. the period is immediately followed by \code{exp\_hi}. So we identify
  4364. \begin{lstlisting}
  4365. exp: . exp_hi (2)
  4366. \end{lstlisting}
  4367. and add the following dotted rule to slot $3$
  4368. \begin{lstlisting}
  4369. exp: exp_hi . (2)
  4370. \end{lstlisting}
  4371. This triggers another completion step for the nonterminal \code{exp},
  4372. adding two more dotted rules to slot $3$.
  4373. \begin{lstlisting}[escapechar=$]
  4374. exp: exp . "+" exp_hi (2)
  4375. exp: exp . "-" exp_hi (2)
  4376. \end{lstlisting}
  4377. Returning to scanning, the next input token is \code{"+"}, so
  4378. we add the following to slot $4$.
  4379. \begin{lstlisting}[escapechar=$]
  4380. exp: exp "+" . exp_hi (2)
  4381. \end{lstlisting}
  4382. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4383. the following dotted rules to slot $4$ of the chart.
  4384. \begin{lstlisting}[escapechar=$]
  4385. exp_hi: . INT (4)
  4386. exp_hi: . "input_int" "(" ")" (4)
  4387. exp_hi: . "-" exp_hi (4)
  4388. exp_hi: . "(" exp ")" (4)
  4389. \end{lstlisting}
  4390. The next input token is \code{"3"} which the lexer categorized as an
  4391. \code{INT}, so we advance the period past \code{INT} for the rules in
  4392. slot $4$, of which there is just one, and put the following into slot $5$.
  4393. \begin{lstlisting}[escapechar=$]
  4394. exp_hi: INT . (4)
  4395. \end{lstlisting}
  4396. The period at the end of the rule triggers a completion action for the
  4397. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4398. So we advance the period and put the following into slot $5$.
  4399. \begin{lstlisting}[escapechar=$]
  4400. exp: exp "+" exp_hi . (2)
  4401. \end{lstlisting}
  4402. This triggers another completion action for the rules in slot $2$ that
  4403. have a period before \code{exp}.
  4404. \begin{lstlisting}[escapechar=$]
  4405. stmt: "print" "(" exp . ")" (0)
  4406. exp: exp . "+" exp_hi (2)
  4407. exp: exp . "-" exp_hi (2)
  4408. \end{lstlisting}
  4409. We scan the next input token \code{")"}, placing the following dotted
  4410. rule into slot $6$.
  4411. \begin{lstlisting}[escapechar=$]
  4412. stmt: "print" "(" exp ")" . (0)
  4413. \end{lstlisting}
  4414. This triggers the completion of \code{stmt} in slot $0$
  4415. \begin{lstlisting}
  4416. stmt_list: stmt . NEWLINE stmt_list (0)
  4417. \end{lstlisting}
  4418. The last input token is a \code{NEWLINE}, so we advance the period
  4419. and place the new dotted rule into slot $7$.
  4420. \begin{lstlisting}
  4421. stmt_list: stmt NEWLINE . stmt_list (0)
  4422. \end{lstlisting}
  4423. We are close to the end of parsing the input!
  4424. The period is before the \code{stmt\_list} nonterminal, so we
  4425. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4426. \begin{lstlisting}
  4427. stmt_list: . (7)
  4428. stmt_list: . stmt NEWLINE stmt_list (7)
  4429. stmt: . "print" "(" exp ")" (7)
  4430. stmt: . exp (7)
  4431. \end{lstlisting}
  4432. There is immediately an opportunity for completion of \code{stmt\_list},
  4433. so we add the following to slot $7$.
  4434. \begin{lstlisting}
  4435. stmt_list: stmt NEWLINE stmt_list . (0)
  4436. \end{lstlisting}
  4437. This triggers another completion action for \code{stmt\_list} in slot $0$
  4438. \begin{lstlisting}
  4439. lang_int: stmt_list . (0)
  4440. \end{lstlisting}
  4441. which in turn completes \code{lang\_int}, the start symbol of the
  4442. grammar, so the parsing of the input is complete.
  4443. For reference, we now give a general description of Earley's
  4444. algorithm.
  4445. \begin{enumerate}
  4446. \item The algorithm begins by initializing slot $0$ of the chart with the
  4447. grammar rule for the start symbol, placing a period at the beginning
  4448. of the right-hand side, and recording its starting position as $0$.
  4449. \item The algorithm repeatedly applies the following three kinds of
  4450. actions for as long as there are opportunities to do so.
  4451. \begin{itemize}
  4452. \item Prediction: If there is a rule in slot $k$ whose period comes
  4453. before a nonterminal, add the rules for that nonterminal into slot
  4454. $k$, placing a period at the beginning of their right-hand sides
  4455. and recording their starting position as $k$.
  4456. \item Scanning: If the token at position $k$ of the input string
  4457. matches the symbol after the period in a dotted rule in slot $k$
  4458. of the chart, advance the period in the dotted rule, adding
  4459. the result to slot $k+1$.
  4460. \item Completion: If a dotted rule in slot $k$ has a period at the
  4461. end, inspect the rules in the slot corresponding to the starting
  4462. position of the completed rule. If any of those rules have a
  4463. nonterminal following their period that matches the left-hand side
  4464. of the completed rule, then advance their period, placing the new
  4465. dotted rule in slot $k$.
  4466. \end{itemize}
  4467. While repeating these three actions, take care never to add
  4468. duplicate dotted rules to the chart.
  4469. \end{enumerate}
  4470. We have described how Earley's algorithm recognizes that an input
  4471. string matches a grammar, but we have not described how it builds a
  4472. parse tree. The basic idea is simple, but building parse trees in an
  4473. efficient way is more complex, requiring a data structure called a
  4474. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4475. to attach a partial parse tree to every dotted rule in the chart.
  4476. Initially, the tree node associated with a dotted rule has no
  4477. children. As the period moves to the right, the nodes from the
  4478. subparses are added as children to the tree node.
  4479. As mentioned at the beginning of this section, Earley's algorithm is
  4480. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4481. files that contain thousands of tokens in a reasonable amount of time,
  4482. but not millions.
  4483. %
  4484. In the next section we discuss the LALR(1) parsing algorithm, which is
  4485. efficient enough to use with even the largest of input files.
  4486. \section{The LALR(1) Algorithm}
  4487. \label{sec:lalr}
  4488. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4489. two-phase approach in which it first compiles the grammar into a state
  4490. machine and then runs the state machine to parse an input string. The
  4491. second phase has time complexity $O(n)$ where $n$ is the number of
  4492. tokens in the input, so LALR(1) is the best one could hope for with
  4493. respect to efficiency.
  4494. %
  4495. A particularly influential implementation of LALR(1) is the
  4496. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4497. \texttt{yacc} stands for ``yet another compiler compiler''.
  4498. %
  4499. The LALR(1) state machine uses a stack to record its progress in
  4500. parsing the input string. Each element of the stack is a pair: a
  4501. state number and a grammar symbol (a terminal or a nonterminal). The
  4502. symbol characterizes the input that has been parsed so far, and the
  4503. state number is used to remember how to proceed once the next
  4504. symbol's worth of input has been parsed. Each state in the machine
  4505. represents where the parser stands in the parsing process with respect
  4506. to certain grammar rules. In particular, each state is associated with
  4507. a set of dotted rules.
  4508. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4509. (also called parse table) for the following simple but ambiguous
  4510. grammar:
  4511. \begin{lstlisting}[escapechar=$]
  4512. exp: INT
  4513. | exp "+" exp
  4514. stmt: "print" exp
  4515. start: stmt
  4516. \end{lstlisting}
  4517. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4518. read in a \lstinline{"print"} token, so the top of the stack is
  4519. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4520. the input according to grammar rule 1, which is signified by showing
  4521. rule 1 with a period after the \code{"print"} token and before the
  4522. \code{exp} nonterminal. There are two rules that could apply next,
  4523. rules 2 and 3, so state 1 also shows those rules with a period at
  4524. the beginning of their right-hand sides. The edges between states
  4525. indicate which transitions the machine should make depending on the
  4526. next input token. So, for example, if the next input token is
  4527. \code{INT} then the parser will push \code{INT} and the target state 4
  4528. on the stack and transition to state 4. Suppose that we are now at the end
  4529. of the input. State 4 says that we should reduce by rule 3, so we pop
  4530. from the stack the same number of items as the number of symbols in
  4531. the right-hand side of the rule, in this case just one. We then
  4532. momentarily jump to the state at the top of the stack (state 1) and
  4533. then follow the goto edge that corresponds to the left-hand side of
  4534. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4535. state 3. (A slightly longer example parse is shown in
  4536. figure~\ref{fig:shift-reduce}.)
  4537. \begin{figure}[htbp]
  4538. \centering
  4539. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4540. \caption{An LALR(1) parse table and a trace of an example run.}
  4541. \label{fig:shift-reduce}
  4542. \end{figure}
  4543. In general, the algorithm works as follows. First, set the current state to
  4544. state $0$. Then repeat the following, looking at the next input token.
  4545. \begin{itemize}
  4546. \item If there there is a shift edge for the input token in the
  4547. current state, push the edge's target state and the input token onto
  4548. the stack and proceed to the edge's target state.
  4549. \item If there is a reduce action for the input token in the current
  4550. state, pop $k$ elements from the stack, where $k$ is the number of
  4551. symbols in the right-hand side of the rule being reduced. Jump to
  4552. the state at the top of the stack and then follow the goto edge for
  4553. the nonterminal that matches the left-hand side of the rule that we
  4554. are reducing by. Push the edge's target state and the nonterminal on the
  4555. stack.
  4556. \end{itemize}
  4557. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4558. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4559. algorithm does not know which action to take in this case. When a
  4560. state has both a shift and a reduce action for the same token, we say
  4561. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4562. will arise, for example, in trying to parse the input
  4563. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4564. the parser will be in state 6 and will not know whether to
  4565. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4566. to proceed by shifting the next \lstinline{+} from the input.
  4567. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4568. arises when there are two reduce actions in a state for the same
  4569. token. To understand which grammars gives rise to shift/reduce and
  4570. reduce/reduce conflicts, it helps to know how the parse table is
  4571. generated from the grammar, which we discuss next.
  4572. The parse table is generated one state at a time. State 0 represents
  4573. the start of the parser. We add the grammar rule for the start symbol
  4574. to this state with a period at the beginning of the right-hand side,
  4575. similarly to the initialization phase of the Earley parser. If the
  4576. period appears immediately before another nonterminal, we add all the
  4577. rules with that nonterminal on the left-hand side. Again, we place a
  4578. period at the beginning of the right-hand side of each new
  4579. rule. This process, called \emph{state closure}, is continued
  4580. until there are no more rules to add (similarly to the prediction
  4581. actions of an Earley parser). We then examine each dotted rule in the
  4582. current state $I$. Suppose that a dotted rule has the form $A ::=
  4583. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4584. are sequences of symbols. We create a new state and call it $J$. If $X$
  4585. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4586. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4587. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4588. state $J$. We start by adding all dotted rules from state $I$ that
  4589. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4590. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4591. the period moved past the $X$. (This is analogous to completion in
  4592. Earley's algorithm.) We then perform state closure on $J$. This
  4593. process repeats until there are no more states or edges to add.
  4594. We then mark states as accepting states if they have a dotted rule
  4595. that is the start rule with a period at the end. Also, to add
  4596. the reduce actions, we look for any state containing a dotted rule
  4597. with a period at the end. Let $n$ be the rule number for this dotted
  4598. rule. We then put a reduce $n$ action into that state for every token
  4599. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4600. dotted rule with a period at the end. We therefore put a reduce by
  4601. rule 3 action into state 4 for every
  4602. token.
  4603. When inserting reduce actions, take care to spot any shift/reduce or
  4604. reduce/reduce conflicts. If there are any, abort the construction of
  4605. the parse table.
  4606. \begin{exercise}
  4607. \normalfont\normalsize
  4608. %
  4609. Working on paper, walk through the parse table generation process for
  4610. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4611. your results against the parse table shown in
  4612. figure~\ref{fig:shift-reduce}.
  4613. \end{exercise}
  4614. \begin{exercise}
  4615. \normalfont\normalsize
  4616. %
  4617. Change the parser in your compiler for \LangVar{} to set the
  4618. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4619. all the \LangVar{} programs that you have created. In doing so, Lark
  4620. may signal an error due to shift/reduce or reduce/reduce conflicts
  4621. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4622. remove those conflicts.
  4623. \end{exercise}
  4624. \section{Further Reading}
  4625. In this chapter we have just scratched the surface of the field of
  4626. parsing, with the study of a very general but less efficient algorithm
  4627. (Earley) and with a more limited but highly efficient algorithm
  4628. (LALR). There are many more algorithms and classes of grammars that
  4629. fall between these two ends of the spectrum. We recommend to the reader
  4630. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4631. Regarding lexical analysis, we have described the specification
  4632. language, which are the regular expressions, but not the algorithms
  4633. for recognizing them. In short, regular expressions can be translated
  4634. to nondeterministic finite automata, which in turn are translated to
  4635. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4636. all the details on lexical analysis.
  4637. \fi}
  4638. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4639. \chapter{Register Allocation}
  4640. \label{ch:register-allocation-Lvar}
  4641. \setcounter{footnote}{0}
  4642. \index{subject}{register allocation}
  4643. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4644. storing variables on the procedure call stack. The CPU may require tens
  4645. to hundreds of cycles to access a location on the stack, whereas
  4646. accessing a register takes only a single cycle. In this chapter we
  4647. improve the efficiency of our generated code by storing some variables
  4648. in registers. The goal of register allocation is to fit as many
  4649. variables into registers as possible. Some programs have more
  4650. variables than registers, so we cannot always map each variable to a
  4651. different register. Fortunately, it is common for different variables
  4652. to be in use during different periods of time during program
  4653. execution, and in those cases we can map multiple variables to the
  4654. same register.
  4655. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4656. example. The source program is on the left and the output of
  4657. instruction selection\index{subject}{instruction selection}
  4658. is on the right. The program is almost
  4659. completely in the x86 assembly language, but it still uses variables.
  4660. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4661. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4662. the other hand, is used only after this point, so \code{x} and
  4663. \code{z} could share the same register.
  4664. \begin{figure}
  4665. \begin{tcolorbox}[colback=white]
  4666. \begin{minipage}{0.45\textwidth}
  4667. Example \LangVar{} program:
  4668. % var_test_28.rkt
  4669. {\if\edition\racketEd
  4670. \begin{lstlisting}
  4671. (let ([v 1])
  4672. (let ([w 42])
  4673. (let ([x (+ v 7)])
  4674. (let ([y x])
  4675. (let ([z (+ x w)])
  4676. (+ z (- y)))))))
  4677. \end{lstlisting}
  4678. \fi}
  4679. {\if\edition\pythonEd\pythonColor
  4680. \begin{lstlisting}
  4681. v = 1
  4682. w = 42
  4683. x = v + 7
  4684. y = x
  4685. z = x + w
  4686. print(z + (- y))
  4687. \end{lstlisting}
  4688. \fi}
  4689. \end{minipage}
  4690. \begin{minipage}{0.45\textwidth}
  4691. After instruction selection:
  4692. {\if\edition\racketEd
  4693. \begin{lstlisting}
  4694. locals-types:
  4695. x : Integer, y : Integer,
  4696. z : Integer, t : Integer,
  4697. v : Integer, w : Integer
  4698. start:
  4699. movq $1, v
  4700. movq $42, w
  4701. movq v, x
  4702. addq $7, x
  4703. movq x, y
  4704. movq x, z
  4705. addq w, z
  4706. movq y, t
  4707. negq t
  4708. movq z, %rax
  4709. addq t, %rax
  4710. jmp conclusion
  4711. \end{lstlisting}
  4712. \fi}
  4713. {\if\edition\pythonEd\pythonColor
  4714. \begin{lstlisting}
  4715. movq $1, v
  4716. movq $42, w
  4717. movq v, x
  4718. addq $7, x
  4719. movq x, y
  4720. movq x, z
  4721. addq w, z
  4722. movq y, tmp_0
  4723. negq tmp_0
  4724. movq z, tmp_1
  4725. addq tmp_0, tmp_1
  4726. movq tmp_1, %rdi
  4727. callq print_int
  4728. \end{lstlisting}
  4729. \fi}
  4730. \end{minipage}
  4731. \end{tcolorbox}
  4732. \caption{A running example for register allocation.}
  4733. \label{fig:reg-eg}
  4734. \end{figure}
  4735. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4736. compute where a variable is in use. Once we have that information, we
  4737. compute which variables are in use at the same time, that is, which ones
  4738. \emph{interfere}\index{subject}{interfere} with each other, and
  4739. represent this relation as an undirected graph whose vertices are
  4740. variables and edges indicate when two variables interfere
  4741. (section~\ref{sec:build-interference}). We then model register
  4742. allocation as a graph coloring problem
  4743. (section~\ref{sec:graph-coloring}).
  4744. If we run out of registers despite these efforts, we place the
  4745. remaining variables on the stack, similarly to how we handled
  4746. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4747. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4748. location. The decision to spill a variable is handled as part of the
  4749. graph coloring process.
  4750. We make the simplifying assumption that each variable is assigned to
  4751. one location (a register or stack address). A more sophisticated
  4752. approach is to assign a variable to one or more locations in different
  4753. regions of the program. For example, if a variable is used many times
  4754. in short sequence and then used again only after many other
  4755. instructions, it could be more efficient to assign the variable to a
  4756. register during the initial sequence and then move it to the stack for
  4757. the rest of its lifetime. We refer the interested reader to
  4758. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4759. approach.
  4760. % discuss prioritizing variables based on how much they are used.
  4761. \section{Registers and Calling Conventions}
  4762. \label{sec:calling-conventions}
  4763. \index{subject}{calling conventions}
  4764. As we perform register allocation, we must be aware of the
  4765. \emph{calling conventions} \index{subject}{calling conventions} that
  4766. govern how function calls are performed in x86.
  4767. %
  4768. Even though \LangVar{} does not include programmer-defined functions,
  4769. our generated code includes a \code{main} function that is called by
  4770. the operating system and our generated code contains calls to the
  4771. \code{read\_int} function.
  4772. Function calls require coordination between two pieces of code that
  4773. may be written by different programmers or generated by different
  4774. compilers. Here we follow the System V calling conventions that are
  4775. used by the GNU C compiler on Linux and
  4776. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4777. %
  4778. The calling conventions include rules about how functions share the
  4779. use of registers. In particular, the caller is responsible for freeing
  4780. some registers prior to the function call for use by the callee.
  4781. These are called the \emph{caller-saved registers}
  4782. \index{subject}{caller-saved registers}
  4783. and they are
  4784. \begin{lstlisting}
  4785. rax rcx rdx rsi rdi r8 r9 r10 r11
  4786. \end{lstlisting}
  4787. On the other hand, the callee is responsible for preserving the values
  4788. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4789. which are
  4790. \begin{lstlisting}
  4791. rsp rbp rbx r12 r13 r14 r15
  4792. \end{lstlisting}
  4793. We can think about this caller/callee convention from two points of
  4794. view, the caller view and the callee view, as follows:
  4795. \begin{itemize}
  4796. \item The caller should assume that all the caller-saved registers get
  4797. overwritten with arbitrary values by the callee. On the other hand,
  4798. the caller can safely assume that all the callee-saved registers
  4799. retain their original values.
  4800. \item The callee can freely use any of the caller-saved registers.
  4801. However, if the callee wants to use a callee-saved register, the
  4802. callee must arrange to put the original value back in the register
  4803. prior to returning to the caller. This can be accomplished by saving
  4804. the value to the stack in the prelude of the function and restoring
  4805. the value in the conclusion of the function.
  4806. \end{itemize}
  4807. In x86, registers are also used for passing arguments to a function
  4808. and for the return value. In particular, the first six arguments of a
  4809. function are passed in the following six registers, in this order.
  4810. \begin{lstlisting}
  4811. rdi rsi rdx rcx r8 r9
  4812. \end{lstlisting}
  4813. We refer to these six registers are the argument-passing registers
  4814. \index{subject}{argument-passing registers}.
  4815. If there are more than six arguments, the convention is to use space
  4816. on the frame of the caller for the rest of the arguments. In
  4817. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4818. argument and the rest of the arguments, which simplifies the treatment
  4819. of efficient tail calls.
  4820. %
  4821. \racket{For now, the only function we care about is \code{read\_int},
  4822. which takes zero arguments.}
  4823. %
  4824. \python{For now, the only functions we care about are \code{read\_int}
  4825. and \code{print\_int}, which take zero and one argument, respectively.}
  4826. %
  4827. The register \code{rax} is used for the return value of a function.
  4828. The next question is how these calling conventions impact register
  4829. allocation. Consider the \LangVar{} program presented in
  4830. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4831. example from the caller point of view and then from the callee point
  4832. of view. We refer to a variable that is in use during a function call
  4833. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4834. The program makes two calls to \READOP{}. The variable \code{x} is
  4835. call-live because it is in use during the second call to \READOP{}; we
  4836. must ensure that the value in \code{x} does not get overwritten during
  4837. the call to \READOP{}. One obvious approach is to save all the values
  4838. that reside in caller-saved registers to the stack prior to each
  4839. function call and to restore them after each call. That way, if the
  4840. register allocator chooses to assign \code{x} to a caller-saved
  4841. register, its value will be preserved across the call to \READOP{}.
  4842. However, saving and restoring to the stack is relatively slow. If
  4843. \code{x} is not used many times, it may be better to assign \code{x}
  4844. to a stack location in the first place. Or better yet, if we can
  4845. arrange for \code{x} to be placed in a callee-saved register, then it
  4846. won't need to be saved and restored during function calls.
  4847. We recommend an approach that captures these issues in the
  4848. interference graph, without complicating the graph coloring algorithm.
  4849. During liveness analysis we know which variables are call-live because
  4850. we compute which variables are in use at every instruction
  4851. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4852. interference graph (section~\ref{sec:build-interference}), we can
  4853. place an edge in the interference graph between each call-live
  4854. variable and the caller-saved registers. This will prevent the graph
  4855. coloring algorithm from assigning call-live variables to caller-saved
  4856. registers.
  4857. On the other hand, for variables that are not call-live, we prefer
  4858. placing them in caller-saved registers to leave more room for
  4859. call-live variables in the callee-saved registers. This can also be
  4860. implemented without complicating the graph coloring algorithm. We
  4861. recommend that the graph coloring algorithm assign variables to
  4862. natural numbers, choosing the lowest number for which there is no
  4863. interference. After the coloring is complete, we map the numbers to
  4864. registers and stack locations: mapping the lowest numbers to
  4865. caller-saved registers, the next lowest to callee-saved registers, and
  4866. the largest numbers to stack locations. This ordering gives preference
  4867. to registers over stack locations and to caller-saved registers over
  4868. callee-saved registers.
  4869. Returning to the example in
  4870. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4871. generated x86 code on the right-hand side. Variable \code{x} is
  4872. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4873. in a safe place during the second call to \code{read\_int}. Next,
  4874. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4875. because \code{y} is not a call-live variable.
  4876. We have completed the analysis from the caller point of view, so now
  4877. we switch to the callee point of view, focusing on the prelude and
  4878. conclusion of the \code{main} function. As usual, the prelude begins
  4879. with saving the \code{rbp} register to the stack and setting the
  4880. \code{rbp} to the current stack pointer. We now know why it is
  4881. necessary to save the \code{rbp}: it is a callee-saved register. The
  4882. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4883. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4884. (\code{x}). The other callee-saved registers are not saved in the
  4885. prelude because they are not used. The prelude subtracts 8 bytes from
  4886. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4887. conclusion, we see that \code{rbx} is restored from the stack with a
  4888. \code{popq} instruction.
  4889. \index{subject}{prelude}\index{subject}{conclusion}
  4890. \begin{figure}[tp]
  4891. \begin{tcolorbox}[colback=white]
  4892. \begin{minipage}{0.45\textwidth}
  4893. Example \LangVar{} program:
  4894. %var_test_14.rkt
  4895. {\if\edition\racketEd
  4896. \begin{lstlisting}
  4897. (let ([x (read)])
  4898. (let ([y (read)])
  4899. (+ (+ x y) 42)))
  4900. \end{lstlisting}
  4901. \fi}
  4902. {\if\edition\pythonEd\pythonColor
  4903. \begin{lstlisting}
  4904. x = input_int()
  4905. y = input_int()
  4906. print((x + y) + 42)
  4907. \end{lstlisting}
  4908. \fi}
  4909. \end{minipage}
  4910. \begin{minipage}{0.45\textwidth}
  4911. Generated x86 assembly:
  4912. {\if\edition\racketEd
  4913. \begin{lstlisting}
  4914. start:
  4915. callq read_int
  4916. movq %rax, %rbx
  4917. callq read_int
  4918. movq %rax, %rcx
  4919. addq %rcx, %rbx
  4920. movq %rbx, %rax
  4921. addq $42, %rax
  4922. jmp _conclusion
  4923. .globl main
  4924. main:
  4925. pushq %rbp
  4926. movq %rsp, %rbp
  4927. pushq %rbx
  4928. subq $8, %rsp
  4929. jmp start
  4930. conclusion:
  4931. addq $8, %rsp
  4932. popq %rbx
  4933. popq %rbp
  4934. retq
  4935. \end{lstlisting}
  4936. \fi}
  4937. {\if\edition\pythonEd\pythonColor
  4938. \begin{lstlisting}
  4939. .globl main
  4940. main:
  4941. pushq %rbp
  4942. movq %rsp, %rbp
  4943. pushq %rbx
  4944. subq $8, %rsp
  4945. callq read_int
  4946. movq %rax, %rbx
  4947. callq read_int
  4948. movq %rax, %rcx
  4949. movq %rbx, %rdx
  4950. addq %rcx, %rdx
  4951. movq %rdx, %rcx
  4952. addq $42, %rcx
  4953. movq %rcx, %rdi
  4954. callq print_int
  4955. addq $8, %rsp
  4956. popq %rbx
  4957. popq %rbp
  4958. retq
  4959. \end{lstlisting}
  4960. \fi}
  4961. \end{minipage}
  4962. \end{tcolorbox}
  4963. \caption{An example with function calls.}
  4964. \label{fig:example-calling-conventions}
  4965. \end{figure}
  4966. %\clearpage
  4967. \section{Liveness Analysis}
  4968. \label{sec:liveness-analysis-Lvar}
  4969. \index{subject}{liveness analysis}
  4970. The \code{uncover\_live} \racket{pass}\python{function} performs
  4971. \emph{liveness analysis}; that is, it discovers which variables are
  4972. in use in different regions of a program.
  4973. %
  4974. A variable or register is \emph{live} at a program point if its
  4975. current value is used at some later point in the program. We refer to
  4976. variables, stack locations, and registers collectively as
  4977. \emph{locations}.
  4978. %
  4979. Consider the following code fragment in which there are two writes to
  4980. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4981. time?
  4982. \begin{center}
  4983. \begin{minipage}{0.85\textwidth}
  4984. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4985. movq $5, a
  4986. movq $30, b
  4987. movq a, c
  4988. movq $10, b
  4989. addq b, c
  4990. \end{lstlisting}
  4991. \end{minipage}
  4992. \end{center}
  4993. The answer is no, because \code{a} is live from line 1 to 3 and
  4994. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4995. line 2 is never used because it is overwritten (line 4) before the
  4996. next read (line 5).
  4997. The live locations for each instruction can be computed by traversing
  4998. the instruction sequence back to front (i.e., backward in execution
  4999. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5000. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5001. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5002. locations before instruction $I_k$. \racket{We recommend representing
  5003. these sets with the Racket \code{set} data structure described in
  5004. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5005. with the Python
  5006. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5007. data structure.}
  5008. {\if\edition\racketEd
  5009. \begin{figure}[tp]
  5010. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5011. \small
  5012. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5013. A \emph{set} is an unordered collection of elements without duplicates.
  5014. Here are some of the operations defined on sets.
  5015. \index{subject}{set}
  5016. \begin{description}
  5017. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5018. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5019. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5020. difference of the two sets.
  5021. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5022. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5023. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5024. \end{description}
  5025. \end{tcolorbox}
  5026. %\end{wrapfigure}
  5027. \caption{The \code{set} data structure.}
  5028. \label{fig:set}
  5029. \end{figure}
  5030. \fi}
  5031. The locations that are live after an instruction are its
  5032. \emph{live-after}\index{subject}{live-after} set, and the locations
  5033. that are live before an instruction are its
  5034. \emph{live-before}\index{subject}{live-before} set. The live-after
  5035. set of an instruction is always the same as the live-before set of the
  5036. next instruction.
  5037. \begin{equation} \label{eq:live-after-before-next}
  5038. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5039. \end{equation}
  5040. To start things off, there are no live locations after the last
  5041. instruction, so
  5042. \begin{equation}\label{eq:live-last-empty}
  5043. L_{\mathsf{after}}(n) = \emptyset
  5044. \end{equation}
  5045. We then apply the following rule repeatedly, traversing the
  5046. instruction sequence back to front.
  5047. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5048. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5049. \end{equation}
  5050. where $W(k)$ are the locations written to by instruction $I_k$, and
  5051. $R(k)$ are the locations read by instruction $I_k$.
  5052. {\if\edition\racketEd
  5053. %
  5054. There is a special case for \code{jmp} instructions. The locations
  5055. that are live before a \code{jmp} should be the locations in
  5056. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5057. maintaining an alist named \code{label->live} that maps each label to
  5058. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5059. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5060. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5061. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5062. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5063. %
  5064. \fi}
  5065. Let us walk through the previous example, applying these formulas
  5066. starting with the instruction on line 5 of the code fragment. We
  5067. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5068. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5069. $\emptyset$ because it is the last instruction
  5070. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5071. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5072. variables \code{b} and \code{c}
  5073. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5074. \[
  5075. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5076. \]
  5077. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5078. the live-before set from line 5 to be the live-after set for this
  5079. instruction (formula~\eqref{eq:live-after-before-next}).
  5080. \[
  5081. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5082. \]
  5083. This move instruction writes to \code{b} and does not read from any
  5084. variables, so we have the following live-before set
  5085. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5086. \[
  5087. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5088. \]
  5089. The live-before for instruction \code{movq a, c}
  5090. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5091. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5092. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5093. variable that is not live and does not read from a variable.
  5094. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5095. because it writes to variable \code{a}.
  5096. \begin{figure}[tbp]
  5097. \centering
  5098. \begin{tcolorbox}[colback=white]
  5099. \hspace{10pt}
  5100. \begin{minipage}{0.4\textwidth}
  5101. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5102. movq $5, a
  5103. movq $30, b
  5104. movq a, c
  5105. movq $10, b
  5106. addq b, c
  5107. \end{lstlisting}
  5108. \end{minipage}
  5109. \vrule\hspace{10pt}
  5110. \begin{minipage}{0.45\textwidth}
  5111. \begin{align*}
  5112. L_{\mathsf{before}}(1)= \emptyset,
  5113. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5114. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5115. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5116. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5117. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5118. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5119. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5120. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5121. L_{\mathsf{after}}(5)= \emptyset
  5122. \end{align*}
  5123. \end{minipage}
  5124. \end{tcolorbox}
  5125. \caption{Example output of liveness analysis on a short example.}
  5126. \label{fig:liveness-example-0}
  5127. \end{figure}
  5128. \begin{exercise}\normalfont\normalsize
  5129. Perform liveness analysis by hand on the running example in
  5130. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5131. sets for each instruction. Compare your answers to the solution
  5132. shown in figure~\ref{fig:live-eg}.
  5133. \end{exercise}
  5134. \begin{figure}[tp]
  5135. \hspace{20pt}
  5136. \begin{minipage}{0.55\textwidth}
  5137. \begin{tcolorbox}[colback=white]
  5138. {\if\edition\racketEd
  5139. \begin{lstlisting}
  5140. |$\{\ttm{rsp}\}$|
  5141. movq $1, v
  5142. |$\{\ttm{v},\ttm{rsp}\}$|
  5143. movq $42, w
  5144. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5145. movq v, x
  5146. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5147. addq $7, x
  5148. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5149. movq x, y
  5150. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5151. movq x, z
  5152. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5153. addq w, z
  5154. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5155. movq y, t
  5156. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5157. negq t
  5158. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5159. movq z, %rax
  5160. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5161. addq t, %rax
  5162. |$\{\ttm{rax},\ttm{rsp}\}$|
  5163. jmp conclusion
  5164. \end{lstlisting}
  5165. \fi}
  5166. {\if\edition\pythonEd\pythonColor
  5167. \begin{lstlisting}
  5168. movq $1, v
  5169. |$\{\ttm{v}\}$|
  5170. movq $42, w
  5171. |$\{\ttm{w}, \ttm{v}\}$|
  5172. movq v, x
  5173. |$\{\ttm{w}, \ttm{x}\}$|
  5174. addq $7, x
  5175. |$\{\ttm{w}, \ttm{x}\}$|
  5176. movq x, y
  5177. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5178. movq x, z
  5179. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5180. addq w, z
  5181. |$\{\ttm{y}, \ttm{z}\}$|
  5182. movq y, tmp_0
  5183. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5184. negq tmp_0
  5185. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5186. movq z, tmp_1
  5187. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5188. addq tmp_0, tmp_1
  5189. |$\{\ttm{tmp\_1}\}$|
  5190. movq tmp_1, %rdi
  5191. |$\{\ttm{rdi}\}$|
  5192. callq print_int
  5193. |$\{\}$|
  5194. \end{lstlisting}
  5195. \fi}
  5196. \end{tcolorbox}
  5197. \end{minipage}
  5198. \caption{The running example annotated with live-after sets.}
  5199. \label{fig:live-eg}
  5200. \end{figure}
  5201. \begin{exercise}\normalfont\normalsize
  5202. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5203. %
  5204. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5205. field of the \code{Block} structure.}
  5206. %
  5207. \python{Return a dictionary that maps each instruction to its
  5208. live-after set.}
  5209. %
  5210. \racket{We recommend creating an auxiliary function that takes a list
  5211. of instructions and an initial live-after set (typically empty) and
  5212. returns the list of live-after sets.}
  5213. %
  5214. We recommend creating auxiliary functions to (1) compute the set
  5215. of locations that appear in an \Arg{}, (2) compute the locations read
  5216. by an instruction (the $R$ function), and (3) the locations written by
  5217. an instruction (the $W$ function). The \code{callq} instruction should
  5218. include all the caller-saved registers in its write set $W$ because
  5219. the calling convention says that those registers may be written to
  5220. during the function call. Likewise, the \code{callq} instruction
  5221. should include the appropriate argument-passing registers in its
  5222. read set $R$, depending on the arity of the function being
  5223. called. (This is why the abstract syntax for \code{callq} includes the
  5224. arity.)
  5225. \end{exercise}
  5226. %\clearpage
  5227. \section{Build the Interference Graph}
  5228. \label{sec:build-interference}
  5229. {\if\edition\racketEd
  5230. \begin{figure}[tp]
  5231. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5232. \small
  5233. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5234. A \emph{graph} is a collection of vertices and edges where each
  5235. edge connects two vertices. A graph is \emph{directed} if each
  5236. edge points from a source to a target. Otherwise the graph is
  5237. \emph{undirected}.
  5238. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5239. \begin{description}
  5240. %% We currently don't use directed graphs. We instead use
  5241. %% directed multi-graphs. -Jeremy
  5242. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5243. directed graph from a list of edges. Each edge is a list
  5244. containing the source and target vertex.
  5245. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5246. undirected graph from a list of edges. Each edge is represented by
  5247. a list containing two vertices.
  5248. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5249. inserts a vertex into the graph.
  5250. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5251. inserts an edge between the two vertices.
  5252. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5253. returns a sequence of vertices adjacent to the vertex.
  5254. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5255. returns a sequence of all vertices in the graph.
  5256. \end{description}
  5257. \end{tcolorbox}
  5258. %\end{wrapfigure}
  5259. \caption{The Racket \code{graph} package.}
  5260. \label{fig:graph}
  5261. \end{figure}
  5262. \fi}
  5263. On the basis of the liveness analysis, we know where each location is
  5264. live. However, during register allocation, we need to answer
  5265. questions of the specific form: are locations $u$ and $v$ live at the
  5266. same time? (If so, they cannot be assigned to the same register.) To
  5267. make this question more efficient to answer, we create an explicit
  5268. data structure, an \emph{interference
  5269. graph}\index{subject}{interference graph}. An interference graph is
  5270. an undirected graph that has a node for every variable and register
  5271. and has an edge between two nodes if they are
  5272. live at the same time, that is, if they interfere with each other.
  5273. %
  5274. \racket{We recommend using the Racket \code{graph} package
  5275. (figure~\ref{fig:graph}) to represent the interference graph.}
  5276. %
  5277. \python{We provide implementations of directed and undirected graph
  5278. data structures in the file \code{graph.py} of the support code.}
  5279. A straightforward way to compute the interference graph is to look at
  5280. the set of live locations between each instruction and add an edge to
  5281. the graph for every pair of variables in the same set. This approach
  5282. is less than ideal for two reasons. First, it can be expensive because
  5283. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5284. locations. Second, in the special case in which two locations hold the
  5285. same value (because one was assigned to the other), they can be live
  5286. at the same time without interfering with each other.
  5287. A better way to compute the interference graph is to focus on
  5288. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5289. must not overwrite something in a live location. So for each
  5290. instruction, we create an edge between the locations being written to
  5291. and the live locations. (However, a location never interferes with
  5292. itself.) For the \key{callq} instruction, we consider all the
  5293. caller-saved registers to have been written to, so an edge is added
  5294. between every live variable and every caller-saved register. Also, for
  5295. \key{movq} there is the special case of two variables holding the same
  5296. value. If a live variable $v$ is the same as the source of the
  5297. \key{movq}, then there is no need to add an edge between $v$ and the
  5298. destination, because they both hold the same value.
  5299. %
  5300. Hence we have the following two rules:
  5301. \begin{enumerate}
  5302. \item If instruction $I_k$ is a move instruction of the form
  5303. \key{movq} $s$\key{,} $d$, then for every $v \in
  5304. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5305. $(d,v)$.
  5306. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5307. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5308. $(d,v)$.
  5309. \end{enumerate}
  5310. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5311. these rules to each instruction. We highlight a few of the
  5312. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5313. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5314. so \code{v} interferes with \code{rsp}.}
  5315. %
  5316. \python{The first instruction is \lstinline{movq $1, v}, and the
  5317. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5318. no interference because $\ttm{v}$ is the destination of the move.}
  5319. %
  5320. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5321. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5322. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5323. %
  5324. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5325. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5326. $\ttm{x}$ interferes with \ttm{w}.}
  5327. %
  5328. \racket{The next instruction is \lstinline{movq x, y}, and the
  5329. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5330. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5331. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5332. \ttm{x} and \ttm{y} hold the same value.}
  5333. %
  5334. \python{The next instruction is \lstinline{movq x, y}, and the
  5335. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5336. applies, so \ttm{y} interferes with \ttm{w} but not
  5337. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5338. \ttm{x} and \ttm{y} hold the same value.}
  5339. %
  5340. Figure~\ref{fig:interference-results} lists the interference results
  5341. for all the instructions, and the resulting interference graph is
  5342. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5343. the interference graph in figure~\ref{fig:interfere} because there
  5344. were no interference edges involving registers and we did not wish to
  5345. clutter the graph, but in general one needs to include all the
  5346. registers in the interference graph.
  5347. \begin{figure}[tbp]
  5348. \begin{tcolorbox}[colback=white]
  5349. \begin{quote}
  5350. {\if\edition\racketEd
  5351. \begin{tabular}{ll}
  5352. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5353. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5354. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5355. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5356. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5357. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5358. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5359. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5360. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5361. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5362. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5363. \lstinline!jmp conclusion!& no interference.
  5364. \end{tabular}
  5365. \fi}
  5366. {\if\edition\pythonEd\pythonColor
  5367. \begin{tabular}{ll}
  5368. \lstinline!movq $1, v!& no interference\\
  5369. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5370. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5371. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5372. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5373. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5374. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5375. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5376. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5377. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5378. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5379. \lstinline!movq tmp_1, %rdi! & no interference \\
  5380. \lstinline!callq print_int!& no interference.
  5381. \end{tabular}
  5382. \fi}
  5383. \end{quote}
  5384. \end{tcolorbox}
  5385. \caption{Interference results for the running example.}
  5386. \label{fig:interference-results}
  5387. \end{figure}
  5388. \begin{figure}[tbp]
  5389. \begin{tcolorbox}[colback=white]
  5390. \large
  5391. {\if\edition\racketEd
  5392. \[
  5393. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5394. \node (rax) at (0,0) {$\ttm{rax}$};
  5395. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5396. \node (t1) at (0,2) {$\ttm{t}$};
  5397. \node (z) at (3,2) {$\ttm{z}$};
  5398. \node (x) at (6,2) {$\ttm{x}$};
  5399. \node (y) at (3,0) {$\ttm{y}$};
  5400. \node (w) at (6,0) {$\ttm{w}$};
  5401. \node (v) at (9,0) {$\ttm{v}$};
  5402. \draw (t1) to (rax);
  5403. \draw (t1) to (z);
  5404. \draw (z) to (y);
  5405. \draw (z) to (w);
  5406. \draw (x) to (w);
  5407. \draw (y) to (w);
  5408. \draw (v) to (w);
  5409. \draw (v) to (rsp);
  5410. \draw (w) to (rsp);
  5411. \draw (x) to (rsp);
  5412. \draw (y) to (rsp);
  5413. \path[-.,bend left=15] (z) edge node {} (rsp);
  5414. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5415. \draw (rax) to (rsp);
  5416. \end{tikzpicture}
  5417. \]
  5418. \fi}
  5419. {\if\edition\pythonEd\pythonColor
  5420. \[
  5421. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5422. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5423. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5424. \node (z) at (3,2) {$\ttm{z}$};
  5425. \node (x) at (6,2) {$\ttm{x}$};
  5426. \node (y) at (3,0) {$\ttm{y}$};
  5427. \node (w) at (6,0) {$\ttm{w}$};
  5428. \node (v) at (9,0) {$\ttm{v}$};
  5429. \draw (t0) to (t1);
  5430. \draw (t0) to (z);
  5431. \draw (z) to (y);
  5432. \draw (z) to (w);
  5433. \draw (x) to (w);
  5434. \draw (y) to (w);
  5435. \draw (v) to (w);
  5436. \end{tikzpicture}
  5437. \]
  5438. \fi}
  5439. \end{tcolorbox}
  5440. \caption{The interference graph of the example program.}
  5441. \label{fig:interfere}
  5442. \end{figure}
  5443. \begin{exercise}\normalfont\normalsize
  5444. \racket{Implement the compiler pass named \code{build\_interference} according
  5445. to the algorithm suggested here. We recommend using the Racket
  5446. \code{graph} package to create and inspect the interference graph.
  5447. The output graph of this pass should be stored in the $\itm{info}$ field of
  5448. the program, under the key \code{conflicts}.}
  5449. %
  5450. \python{Implement a function named \code{build\_interference}
  5451. according to the algorithm suggested above that
  5452. returns the interference graph.}
  5453. \end{exercise}
  5454. \section{Graph Coloring via Sudoku}
  5455. \label{sec:graph-coloring}
  5456. \index{subject}{graph coloring}
  5457. \index{subject}{sudoku}
  5458. \index{subject}{color}
  5459. We come to the main event discussed in this chapter, mapping variables
  5460. to registers and stack locations. Variables that interfere with each
  5461. other must be mapped to different locations. In terms of the
  5462. interference graph, this means that adjacent vertices must be mapped
  5463. to different locations. If we think of locations as colors, the
  5464. register allocation problem becomes the graph coloring
  5465. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5466. The reader may be more familiar with the graph coloring problem than he
  5467. or she realizes; the popular game of sudoku is an instance of the
  5468. graph coloring problem. The following describes how to build a graph
  5469. out of an initial sudoku board.
  5470. \begin{itemize}
  5471. \item There is one vertex in the graph for each sudoku square.
  5472. \item There is an edge between two vertices if the corresponding squares
  5473. are in the same row, in the same column, or in the same $3\times 3$ region.
  5474. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5475. \item On the basis of the initial assignment of numbers to squares on the
  5476. sudoku board, assign the corresponding colors to the corresponding
  5477. vertices in the graph.
  5478. \end{itemize}
  5479. If you can color the remaining vertices in the graph with the nine
  5480. colors, then you have also solved the corresponding game of sudoku.
  5481. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5482. the corresponding graph with colored vertices. Here we use a
  5483. monochrome representation of colors, mapping the sudoku number 1 to
  5484. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5485. of the vertices (the colored ones) because showing edges for all the
  5486. vertices would make the graph unreadable.
  5487. \begin{figure}[tbp]
  5488. \begin{tcolorbox}[colback=white]
  5489. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5490. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5491. \end{tcolorbox}
  5492. \caption{A sudoku game board and the corresponding colored graph.}
  5493. \label{fig:sudoku-graph}
  5494. \end{figure}
  5495. Some techniques for playing sudoku correspond to heuristics used in
  5496. graph coloring algorithms. For example, one of the basic techniques
  5497. for sudoku is called Pencil Marks. The idea is to use a process of
  5498. elimination to determine what numbers are no longer available for a
  5499. square and to write those numbers in the square (writing very
  5500. small). For example, if the number $1$ is assigned to a square, then
  5501. write the pencil mark $1$ in all the squares in the same row, column,
  5502. and region to indicate that $1$ is no longer an option for those other
  5503. squares.
  5504. %
  5505. The Pencil Marks technique corresponds to the notion of
  5506. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5507. saturation of a vertex, in sudoku terms, is the set of numbers that
  5508. are no longer available. In graph terminology, we have the following
  5509. definition:
  5510. \begin{equation*}
  5511. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5512. \text{ and } \mathrm{color}(v) = c \}
  5513. \end{equation*}
  5514. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5515. edge with $u$.
  5516. The Pencil Marks technique leads to a simple strategy for filling in
  5517. numbers: if there is a square with only one possible number left, then
  5518. choose that number! But what if there are no squares with only one
  5519. possibility left? One brute-force approach is to try them all: choose
  5520. the first one, and if that ultimately leads to a solution, great. If
  5521. not, backtrack and choose the next possibility. One good thing about
  5522. Pencil Marks is that it reduces the degree of branching in the search
  5523. tree. Nevertheless, backtracking can be terribly time consuming. One
  5524. way to reduce the amount of backtracking is to use the
  5525. most-constrained-first heuristic (aka minimum remaining
  5526. values)~\citep{Russell2003}. That is, in choosing a square, always
  5527. choose one with the fewest possibilities left (the vertex with the
  5528. highest saturation). The idea is that choosing highly constrained
  5529. squares earlier rather than later is better, because later on there may
  5530. not be any possibilities left in the highly saturated squares.
  5531. However, register allocation is easier than sudoku, because the
  5532. register allocator can fall back to assigning variables to stack
  5533. locations when the registers run out. Thus, it makes sense to replace
  5534. backtracking with greedy search: make the best choice at the time and
  5535. keep going. We still wish to minimize the number of colors needed, so
  5536. we use the most-constrained-first heuristic in the greedy search.
  5537. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5538. algorithm for register allocation based on saturation and the
  5539. most-constrained-first heuristic. It is roughly equivalent to the
  5540. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5541. sudoku, the algorithm represents colors with integers. The integers
  5542. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5543. register allocation. In particular, we recommend the following
  5544. correspondence, with $k=11$.
  5545. \begin{lstlisting}
  5546. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5547. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5548. \end{lstlisting}
  5549. The integers $k$ and larger correspond to stack locations. The
  5550. registers that are not used for register allocation, such as
  5551. \code{rax}, are assigned to negative integers. In particular, we
  5552. recommend the following correspondence.
  5553. \begin{lstlisting}
  5554. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5555. \end{lstlisting}
  5556. %% One might wonder why we include registers at all in the liveness
  5557. %% analysis and interference graph. For example, we never allocate a
  5558. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5559. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5560. %% to use register for passing arguments to functions, it will be
  5561. %% necessary for those registers to appear in the interference graph
  5562. %% because those registers will also be assigned to variables, and we
  5563. %% don't want those two uses to encroach on each other. Regarding
  5564. %% registers such as \code{rax} and \code{rsp} that are not used for
  5565. %% variables, we could omit them from the interference graph but that
  5566. %% would require adding special cases to our algorithm, which would
  5567. %% complicate the logic for little gain.
  5568. \begin{figure}[btp]
  5569. \begin{tcolorbox}[colback=white]
  5570. \centering
  5571. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5572. Algorithm: DSATUR
  5573. Input: A graph |$G$|
  5574. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5575. |$W \gets \mathrm{vertices}(G)$|
  5576. while |$W \neq \emptyset$| do
  5577. pick a vertex |$u$| from |$W$| with the highest saturation,
  5578. breaking ties randomly
  5579. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5580. |$\mathrm{color}[u] \gets c$|
  5581. |$W \gets W - \{u\}$|
  5582. \end{lstlisting}
  5583. \end{tcolorbox}
  5584. \caption{The saturation-based greedy graph coloring algorithm.}
  5585. \label{fig:satur-algo}
  5586. \end{figure}
  5587. {\if\edition\racketEd
  5588. With the DSATUR algorithm in hand, let us return to the running
  5589. example and consider how to color the interference graph shown in
  5590. figure~\ref{fig:interfere}.
  5591. %
  5592. We start by assigning each register node to its own color. For
  5593. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5594. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5595. (To reduce clutter in the interference graph, we elide nodes
  5596. that do not have interference edges, such as \code{rcx}.)
  5597. The variables are not yet colored, so they are annotated with a dash. We
  5598. then update the saturation for vertices that are adjacent to a
  5599. register, obtaining the following annotated graph. For example, the
  5600. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5601. \code{rax} and \code{rsp}.
  5602. \[
  5603. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5604. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5605. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5606. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5607. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5608. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5609. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5610. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5611. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5612. \draw (t1) to (rax);
  5613. \draw (t1) to (z);
  5614. \draw (z) to (y);
  5615. \draw (z) to (w);
  5616. \draw (x) to (w);
  5617. \draw (y) to (w);
  5618. \draw (v) to (w);
  5619. \draw (v) to (rsp);
  5620. \draw (w) to (rsp);
  5621. \draw (x) to (rsp);
  5622. \draw (y) to (rsp);
  5623. \path[-.,bend left=15] (z) edge node {} (rsp);
  5624. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5625. \draw (rax) to (rsp);
  5626. \end{tikzpicture}
  5627. \]
  5628. The algorithm says to select a maximally saturated vertex. So, we pick
  5629. $\ttm{t}$ and color it with the first available integer, which is
  5630. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5631. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5632. \[
  5633. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5634. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5635. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5636. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5637. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5638. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5639. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5640. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5641. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5642. \draw (t1) to (rax);
  5643. \draw (t1) to (z);
  5644. \draw (z) to (y);
  5645. \draw (z) to (w);
  5646. \draw (x) to (w);
  5647. \draw (y) to (w);
  5648. \draw (v) to (w);
  5649. \draw (v) to (rsp);
  5650. \draw (w) to (rsp);
  5651. \draw (x) to (rsp);
  5652. \draw (y) to (rsp);
  5653. \path[-.,bend left=15] (z) edge node {} (rsp);
  5654. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5655. \draw (rax) to (rsp);
  5656. \end{tikzpicture}
  5657. \]
  5658. We repeat the process, selecting a maximally saturated vertex,
  5659. choosing \code{z}, and coloring it with the first available number, which
  5660. is $1$. We add $1$ to the saturation for the neighboring vertices
  5661. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5662. \[
  5663. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5664. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5665. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5666. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5667. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5668. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5669. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5670. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5671. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5672. \draw (t1) to (rax);
  5673. \draw (t1) to (z);
  5674. \draw (z) to (y);
  5675. \draw (z) to (w);
  5676. \draw (x) to (w);
  5677. \draw (y) to (w);
  5678. \draw (v) to (w);
  5679. \draw (v) to (rsp);
  5680. \draw (w) to (rsp);
  5681. \draw (x) to (rsp);
  5682. \draw (y) to (rsp);
  5683. \path[-.,bend left=15] (z) edge node {} (rsp);
  5684. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5685. \draw (rax) to (rsp);
  5686. \end{tikzpicture}
  5687. \]
  5688. The most saturated vertices are now \code{w} and \code{y}. We color
  5689. \code{w} with the first available color, which is $0$.
  5690. \[
  5691. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5692. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5693. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5694. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5695. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5696. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5697. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5698. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5699. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5700. \draw (t1) to (rax);
  5701. \draw (t1) to (z);
  5702. \draw (z) to (y);
  5703. \draw (z) to (w);
  5704. \draw (x) to (w);
  5705. \draw (y) to (w);
  5706. \draw (v) to (w);
  5707. \draw (v) to (rsp);
  5708. \draw (w) to (rsp);
  5709. \draw (x) to (rsp);
  5710. \draw (y) to (rsp);
  5711. \path[-.,bend left=15] (z) edge node {} (rsp);
  5712. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5713. \draw (rax) to (rsp);
  5714. \end{tikzpicture}
  5715. \]
  5716. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5717. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5718. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5719. and \code{z}, whose colors are $0$ and $1$ respectively.
  5720. \[
  5721. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5722. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5723. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5724. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5725. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5726. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5727. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5728. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5729. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5730. \draw (t1) to (rax);
  5731. \draw (t1) to (z);
  5732. \draw (z) to (y);
  5733. \draw (z) to (w);
  5734. \draw (x) to (w);
  5735. \draw (y) to (w);
  5736. \draw (v) to (w);
  5737. \draw (v) to (rsp);
  5738. \draw (w) to (rsp);
  5739. \draw (x) to (rsp);
  5740. \draw (y) to (rsp);
  5741. \path[-.,bend left=15] (z) edge node {} (rsp);
  5742. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5743. \draw (rax) to (rsp);
  5744. \end{tikzpicture}
  5745. \]
  5746. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5747. \[
  5748. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5749. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5750. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5751. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5752. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5753. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5754. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5755. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5756. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5757. \draw (t1) to (rax);
  5758. \draw (t1) to (z);
  5759. \draw (z) to (y);
  5760. \draw (z) to (w);
  5761. \draw (x) to (w);
  5762. \draw (y) to (w);
  5763. \draw (v) to (w);
  5764. \draw (v) to (rsp);
  5765. \draw (w) to (rsp);
  5766. \draw (x) to (rsp);
  5767. \draw (y) to (rsp);
  5768. \path[-.,bend left=15] (z) edge node {} (rsp);
  5769. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5770. \draw (rax) to (rsp);
  5771. \end{tikzpicture}
  5772. \]
  5773. In the last step of the algorithm, we color \code{x} with $1$.
  5774. \[
  5775. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5776. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5777. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5778. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5779. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5780. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5781. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5782. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5783. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5784. \draw (t1) to (rax);
  5785. \draw (t1) to (z);
  5786. \draw (z) to (y);
  5787. \draw (z) to (w);
  5788. \draw (x) to (w);
  5789. \draw (y) to (w);
  5790. \draw (v) to (w);
  5791. \draw (v) to (rsp);
  5792. \draw (w) to (rsp);
  5793. \draw (x) to (rsp);
  5794. \draw (y) to (rsp);
  5795. \path[-.,bend left=15] (z) edge node {} (rsp);
  5796. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5797. \draw (rax) to (rsp);
  5798. \end{tikzpicture}
  5799. \]
  5800. So, we obtain the following coloring:
  5801. \[
  5802. \{
  5803. \ttm{rax} \mapsto -1,
  5804. \ttm{rsp} \mapsto -2,
  5805. \ttm{t} \mapsto 0,
  5806. \ttm{z} \mapsto 1,
  5807. \ttm{x} \mapsto 1,
  5808. \ttm{y} \mapsto 2,
  5809. \ttm{w} \mapsto 0,
  5810. \ttm{v} \mapsto 1
  5811. \}
  5812. \]
  5813. \fi}
  5814. %
  5815. {\if\edition\pythonEd\pythonColor
  5816. %
  5817. With the DSATUR algorithm in hand, let us return to the running
  5818. example and consider how to color the interference graph shown in
  5819. figure~\ref{fig:interfere}, again mapping 1 to blank, 2 to white, and
  5820. 3 to gray. We annotate each variable node with a dash to indicate that
  5821. it has not yet been assigned a color. Each register node (not shown)
  5822. should be assigned the number that the register corresponds to, for
  5823. example, color \code{rcx} with the number \code{0} and \code{rdx} with
  5824. \code{1}. The saturation sets are also shown for each node; all of
  5825. them start as the empty set. We do not show the register nodes in the
  5826. following graph because there were no interference edges involving
  5827. registers in this program; however, in general there can be inference
  5828. edges that involve registers.
  5829. %
  5830. \[
  5831. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5832. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5833. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5834. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5835. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5836. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5837. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5838. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5839. \draw (t0) to (t1);
  5840. \draw (t0) to (z);
  5841. \draw (z) to (y);
  5842. \draw (z) to (w);
  5843. \draw (x) to (w);
  5844. \draw (y) to (w);
  5845. \draw (v) to (w);
  5846. \end{tikzpicture}
  5847. \]
  5848. The algorithm says to select a maximally saturated vertex, but they
  5849. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5850. and then we color it with the first available integer, which is $0$. We mark
  5851. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5852. they interfere with $\ttm{tmp\_0}$.
  5853. \[
  5854. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5855. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5856. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5857. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5858. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5859. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5860. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5861. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5862. \draw (t0) to (t1);
  5863. \draw (t0) to (z);
  5864. \draw (z) to (y);
  5865. \draw (z) to (w);
  5866. \draw (x) to (w);
  5867. \draw (y) to (w);
  5868. \draw (v) to (w);
  5869. \end{tikzpicture}
  5870. \]
  5871. We repeat the process. The most saturated vertices are \code{z} and
  5872. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5873. available number, which is $1$. We add $1$ to the saturation for the
  5874. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5875. \[
  5876. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5877. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5878. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5879. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5880. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5881. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5882. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5883. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5884. \draw (t0) to (t1);
  5885. \draw (t0) to (z);
  5886. \draw (z) to (y);
  5887. \draw (z) to (w);
  5888. \draw (x) to (w);
  5889. \draw (y) to (w);
  5890. \draw (v) to (w);
  5891. \end{tikzpicture}
  5892. \]
  5893. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5894. \code{y}. We color \code{w} with the first available color, which
  5895. is $0$.
  5896. \[
  5897. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5898. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5899. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5900. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5901. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5902. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5903. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5904. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5905. \draw (t0) to (t1);
  5906. \draw (t0) to (z);
  5907. \draw (z) to (y);
  5908. \draw (z) to (w);
  5909. \draw (x) to (w);
  5910. \draw (y) to (w);
  5911. \draw (v) to (w);
  5912. \end{tikzpicture}
  5913. \]
  5914. Now \code{y} is the most saturated, so we color it with $2$.
  5915. \[
  5916. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5917. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5918. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5919. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5920. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5921. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5922. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5923. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5924. \draw (t0) to (t1);
  5925. \draw (t0) to (z);
  5926. \draw (z) to (y);
  5927. \draw (z) to (w);
  5928. \draw (x) to (w);
  5929. \draw (y) to (w);
  5930. \draw (v) to (w);
  5931. \end{tikzpicture}
  5932. \]
  5933. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5934. We choose to color \code{v} with $1$.
  5935. \[
  5936. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5937. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5938. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5939. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5940. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5941. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5942. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5943. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5944. \draw (t0) to (t1);
  5945. \draw (t0) to (z);
  5946. \draw (z) to (y);
  5947. \draw (z) to (w);
  5948. \draw (x) to (w);
  5949. \draw (y) to (w);
  5950. \draw (v) to (w);
  5951. \end{tikzpicture}
  5952. \]
  5953. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5954. \[
  5955. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5956. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5957. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5958. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5959. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5960. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5961. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5962. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5963. \draw (t0) to (t1);
  5964. \draw (t0) to (z);
  5965. \draw (z) to (y);
  5966. \draw (z) to (w);
  5967. \draw (x) to (w);
  5968. \draw (y) to (w);
  5969. \draw (v) to (w);
  5970. \end{tikzpicture}
  5971. \]
  5972. So, we obtain the following coloring:
  5973. \[
  5974. \{ \ttm{tmp\_0} \mapsto 0,
  5975. \ttm{tmp\_1} \mapsto 1,
  5976. \ttm{z} \mapsto 1,
  5977. \ttm{x} \mapsto 1,
  5978. \ttm{y} \mapsto 2,
  5979. \ttm{w} \mapsto 0,
  5980. \ttm{v} \mapsto 1 \}
  5981. \]
  5982. \fi}
  5983. We recommend creating an auxiliary function named \code{color\_graph}
  5984. that takes an interference graph and a list of all the variables in
  5985. the program. This function should return a mapping of variables to
  5986. their colors (represented as natural numbers). By creating this helper
  5987. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5988. when we add support for functions.
  5989. To prioritize the processing of highly saturated nodes inside the
  5990. \code{color\_graph} function, we recommend using the priority queue
  5991. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5992. addition, you will need to maintain a mapping from variables to their
  5993. handles in the priority queue so that you can notify the priority
  5994. queue when their saturation changes.}
  5995. {\if\edition\racketEd
  5996. \begin{figure}[tp]
  5997. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5998. \small
  5999. \begin{tcolorbox}[title=Priority Queue]
  6000. A \emph{priority queue}\index{subject}{priority queue}
  6001. is a collection of items in which the
  6002. removal of items is governed by priority. In a \emph{min} queue,
  6003. lower priority items are removed first. An implementation is in
  6004. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6005. \begin{description}
  6006. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6007. priority queue that uses the $\itm{cmp}$ predicate to determine
  6008. whether its first argument has lower or equal priority to its
  6009. second argument.
  6010. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6011. items in the queue.
  6012. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6013. the item into the queue and returns a handle for the item in the
  6014. queue.
  6015. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6016. the lowest priority.
  6017. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6018. notifies the queue that the priority has decreased for the item
  6019. associated with the given handle.
  6020. \end{description}
  6021. \end{tcolorbox}
  6022. %\end{wrapfigure}
  6023. \caption{The priority queue data structure.}
  6024. \label{fig:priority-queue}
  6025. \end{figure}
  6026. \fi}
  6027. With the coloring complete, we finalize the assignment of variables to
  6028. registers and stack locations. We map the first $k$ colors to the $k$
  6029. registers and the rest of the colors to stack locations. Suppose for
  6030. the moment that we have just one register to use for register
  6031. allocation, \key{rcx}. Then we have the following map from colors to
  6032. locations.
  6033. \[
  6034. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6035. \]
  6036. Composing this mapping with the coloring, we arrive at the following
  6037. assignment of variables to locations.
  6038. {\if\edition\racketEd
  6039. \begin{gather*}
  6040. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6041. \ttm{w} \mapsto \key{\%rcx}, \,
  6042. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6043. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6044. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6045. \ttm{t} \mapsto \key{\%rcx} \}
  6046. \end{gather*}
  6047. \fi}
  6048. {\if\edition\pythonEd\pythonColor
  6049. \begin{gather*}
  6050. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6051. \ttm{w} \mapsto \key{\%rcx}, \,
  6052. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6053. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6054. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6055. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6056. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6057. \end{gather*}
  6058. \fi}
  6059. Adapt the code from the \code{assign\_homes} pass
  6060. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6061. assigned location. Applying this assignment to our running
  6062. example shown next, on the left, yields the program on the right.
  6063. % why frame size of 32? -JGS
  6064. \begin{center}
  6065. {\if\edition\racketEd
  6066. \begin{minipage}{0.35\textwidth}
  6067. \begin{lstlisting}
  6068. movq $1, v
  6069. movq $42, w
  6070. movq v, x
  6071. addq $7, x
  6072. movq x, y
  6073. movq x, z
  6074. addq w, z
  6075. movq y, t
  6076. negq t
  6077. movq z, %rax
  6078. addq t, %rax
  6079. jmp conclusion
  6080. \end{lstlisting}
  6081. \end{minipage}
  6082. $\Rightarrow\qquad$
  6083. \begin{minipage}{0.45\textwidth}
  6084. \begin{lstlisting}
  6085. movq $1, -8(%rbp)
  6086. movq $42, %rcx
  6087. movq -8(%rbp), -8(%rbp)
  6088. addq $7, -8(%rbp)
  6089. movq -8(%rbp), -16(%rbp)
  6090. movq -8(%rbp), -8(%rbp)
  6091. addq %rcx, -8(%rbp)
  6092. movq -16(%rbp), %rcx
  6093. negq %rcx
  6094. movq -8(%rbp), %rax
  6095. addq %rcx, %rax
  6096. jmp conclusion
  6097. \end{lstlisting}
  6098. \end{minipage}
  6099. \fi}
  6100. {\if\edition\pythonEd\pythonColor
  6101. \begin{minipage}{0.35\textwidth}
  6102. \begin{lstlisting}
  6103. movq $1, v
  6104. movq $42, w
  6105. movq v, x
  6106. addq $7, x
  6107. movq x, y
  6108. movq x, z
  6109. addq w, z
  6110. movq y, tmp_0
  6111. negq tmp_0
  6112. movq z, tmp_1
  6113. addq tmp_0, tmp_1
  6114. movq tmp_1, %rdi
  6115. callq print_int
  6116. \end{lstlisting}
  6117. \end{minipage}
  6118. $\Rightarrow\qquad$
  6119. \begin{minipage}{0.45\textwidth}
  6120. \begin{lstlisting}
  6121. movq $1, -8(%rbp)
  6122. movq $42, %rcx
  6123. movq -8(%rbp), -8(%rbp)
  6124. addq $7, -8(%rbp)
  6125. movq -8(%rbp), -16(%rbp)
  6126. movq -8(%rbp), -8(%rbp)
  6127. addq %rcx, -8(%rbp)
  6128. movq -16(%rbp), %rcx
  6129. negq %rcx
  6130. movq -8(%rbp), -8(%rbp)
  6131. addq %rcx, -8(%rbp)
  6132. movq -8(%rbp), %rdi
  6133. callq print_int
  6134. \end{lstlisting}
  6135. \end{minipage}
  6136. \fi}
  6137. \end{center}
  6138. \begin{exercise}\normalfont\normalsize
  6139. Implement the \code{allocate\_registers} pass.
  6140. Create five programs that exercise all aspects of the register
  6141. allocation algorithm, including spilling variables to the stack.
  6142. %
  6143. {\if\edition\racketEd
  6144. Replace \code{assign\_homes} in the list of \code{passes} in the
  6145. \code{run-tests.rkt} script with the three new passes:
  6146. \code{uncover\_live}, \code{build\_interference}, and
  6147. \code{allocate\_registers}.
  6148. Temporarily remove the call to \code{compiler-tests}.
  6149. Run the script to test the register allocator.
  6150. \fi}
  6151. %
  6152. {\if\edition\pythonEd\pythonColor
  6153. Run the \code{run-tests.py} script to check whether the
  6154. output programs produce the same result as the input programs.
  6155. \fi}
  6156. \end{exercise}
  6157. \section{Patch Instructions}
  6158. \label{sec:patch-instructions}
  6159. The remaining step in the compilation to x86 is to ensure that the
  6160. instructions have at most one argument that is a memory access.
  6161. %
  6162. In the running example, the instruction \code{movq -8(\%rbp),
  6163. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6164. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6165. then move \code{rax} into \code{-16(\%rbp)}.
  6166. %
  6167. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6168. problematic, but they can simply be deleted. In general, we recommend
  6169. deleting all the trivial moves whose source and destination are the
  6170. same location.
  6171. %
  6172. The following is the output of \code{patch\_instructions} on the
  6173. running example.
  6174. \begin{center}
  6175. {\if\edition\racketEd
  6176. \begin{minipage}{0.35\textwidth}
  6177. \begin{lstlisting}
  6178. movq $1, -8(%rbp)
  6179. movq $42, %rcx
  6180. movq -8(%rbp), -8(%rbp)
  6181. addq $7, -8(%rbp)
  6182. movq -8(%rbp), -16(%rbp)
  6183. movq -8(%rbp), -8(%rbp)
  6184. addq %rcx, -8(%rbp)
  6185. movq -16(%rbp), %rcx
  6186. negq %rcx
  6187. movq -8(%rbp), %rax
  6188. addq %rcx, %rax
  6189. jmp conclusion
  6190. \end{lstlisting}
  6191. \end{minipage}
  6192. $\Rightarrow\qquad$
  6193. \begin{minipage}{0.45\textwidth}
  6194. \begin{lstlisting}
  6195. movq $1, -8(%rbp)
  6196. movq $42, %rcx
  6197. addq $7, -8(%rbp)
  6198. movq -8(%rbp), %rax
  6199. movq %rax, -16(%rbp)
  6200. addq %rcx, -8(%rbp)
  6201. movq -16(%rbp), %rcx
  6202. negq %rcx
  6203. movq -8(%rbp), %rax
  6204. addq %rcx, %rax
  6205. jmp conclusion
  6206. \end{lstlisting}
  6207. \end{minipage}
  6208. \fi}
  6209. {\if\edition\pythonEd\pythonColor
  6210. \begin{minipage}{0.35\textwidth}
  6211. \begin{lstlisting}
  6212. movq $1, -8(%rbp)
  6213. movq $42, %rcx
  6214. movq -8(%rbp), -8(%rbp)
  6215. addq $7, -8(%rbp)
  6216. movq -8(%rbp), -16(%rbp)
  6217. movq -8(%rbp), -8(%rbp)
  6218. addq %rcx, -8(%rbp)
  6219. movq -16(%rbp), %rcx
  6220. negq %rcx
  6221. movq -8(%rbp), -8(%rbp)
  6222. addq %rcx, -8(%rbp)
  6223. movq -8(%rbp), %rdi
  6224. callq print_int
  6225. \end{lstlisting}
  6226. \end{minipage}
  6227. $\Rightarrow\qquad$
  6228. \begin{minipage}{0.45\textwidth}
  6229. \begin{lstlisting}
  6230. movq $1, -8(%rbp)
  6231. movq $42, %rcx
  6232. addq $7, -8(%rbp)
  6233. movq -8(%rbp), %rax
  6234. movq %rax, -16(%rbp)
  6235. addq %rcx, -8(%rbp)
  6236. movq -16(%rbp), %rcx
  6237. negq %rcx
  6238. addq %rcx, -8(%rbp)
  6239. movq -8(%rbp), %rdi
  6240. callq print_int
  6241. \end{lstlisting}
  6242. \end{minipage}
  6243. \fi}
  6244. \end{center}
  6245. \begin{exercise}\normalfont\normalsize
  6246. %
  6247. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6248. %
  6249. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6250. %in the \code{run-tests.rkt} script.
  6251. %
  6252. Run the script to test the \code{patch\_instructions} pass.
  6253. \end{exercise}
  6254. \section{Prelude and Conclusion}
  6255. \label{sec:print-x86-reg-alloc}
  6256. \index{subject}{calling conventions}
  6257. \index{subject}{prelude}\index{subject}{conclusion}
  6258. Recall that this pass generates the prelude and conclusion
  6259. instructions to satisfy the x86 calling conventions
  6260. (section~\ref{sec:calling-conventions}). With the addition of the
  6261. register allocator, the callee-saved registers used by the register
  6262. allocator must be saved in the prelude and restored in the conclusion.
  6263. In the \code{allocate\_registers} pass,
  6264. %
  6265. \racket{add an entry to the \itm{info}
  6266. of \code{X86Program} named \code{used\_callee}}
  6267. %
  6268. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6269. %
  6270. that stores the set of callee-saved registers that were assigned to
  6271. variables. The \code{prelude\_and\_conclusion} pass can then access
  6272. this information to decide which callee-saved registers need to be
  6273. saved and restored.
  6274. %
  6275. When calculating the amount to adjust the \code{rsp} in the prelude,
  6276. make sure to take into account the space used for saving the
  6277. callee-saved registers. Also, remember that the frame needs to be a
  6278. multiple of 16 bytes! We recommend using the following equation for
  6279. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6280. of stack locations used by spilled variables\footnote{Sometimes two or
  6281. more spilled variables are assigned to the same stack location, so
  6282. $S$ can be less than the number of spilled variables.} and $C$ be
  6283. the number of callee-saved registers that were
  6284. allocated\index{subject}{allocate} to
  6285. variables. The $\itm{align}$ function rounds a number up to the
  6286. nearest 16 bytes.
  6287. \[
  6288. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6289. \]
  6290. The reason we subtract $8\itm{C}$ in this equation is that the
  6291. prelude uses \code{pushq} to save each of the callee-saved registers,
  6292. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6293. \racket{An overview of all the passes involved in register
  6294. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6295. {\if\edition\racketEd
  6296. \begin{figure}[tbp]
  6297. \begin{tcolorbox}[colback=white]
  6298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6299. \node (Lvar) at (0,2) {\large \LangVar{}};
  6300. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6301. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6302. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6303. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6304. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6305. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6306. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6307. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6308. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6309. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6310. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6311. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6312. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6313. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6314. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6315. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6316. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6317. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6318. \end{tikzpicture}
  6319. \end{tcolorbox}
  6320. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6321. \label{fig:reg-alloc-passes}
  6322. \end{figure}
  6323. \fi}
  6324. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6325. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6326. use of registers and the stack, we limit the register allocator for
  6327. this example to use just two registers: \code{rcx} (color $0$) and
  6328. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6329. \code{main} function, we push \code{rbx} onto the stack because it is
  6330. a callee-saved register and it was assigned to a variable by the
  6331. register allocator. We subtract \code{8} from the \code{rsp} at the
  6332. end of the prelude to reserve space for the one spilled variable.
  6333. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6334. Moving on to the program proper, we see how the registers were
  6335. allocated.
  6336. %
  6337. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6338. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6339. %
  6340. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6341. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6342. were assigned to \code{rbx}.}
  6343. %
  6344. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6345. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6346. callee-save register \code{rbx} onto the stack. The spilled variables
  6347. must be placed lower on the stack than the saved callee-save
  6348. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6349. \code{-16(\%rbp)}.
  6350. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6351. done in the prelude. We move the stack pointer up by \code{8} bytes
  6352. (the room for spilled variables), then pop the old values of
  6353. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6354. \code{retq} to return control to the operating system.
  6355. \begin{figure}[tbp]
  6356. \begin{minipage}{0.55\textwidth}
  6357. \begin{tcolorbox}[colback=white]
  6358. % var_test_28.rkt
  6359. % (use-minimal-set-of-registers! #t)
  6360. % 0 -> rcx
  6361. % 1 -> rbx
  6362. %
  6363. % t 0 rcx
  6364. % z 1 rbx
  6365. % w 0 rcx
  6366. % y 2 rbp -16
  6367. % v 1 rbx
  6368. % x 1 rbx
  6369. {\if\edition\racketEd
  6370. \begin{lstlisting}
  6371. start:
  6372. movq $1, %rbx
  6373. movq $42, %rcx
  6374. addq $7, %rbx
  6375. movq %rbx, -16(%rbp)
  6376. addq %rcx, %rbx
  6377. movq -16(%rbp), %rcx
  6378. negq %rcx
  6379. movq %rbx, %rax
  6380. addq %rcx, %rax
  6381. jmp conclusion
  6382. .globl main
  6383. main:
  6384. pushq %rbp
  6385. movq %rsp, %rbp
  6386. pushq %rbx
  6387. subq $8, %rsp
  6388. jmp start
  6389. conclusion:
  6390. addq $8, %rsp
  6391. popq %rbx
  6392. popq %rbp
  6393. retq
  6394. \end{lstlisting}
  6395. \fi}
  6396. {\if\edition\pythonEd\pythonColor
  6397. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6398. \begin{lstlisting}
  6399. .globl main
  6400. main:
  6401. pushq %rbp
  6402. movq %rsp, %rbp
  6403. pushq %rbx
  6404. subq $8, %rsp
  6405. movq $1, %rcx
  6406. movq $42, %rbx
  6407. addq $7, %rcx
  6408. movq %rcx, -16(%rbp)
  6409. addq %rbx, -16(%rbp)
  6410. negq %rcx
  6411. movq -16(%rbp), %rbx
  6412. addq %rcx, %rbx
  6413. movq %rbx, %rdi
  6414. callq print_int
  6415. addq $8, %rsp
  6416. popq %rbx
  6417. popq %rbp
  6418. retq
  6419. \end{lstlisting}
  6420. \fi}
  6421. \end{tcolorbox}
  6422. \end{minipage}
  6423. \caption{The x86 output from the running example
  6424. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6425. and \code{rcx}.}
  6426. \label{fig:running-example-x86}
  6427. \end{figure}
  6428. \begin{exercise}\normalfont\normalsize
  6429. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6430. %
  6431. \racket{
  6432. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6433. list of passes and the call to \code{compiler-tests}.}
  6434. %
  6435. Run the script to test the complete compiler for \LangVar{} that
  6436. performs register allocation.
  6437. \end{exercise}
  6438. \section{Challenge: Move Biasing}
  6439. \label{sec:move-biasing}
  6440. \index{subject}{move biasing}
  6441. This section describes an enhancement to the register allocator,
  6442. called move biasing, for students who are looking for an extra
  6443. challenge.
  6444. {\if\edition\racketEd
  6445. To motivate the need for move biasing we return to the running example,
  6446. but this time we use all the general purpose registers. So, we have
  6447. the following mapping of color numbers to registers.
  6448. \[
  6449. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6450. \]
  6451. Using the same assignment of variables to color numbers that was
  6452. produced by the register allocator described in the last section, we
  6453. get the following program.
  6454. \begin{center}
  6455. \begin{minipage}{0.35\textwidth}
  6456. \begin{lstlisting}
  6457. movq $1, v
  6458. movq $42, w
  6459. movq v, x
  6460. addq $7, x
  6461. movq x, y
  6462. movq x, z
  6463. addq w, z
  6464. movq y, t
  6465. negq t
  6466. movq z, %rax
  6467. addq t, %rax
  6468. jmp conclusion
  6469. \end{lstlisting}
  6470. \end{minipage}
  6471. $\Rightarrow\qquad$
  6472. \begin{minipage}{0.45\textwidth}
  6473. \begin{lstlisting}
  6474. movq $1, %rdx
  6475. movq $42, %rcx
  6476. movq %rdx, %rdx
  6477. addq $7, %rdx
  6478. movq %rdx, %rsi
  6479. movq %rdx, %rdx
  6480. addq %rcx, %rdx
  6481. movq %rsi, %rcx
  6482. negq %rcx
  6483. movq %rdx, %rax
  6484. addq %rcx, %rax
  6485. jmp conclusion
  6486. \end{lstlisting}
  6487. \end{minipage}
  6488. \end{center}
  6489. In this output code there are two \key{movq} instructions that
  6490. can be removed because their source and target are the same. However,
  6491. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6492. register, we could instead remove three \key{movq} instructions. We
  6493. can accomplish this by taking into account which variables appear in
  6494. \key{movq} instructions with which other variables.
  6495. \fi}
  6496. {\if\edition\pythonEd\pythonColor
  6497. %
  6498. To motivate the need for move biasing we return to the running example
  6499. and recall that in section~\ref{sec:patch-instructions} we were able to
  6500. remove three trivial move instructions from the running
  6501. example. However, we could remove another trivial move if we were able
  6502. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6503. We say that two variables $p$ and $q$ are \emph{move
  6504. related}\index{subject}{move related} if they participate together in
  6505. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6506. \key{movq} $q$\key{,} $p$.
  6507. %
  6508. Recall that we color variables that are more saturated before coloring
  6509. variables that are less saturated, and in the case of equally
  6510. saturated variables, we choose randomly. Now we break such ties by
  6511. giving preference to variables that have an available color that is
  6512. the same as the color of a move-related variable.
  6513. %
  6514. Furthermore, when the register allocator chooses a color for a
  6515. variable, it should prefer a color that has already been used for a
  6516. move-related variable if one exists (and assuming that they do not
  6517. interfere). This preference should not override the preference for
  6518. registers over stack locations. So, this preference should be used as
  6519. a tie breaker in choosing between two registers or in choosing between
  6520. two stack locations.
  6521. We recommend representing the move relationships in a graph, similarly
  6522. to how we represented interference. The following is the \emph{move
  6523. graph} for our running example.
  6524. {\if\edition\racketEd
  6525. \[
  6526. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6527. \node (rax) at (0,0) {$\ttm{rax}$};
  6528. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6529. \node (t) at (0,2) {$\ttm{t}$};
  6530. \node (z) at (3,2) {$\ttm{z}$};
  6531. \node (x) at (6,2) {$\ttm{x}$};
  6532. \node (y) at (3,0) {$\ttm{y}$};
  6533. \node (w) at (6,0) {$\ttm{w}$};
  6534. \node (v) at (9,0) {$\ttm{v}$};
  6535. \draw (v) to (x);
  6536. \draw (x) to (y);
  6537. \draw (x) to (z);
  6538. \draw (y) to (t);
  6539. \end{tikzpicture}
  6540. \]
  6541. \fi}
  6542. %
  6543. {\if\edition\pythonEd\pythonColor
  6544. \[
  6545. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6546. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6547. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6548. \node (z) at (3,2) {$\ttm{z}$};
  6549. \node (x) at (6,2) {$\ttm{x}$};
  6550. \node (y) at (3,0) {$\ttm{y}$};
  6551. \node (w) at (6,0) {$\ttm{w}$};
  6552. \node (v) at (9,0) {$\ttm{v}$};
  6553. \draw (y) to (t0);
  6554. \draw (z) to (x);
  6555. \draw (z) to (t1);
  6556. \draw (x) to (y);
  6557. \draw (x) to (v);
  6558. \end{tikzpicture}
  6559. \]
  6560. \fi}
  6561. {\if\edition\racketEd
  6562. Now we replay the graph coloring, pausing to see the coloring of
  6563. \code{y}. Recall the following configuration. The most saturated vertices
  6564. were \code{w} and \code{y}.
  6565. \[
  6566. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6567. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6568. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6569. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6570. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6571. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6572. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6573. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6574. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6575. \draw (t1) to (rax);
  6576. \draw (t1) to (z);
  6577. \draw (z) to (y);
  6578. \draw (z) to (w);
  6579. \draw (x) to (w);
  6580. \draw (y) to (w);
  6581. \draw (v) to (w);
  6582. \draw (v) to (rsp);
  6583. \draw (w) to (rsp);
  6584. \draw (x) to (rsp);
  6585. \draw (y) to (rsp);
  6586. \path[-.,bend left=15] (z) edge node {} (rsp);
  6587. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6588. \draw (rax) to (rsp);
  6589. \end{tikzpicture}
  6590. \]
  6591. %
  6592. The last time, we chose to color \code{w} with $0$. This time, we see
  6593. that \code{w} is not move-related to any vertex, but \code{y} is
  6594. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6595. the same color as \code{t}.
  6596. \[
  6597. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6598. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6599. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6600. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6601. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6602. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6603. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6604. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6605. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6606. \draw (t1) to (rax);
  6607. \draw (t1) to (z);
  6608. \draw (z) to (y);
  6609. \draw (z) to (w);
  6610. \draw (x) to (w);
  6611. \draw (y) to (w);
  6612. \draw (v) to (w);
  6613. \draw (v) to (rsp);
  6614. \draw (w) to (rsp);
  6615. \draw (x) to (rsp);
  6616. \draw (y) to (rsp);
  6617. \path[-.,bend left=15] (z) edge node {} (rsp);
  6618. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6619. \draw (rax) to (rsp);
  6620. \end{tikzpicture}
  6621. \]
  6622. Now \code{w} is the most saturated, so we color it $2$.
  6623. \[
  6624. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6625. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6626. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6627. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6628. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6629. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6630. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6631. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6632. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6633. \draw (t1) to (rax);
  6634. \draw (t1) to (z);
  6635. \draw (z) to (y);
  6636. \draw (z) to (w);
  6637. \draw (x) to (w);
  6638. \draw (y) to (w);
  6639. \draw (v) to (w);
  6640. \draw (v) to (rsp);
  6641. \draw (w) to (rsp);
  6642. \draw (x) to (rsp);
  6643. \draw (y) to (rsp);
  6644. \path[-.,bend left=15] (z) edge node {} (rsp);
  6645. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6646. \draw (rax) to (rsp);
  6647. \end{tikzpicture}
  6648. \]
  6649. At this point, vertices \code{x} and \code{v} are most saturated, but
  6650. \code{x} is move related to \code{y} and \code{z}, so we color
  6651. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6652. \[
  6653. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6654. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6655. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6656. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6657. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6658. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6659. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6660. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6661. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6662. \draw (t1) to (rax);
  6663. \draw (t) to (z);
  6664. \draw (z) to (y);
  6665. \draw (z) to (w);
  6666. \draw (x) to (w);
  6667. \draw (y) to (w);
  6668. \draw (v) to (w);
  6669. \draw (v) to (rsp);
  6670. \draw (w) to (rsp);
  6671. \draw (x) to (rsp);
  6672. \draw (y) to (rsp);
  6673. \path[-.,bend left=15] (z) edge node {} (rsp);
  6674. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6675. \draw (rax) to (rsp);
  6676. \end{tikzpicture}
  6677. \]
  6678. \fi}
  6679. %
  6680. {\if\edition\pythonEd\pythonColor
  6681. Now we replay the graph coloring, pausing before the coloring of
  6682. \code{w}. Recall the following configuration. The most saturated vertices
  6683. were \code{tmp\_1}, \code{w}, and \code{y}.
  6684. \[
  6685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6686. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6687. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6688. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6689. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6690. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6691. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6692. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6693. \draw (t0) to (t1);
  6694. \draw (t0) to (z);
  6695. \draw (z) to (y);
  6696. \draw (z) to (w);
  6697. \draw (x) to (w);
  6698. \draw (y) to (w);
  6699. \draw (v) to (w);
  6700. \end{tikzpicture}
  6701. \]
  6702. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6703. or \code{y}. Note, however, that \code{w} is not move related to any
  6704. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6705. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6706. \code{y} and color it $0$, we can delete another move instruction.
  6707. \[
  6708. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6709. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6710. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6711. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6712. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6713. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6714. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6715. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6716. \draw (t0) to (t1);
  6717. \draw (t0) to (z);
  6718. \draw (z) to (y);
  6719. \draw (z) to (w);
  6720. \draw (x) to (w);
  6721. \draw (y) to (w);
  6722. \draw (v) to (w);
  6723. \end{tikzpicture}
  6724. \]
  6725. Now \code{w} is the most saturated, so we color it $2$.
  6726. \[
  6727. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6728. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6729. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6730. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6731. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6732. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6733. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6734. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6735. \draw (t0) to (t1);
  6736. \draw (t0) to (z);
  6737. \draw (z) to (y);
  6738. \draw (z) to (w);
  6739. \draw (x) to (w);
  6740. \draw (y) to (w);
  6741. \draw (v) to (w);
  6742. \end{tikzpicture}
  6743. \]
  6744. To finish the coloring, \code{x} and \code{v} get $0$ and
  6745. \code{tmp\_1} gets $1$.
  6746. \[
  6747. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6748. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6749. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6750. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6751. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6752. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6753. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6754. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6755. \draw (t0) to (t1);
  6756. \draw (t0) to (z);
  6757. \draw (z) to (y);
  6758. \draw (z) to (w);
  6759. \draw (x) to (w);
  6760. \draw (y) to (w);
  6761. \draw (v) to (w);
  6762. \end{tikzpicture}
  6763. \]
  6764. \fi}
  6765. So, we have the following assignment of variables to registers.
  6766. {\if\edition\racketEd
  6767. \begin{gather*}
  6768. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6769. \ttm{w} \mapsto \key{\%rsi}, \,
  6770. \ttm{x} \mapsto \key{\%rcx}, \,
  6771. \ttm{y} \mapsto \key{\%rcx}, \,
  6772. \ttm{z} \mapsto \key{\%rdx}, \,
  6773. \ttm{t} \mapsto \key{\%rcx} \}
  6774. \end{gather*}
  6775. \fi}
  6776. {\if\edition\pythonEd\pythonColor
  6777. \begin{gather*}
  6778. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6779. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6780. \ttm{x} \mapsto \key{\%rcx}, \,
  6781. \ttm{y} \mapsto \key{\%rcx}, \\
  6782. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6783. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6784. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6785. \end{gather*}
  6786. \fi}
  6787. %
  6788. We apply this register assignment to the running example shown next,
  6789. on the left, to obtain the code in the middle. The
  6790. \code{patch\_instructions} then deletes the trivial moves to obtain
  6791. the code on the right.
  6792. {\if\edition\racketEd
  6793. \begin{center}
  6794. \begin{minipage}{0.2\textwidth}
  6795. \begin{lstlisting}
  6796. movq $1, v
  6797. movq $42, w
  6798. movq v, x
  6799. addq $7, x
  6800. movq x, y
  6801. movq x, z
  6802. addq w, z
  6803. movq y, t
  6804. negq t
  6805. movq z, %rax
  6806. addq t, %rax
  6807. jmp conclusion
  6808. \end{lstlisting}
  6809. \end{minipage}
  6810. $\Rightarrow\qquad$
  6811. \begin{minipage}{0.25\textwidth}
  6812. \begin{lstlisting}
  6813. movq $1, %rcx
  6814. movq $42, %rsi
  6815. movq %rcx, %rcx
  6816. addq $7, %rcx
  6817. movq %rcx, %rcx
  6818. movq %rcx, %rdx
  6819. addq %rsi, %rdx
  6820. movq %rcx, %rcx
  6821. negq %rcx
  6822. movq %rdx, %rax
  6823. addq %rcx, %rax
  6824. jmp conclusion
  6825. \end{lstlisting}
  6826. \end{minipage}
  6827. $\Rightarrow\qquad$
  6828. \begin{minipage}{0.23\textwidth}
  6829. \begin{lstlisting}
  6830. movq $1, %rcx
  6831. movq $42, %rsi
  6832. addq $7, %rcx
  6833. movq %rcx, %rdx
  6834. addq %rsi, %rdx
  6835. negq %rcx
  6836. movq %rdx, %rax
  6837. addq %rcx, %rax
  6838. jmp conclusion
  6839. \end{lstlisting}
  6840. \end{minipage}
  6841. \end{center}
  6842. \fi}
  6843. {\if\edition\pythonEd\pythonColor
  6844. \begin{center}
  6845. \begin{minipage}{0.20\textwidth}
  6846. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6847. movq $1, v
  6848. movq $42, w
  6849. movq v, x
  6850. addq $7, x
  6851. movq x, y
  6852. movq x, z
  6853. addq w, z
  6854. movq y, tmp_0
  6855. negq tmp_0
  6856. movq z, tmp_1
  6857. addq tmp_0, tmp_1
  6858. movq tmp_1, %rdi
  6859. callq _print_int
  6860. \end{lstlisting}
  6861. \end{minipage}
  6862. ${\Rightarrow\qquad}$
  6863. \begin{minipage}{0.35\textwidth}
  6864. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6865. movq $1, %rcx
  6866. movq $42, -16(%rbp)
  6867. movq %rcx, %rcx
  6868. addq $7, %rcx
  6869. movq %rcx, %rcx
  6870. movq %rcx, -8(%rbp)
  6871. addq -16(%rbp), -8(%rbp)
  6872. movq %rcx, %rcx
  6873. negq %rcx
  6874. movq -8(%rbp), -8(%rbp)
  6875. addq %rcx, -8(%rbp)
  6876. movq -8(%rbp), %rdi
  6877. callq _print_int
  6878. \end{lstlisting}
  6879. \end{minipage}
  6880. ${\Rightarrow\qquad}$
  6881. \begin{minipage}{0.20\textwidth}
  6882. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6883. movq $1, %rcx
  6884. movq $42, -16(%rbp)
  6885. addq $7, %rcx
  6886. movq %rcx, -8(%rbp)
  6887. movq -16(%rbp), %rax
  6888. addq %rax, -8(%rbp)
  6889. negq %rcx
  6890. addq %rcx, -8(%rbp)
  6891. movq -8(%rbp), %rdi
  6892. callq print_int
  6893. \end{lstlisting}
  6894. \end{minipage}
  6895. \end{center}
  6896. \fi}
  6897. \begin{exercise}\normalfont\normalsize
  6898. Change your implementation of \code{allocate\_registers} to take move
  6899. biasing into account. Create two new tests that include at least one
  6900. opportunity for move biasing, and visually inspect the output x86
  6901. programs to make sure that your move biasing is working properly. Make
  6902. sure that your compiler still passes all the tests.
  6903. \end{exercise}
  6904. %To do: another neat challenge would be to do
  6905. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6906. %% \subsection{Output of the Running Example}
  6907. %% \label{sec:reg-alloc-output}
  6908. % challenge: prioritize variables based on execution frequencies
  6909. % and the number of uses of a variable
  6910. % challenge: enhance the coloring algorithm using Chaitin's
  6911. % approach of prioritizing high-degree variables
  6912. % by removing low-degree variables (coloring them later)
  6913. % from the interference graph
  6914. \section{Further Reading}
  6915. \label{sec:register-allocation-further-reading}
  6916. Early register allocation algorithms were developed for Fortran
  6917. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6918. of graph coloring began in the late 1970s and early 1980s with the
  6919. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6920. algorithm is based on the following observation of
  6921. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6922. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6923. $v$ removed is also $k$ colorable. To see why, suppose that the
  6924. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6925. different colors, but because there are fewer than $k$ neighbors, there
  6926. will be one or more colors left over to use for coloring $v$ in $G$.
  6927. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6928. less than $k$ from the graph and recursively colors the rest of the
  6929. graph. Upon returning from the recursion, it colors $v$ with one of
  6930. the available colors and returns. \citet{Chaitin:1982vn} augments
  6931. this algorithm to handle spilling as follows. If there are no vertices
  6932. of degree lower than $k$ then pick a vertex at random, spill it,
  6933. remove it from the graph, and proceed recursively to color the rest of
  6934. the graph.
  6935. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6936. move-related and that don't interfere with each other, in a process
  6937. called \emph{coalescing}. Although coalescing decreases the number of
  6938. moves, it can make the graph more difficult to
  6939. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6940. which two variables are merged only if they have fewer than $k$
  6941. neighbors of high degree. \citet{George:1996aa} observes that
  6942. conservative coalescing is sometimes too conservative and made it more
  6943. aggressive by iterating the coalescing with the removal of low-degree
  6944. vertices.
  6945. %
  6946. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6947. also proposed \emph{biased coloring}, in which a variable is assigned to
  6948. the same color as another move-related variable if possible, as
  6949. discussed in section~\ref{sec:move-biasing}.
  6950. %
  6951. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6952. performs coalescing, graph coloring, and spill code insertion until
  6953. all variables have been assigned a location.
  6954. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6955. spilled variables that don't have to be: a high-degree variable can be
  6956. colorable if many of its neighbors are assigned the same color.
  6957. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6958. high-degree vertex is not immediately spilled. Instead the decision is
  6959. deferred until after the recursive call, when it is apparent whether
  6960. there is an available color or not. We observe that this algorithm is
  6961. equivalent to the smallest-last ordering
  6962. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6963. be registers and the rest to be stack locations.
  6964. %% biased coloring
  6965. Earlier editions of the compiler course at Indiana University
  6966. \citep{Dybvig:2010aa} were based on the algorithm of
  6967. \citet{Briggs:1994kx}.
  6968. The smallest-last ordering algorithm is one of many \emph{greedy}
  6969. coloring algorithms. A greedy coloring algorithm visits all the
  6970. vertices in a particular order and assigns each one the first
  6971. available color. An \emph{offline} greedy algorithm chooses the
  6972. ordering up front, prior to assigning colors. The algorithm of
  6973. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6974. ordering does not depend on the colors assigned. Other orderings are
  6975. possible. For example, \citet{Chow:1984ys} ordered variables according
  6976. to an estimate of runtime cost.
  6977. An \emph{online} greedy coloring algorithm uses information about the
  6978. current assignment of colors to influence the order in which the
  6979. remaining vertices are colored. The saturation-based algorithm
  6980. described in this chapter is one such algorithm. We choose to use
  6981. saturation-based coloring because it is fun to introduce graph
  6982. coloring via sudoku!
  6983. A register allocator may choose to map each variable to just one
  6984. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6985. variable to one or more locations. The latter can be achieved by
  6986. \emph{live range splitting}, where a variable is replaced by several
  6987. variables that each handle part of its live
  6988. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6989. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6990. %% replacement algorithm, bottom-up local
  6991. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6992. %% Cooper: top-down (priority bassed), bottom-up
  6993. %% top-down
  6994. %% order variables by priority (estimated cost)
  6995. %% caveat: split variables into two groups:
  6996. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6997. %% color the constrained ones first
  6998. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6999. %% cite J. Cocke for an algorithm that colors variables
  7000. %% in a high-degree first ordering
  7001. %Register Allocation via Usage Counts, Freiburghouse CACM
  7002. \citet{Palsberg:2007si} observes that many of the interference graphs
  7003. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7004. that is, every cycle with four or more edges has an edge that is not
  7005. part of the cycle but that connects two vertices on the cycle. Such
  7006. graphs can be optimally colored by the greedy algorithm with a vertex
  7007. ordering determined by maximum cardinality search.
  7008. In situations in which compile time is of utmost importance, such as
  7009. in just-in-time compilers, graph coloring algorithms can be too
  7010. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7011. be more appropriate.
  7012. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7013. {\if\edition\racketEd
  7014. \addtocontents{toc}{\newpage}
  7015. \fi}
  7016. \chapter{Booleans and Conditionals}
  7017. \label{ch:Lif}
  7018. \setcounter{footnote}{0}
  7019. The \LangVar{} language has only a single kind of value, the
  7020. integers. In this chapter we add a second kind of value, the Booleans,
  7021. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7022. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7023. are written
  7024. \TRUE{}\index{subject}{True@\TRUE{}} and
  7025. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7026. language includes several operations that involve Booleans
  7027. (\key{and}\index{subject}{and@\ANDNAME{}},
  7028. \key{or}\index{subject}{or@\ORNAME{}},
  7029. \key{not}\index{subject}{not@\NOTNAME{}},
  7030. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7031. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7032. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7033. conditional expression\index{subject}{conditional expression}
  7034. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7035. With the addition of \key{if}, programs can have
  7036. nontrivial control flow\index{subject}{control flow}, which
  7037. %
  7038. \racket{impacts \code{explicate\_control} and liveness analysis.}
  7039. %
  7040. \python{impacts liveness analysis and motivates a new pass named
  7041. \code{explicate\_control}.}
  7042. %
  7043. Also, because we now have two kinds of values, we need to handle
  7044. programs that apply an operation to the wrong kind of value, such as
  7045. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7046. There are two language design options for such situations. One option
  7047. is to signal an error and the other is to provide a wider
  7048. interpretation of the operation. \racket{The Racket
  7049. language}\python{Python} uses a mixture of these two options,
  7050. depending on the operation and the kind of value. For example, the
  7051. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7052. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7053. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7054. %
  7055. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7056. in Racket because \code{car} expects a pair.}
  7057. %
  7058. \python{On the other hand, \code{1[0]} results in a runtime error
  7059. in Python because an ``\code{int} object is not subscriptable.''}
  7060. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7061. design choices as \racket{Racket}\python{Python}, except that much of the
  7062. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7063. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7064. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7065. \python{MyPy} reports a compile-time error
  7066. %
  7067. \racket{because Racket expects the type of the argument to be of the form
  7068. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7069. %
  7070. \python{stating that a ``value of type \code{int} is not indexable.''}
  7071. The \LangIf{} language performs type checking during compilation just as
  7072. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7073. the alternative choice, that is, a dynamically typed language like
  7074. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7075. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7076. restrictive, for example, rejecting \racket{\code{(not
  7077. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7078. fairly simple because the focus of this book is on compilation and not
  7079. type systems, about which there are already several excellent
  7080. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7081. This chapter is organized as follows. We begin by defining the syntax
  7082. and interpreter for the \LangIf{} language
  7083. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7084. checking (aka semantic analysis\index{subject}{semantic analysis})
  7085. and define a type checker for \LangIf{}
  7086. (section~\ref{sec:type-check-Lif}).
  7087. %
  7088. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7089. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7090. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7091. %
  7092. The remaining sections of this chapter discuss how Booleans and
  7093. conditional control flow require changes to the existing compiler
  7094. passes and the addition of new ones. We introduce the \code{shrink}
  7095. pass to translate some operators into others, thereby reducing the
  7096. number of operators that need to be handled in later passes.
  7097. %
  7098. The main event of this chapter is the \code{explicate\_control} pass
  7099. that is responsible for translating \code{if}s into conditional
  7100. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7101. %
  7102. Regarding register allocation, there is the interesting question of
  7103. how to handle conditional \code{goto}s during liveness analysis.
  7104. \section{The \LangIf{} Language}
  7105. \label{sec:lang-if}
  7106. Definitions of the concrete syntax and abstract syntax of the
  7107. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7108. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7109. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7110. literals\index{subject}{literals}
  7111. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7112. \python{, and the \code{if} statement}. We expand the set of
  7113. operators to include
  7114. \begin{enumerate}
  7115. \item the logical operators \key{and}, \key{or}, and \key{not},
  7116. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7117. for comparing integers or Booleans for equality, and
  7118. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7119. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7120. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7121. comparing integers.
  7122. \end{enumerate}
  7123. \racket{We reorganize the abstract syntax for the primitive
  7124. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7125. rule for all of them. This means that the grammar no longer checks
  7126. whether the arity of an operator matches the number of
  7127. arguments. That responsibility is moved to the type checker for
  7128. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7129. \newcommand{\LifGrammarRacket}{
  7130. \begin{array}{lcl}
  7131. \Type &::=& \key{Boolean} \\
  7132. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7133. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7134. \Exp &::=& \itm{bool}
  7135. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7136. \MID (\key{not}\;\Exp) \\
  7137. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7138. \end{array}
  7139. }
  7140. \newcommand{\LifASTRacket}{
  7141. \begin{array}{lcl}
  7142. \Type &::=& \key{Boolean} \\
  7143. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7144. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7145. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7146. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7147. \end{array}
  7148. }
  7149. \newcommand{\LintOpAST}{
  7150. \begin{array}{rcl}
  7151. \Type &::=& \key{Integer} \\
  7152. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7153. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7154. \end{array}
  7155. }
  7156. \newcommand{\LifGrammarPython}{
  7157. \begin{array}{rcl}
  7158. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7159. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7160. \MID \key{not}~\Exp \\
  7161. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7162. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7163. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7164. \end{array}
  7165. }
  7166. \newcommand{\LifASTPython}{
  7167. \begin{array}{lcl}
  7168. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7169. \itm{unaryop} &::=& \code{Not()} \\
  7170. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7171. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7172. \Exp &::=& \BOOL{\itm{bool}}
  7173. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7174. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7175. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7176. \end{array}
  7177. }
  7178. \begin{figure}[tp]
  7179. \centering
  7180. \begin{tcolorbox}[colback=white]
  7181. {\if\edition\racketEd
  7182. \[
  7183. \begin{array}{l}
  7184. \gray{\LintGrammarRacket{}} \\ \hline
  7185. \gray{\LvarGrammarRacket{}} \\ \hline
  7186. \LifGrammarRacket{} \\
  7187. \begin{array}{lcl}
  7188. \LangIfM{} &::=& \Exp
  7189. \end{array}
  7190. \end{array}
  7191. \]
  7192. \fi}
  7193. {\if\edition\pythonEd\pythonColor
  7194. \[
  7195. \begin{array}{l}
  7196. \gray{\LintGrammarPython} \\ \hline
  7197. \gray{\LvarGrammarPython} \\ \hline
  7198. \LifGrammarPython \\
  7199. \begin{array}{rcl}
  7200. \LangIfM{} &::=& \Stmt^{*}
  7201. \end{array}
  7202. \end{array}
  7203. \]
  7204. \fi}
  7205. \end{tcolorbox}
  7206. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7207. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7208. \label{fig:Lif-concrete-syntax}
  7209. \end{figure}
  7210. \begin{figure}[tp]
  7211. %\begin{minipage}{0.66\textwidth}
  7212. \begin{tcolorbox}[colback=white]
  7213. \centering
  7214. {\if\edition\racketEd
  7215. \[
  7216. \begin{array}{l}
  7217. \gray{\LintOpAST} \\ \hline
  7218. \gray{\LvarASTRacket{}} \\ \hline
  7219. \LifASTRacket{} \\
  7220. \begin{array}{lcl}
  7221. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7222. \end{array}
  7223. \end{array}
  7224. \]
  7225. \fi}
  7226. {\if\edition\pythonEd\pythonColor
  7227. \[
  7228. \begin{array}{l}
  7229. \gray{\LintASTPython} \\ \hline
  7230. \gray{\LvarASTPython} \\ \hline
  7231. \LifASTPython \\
  7232. \begin{array}{lcl}
  7233. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7234. \end{array}
  7235. \end{array}
  7236. \]
  7237. \fi}
  7238. \end{tcolorbox}
  7239. %\end{minipage}
  7240. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7241. \python{
  7242. \index{subject}{BoolOp@\texttt{BoolOp}}
  7243. \index{subject}{Compare@\texttt{Compare}}
  7244. \index{subject}{Lt@\texttt{Lt}}
  7245. \index{subject}{LtE@\texttt{LtE}}
  7246. \index{subject}{Gt@\texttt{Gt}}
  7247. \index{subject}{GtE@\texttt{GtE}}
  7248. }
  7249. \caption{The abstract syntax of \LangIf{}.}
  7250. \label{fig:Lif-syntax}
  7251. \end{figure}
  7252. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7253. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7254. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7255. evaluate to the corresponding Boolean values. The conditional
  7256. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7257. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7258. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7259. \code{or}, and \code{not} behave according to propositional logic. In
  7260. addition, the \code{and} and \code{or} operations perform
  7261. \emph{short-circuit evaluation}.
  7262. %
  7263. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7264. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7265. %
  7266. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7267. evaluated if $e_1$ evaluates to \TRUE{}.
  7268. \racket{With the increase in the number of primitive operations, the
  7269. interpreter would become repetitive without some care. We refactor
  7270. the case for \code{Prim}, moving the code that differs with each
  7271. operation into the \code{interp\_op} method shown in
  7272. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7273. \code{or} operations separately because of their short-circuiting
  7274. behavior.}
  7275. \begin{figure}[tbp]
  7276. \begin{tcolorbox}[colback=white]
  7277. {\if\edition\racketEd
  7278. \begin{lstlisting}
  7279. (define interp-Lif-class
  7280. (class interp-Lvar-class
  7281. (super-new)
  7282. (define/public (interp_op op) ...)
  7283. (define/override ((interp_exp env) e)
  7284. (define recur (interp_exp env))
  7285. (match e
  7286. [(Bool b) b]
  7287. [(If cnd thn els)
  7288. (match (recur cnd)
  7289. [#t (recur thn)]
  7290. [#f (recur els)])]
  7291. [(Prim 'and (list e1 e2))
  7292. (match (recur e1)
  7293. [#t (match (recur e2) [#t #t] [#f #f])]
  7294. [#f #f])]
  7295. [(Prim 'or (list e1 e2))
  7296. (define v1 (recur e1))
  7297. (match v1
  7298. [#t #t]
  7299. [#f (match (recur e2) [#t #t] [#f #f])])]
  7300. [(Prim op args)
  7301. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7302. [else ((super interp_exp env) e)]))
  7303. ))
  7304. (define (interp_Lif p)
  7305. (send (new interp-Lif-class) interp_program p))
  7306. \end{lstlisting}
  7307. \fi}
  7308. {\if\edition\pythonEd\pythonColor
  7309. \begin{lstlisting}
  7310. class InterpLif(InterpLvar):
  7311. def interp_exp(self, e, env):
  7312. match e:
  7313. case IfExp(test, body, orelse):
  7314. if self.interp_exp(test, env):
  7315. return self.interp_exp(body, env)
  7316. else:
  7317. return self.interp_exp(orelse, env)
  7318. case UnaryOp(Not(), v):
  7319. return not self.interp_exp(v, env)
  7320. case BoolOp(And(), values):
  7321. if self.interp_exp(values[0], env):
  7322. return self.interp_exp(values[1], env)
  7323. else:
  7324. return False
  7325. case BoolOp(Or(), values):
  7326. if self.interp_exp(values[0], env):
  7327. return True
  7328. else:
  7329. return self.interp_exp(values[1], env)
  7330. case Compare(left, [cmp], [right]):
  7331. l = self.interp_exp(left, env)
  7332. r = self.interp_exp(right, env)
  7333. return self.interp_cmp(cmp)(l, r)
  7334. case _:
  7335. return super().interp_exp(e, env)
  7336. def interp_stmt(self, s, env, cont):
  7337. match s:
  7338. case If(test, body, orelse):
  7339. match self.interp_exp(test, env):
  7340. case True:
  7341. return self.interp_stmts(body + cont, env)
  7342. case False:
  7343. return self.interp_stmts(orelse + cont, env)
  7344. case _:
  7345. return super().interp_stmt(s, env, cont)
  7346. ...
  7347. \end{lstlisting}
  7348. \fi}
  7349. \end{tcolorbox}
  7350. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7351. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7352. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7353. \label{fig:interp-Lif}
  7354. \end{figure}
  7355. {\if\edition\racketEd
  7356. \begin{figure}[tbp]
  7357. \begin{tcolorbox}[colback=white]
  7358. \begin{lstlisting}
  7359. (define/public (interp_op op)
  7360. (match op
  7361. ['+ fx+]
  7362. ['- fx-]
  7363. ['read read-fixnum]
  7364. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7365. ['eq? (lambda (v1 v2)
  7366. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7367. (and (boolean? v1) (boolean? v2))
  7368. (and (vector? v1) (vector? v2)))
  7369. (eq? v1 v2)]))]
  7370. ['< (lambda (v1 v2)
  7371. (cond [(and (fixnum? v1) (fixnum? v2))
  7372. (< v1 v2)]))]
  7373. ['<= (lambda (v1 v2)
  7374. (cond [(and (fixnum? v1) (fixnum? v2))
  7375. (<= v1 v2)]))]
  7376. ['> (lambda (v1 v2)
  7377. (cond [(and (fixnum? v1) (fixnum? v2))
  7378. (> v1 v2)]))]
  7379. ['>= (lambda (v1 v2)
  7380. (cond [(and (fixnum? v1) (fixnum? v2))
  7381. (>= v1 v2)]))]
  7382. [else (error 'interp_op "unknown operator")]))
  7383. \end{lstlisting}
  7384. \end{tcolorbox}
  7385. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7386. \label{fig:interp-op-Lif}
  7387. \end{figure}
  7388. \fi}
  7389. {\if\edition\pythonEd\pythonColor
  7390. \begin{figure}
  7391. \begin{tcolorbox}[colback=white]
  7392. \begin{lstlisting}
  7393. class InterpLif(InterpLvar):
  7394. ...
  7395. def interp_cmp(self, cmp):
  7396. match cmp:
  7397. case Lt():
  7398. return lambda x, y: x < y
  7399. case LtE():
  7400. return lambda x, y: x <= y
  7401. case Gt():
  7402. return lambda x, y: x > y
  7403. case GtE():
  7404. return lambda x, y: x >= y
  7405. case Eq():
  7406. return lambda x, y: x == y
  7407. case NotEq():
  7408. return lambda x, y: x != y
  7409. \end{lstlisting}
  7410. \end{tcolorbox}
  7411. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7412. \label{fig:interp-cmp-Lif}
  7413. \end{figure}
  7414. \fi}
  7415. \section{Type Checking \LangIf{} Programs}
  7416. \label{sec:type-check-Lif}
  7417. It is helpful to think about type checking\index{subject}{type
  7418. checking} in two complementary ways. A type checker predicts the
  7419. type of value that will be produced by each expression in the program.
  7420. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7421. type checker should predict that {\if\edition\racketEd
  7422. \begin{lstlisting}
  7423. (+ 10 (- (+ 12 20)))
  7424. \end{lstlisting}
  7425. \fi}
  7426. {\if\edition\pythonEd\pythonColor
  7427. \begin{lstlisting}
  7428. 10 + -(12 + 20)
  7429. \end{lstlisting}
  7430. \fi}
  7431. \noindent produces a value of type \INTTY{}, whereas
  7432. {\if\edition\racketEd
  7433. \begin{lstlisting}
  7434. (and (not #f) #t)
  7435. \end{lstlisting}
  7436. \fi}
  7437. {\if\edition\pythonEd\pythonColor
  7438. \begin{lstlisting}
  7439. (not False) and True
  7440. \end{lstlisting}
  7441. \fi}
  7442. \noindent produces a value of type \BOOLTY{}.
  7443. A second way to think about type checking is that it enforces a set of
  7444. rules about which operators can be applied to which kinds of
  7445. values. For example, our type checker for \LangIf{} signals an error
  7446. for the following expression:
  7447. %
  7448. {\if\edition\racketEd
  7449. \begin{lstlisting}
  7450. (not (+ 10 (- (+ 12 20))))
  7451. \end{lstlisting}
  7452. \fi}
  7453. {\if\edition\pythonEd\pythonColor
  7454. \begin{lstlisting}
  7455. not (10 + -(12 + 20))
  7456. \end{lstlisting}
  7457. \fi}
  7458. \noindent The subexpression
  7459. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7460. \python{\code{(10 + -(12 + 20))}}
  7461. has type \INTTY{}, but the type checker enforces the rule that the
  7462. argument of \code{not} must be an expression of type \BOOLTY{}.
  7463. We implement type checking using classes and methods because they
  7464. provide the open recursion needed to reuse code as we extend the type
  7465. checker in subsequent chapters, analogous to the use of classes and methods
  7466. for the interpreters (section~\ref{sec:extensible-interp}).
  7467. We separate the type checker for the \LangVar{} subset into its own
  7468. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7469. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7470. from the type checker for \LangVar{}. These type checkers are in the
  7471. files
  7472. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7473. and
  7474. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7475. of the support code.
  7476. %
  7477. Each type checker is a structurally recursive function over the AST.
  7478. Given an input expression \code{e}, the type checker either signals an
  7479. error or returns \racket{an expression and} its type.
  7480. %
  7481. \racket{It returns an expression because there are situations in which
  7482. we want to change or update the expression.}
  7483. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7484. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7485. constant is \INTTY{}. To handle variables, the type checker uses the
  7486. environment \code{env} to map variables to types.
  7487. %
  7488. \racket{Consider the case for \key{let}. We type check the
  7489. initializing expression to obtain its type \key{T} and then
  7490. associate type \code{T} with the variable \code{x} in the
  7491. environment used to type check the body of the \key{let}. Thus,
  7492. when the type checker encounters a use of variable \code{x}, it can
  7493. find its type in the environment.}
  7494. %
  7495. \python{Consider the case for assignment. We type check the
  7496. initializing expression to obtain its type \key{t}. If the variable
  7497. \code{lhs.id} is already in the environment because there was a
  7498. prior assignment, we check that this initializer has the same type
  7499. as the prior one. If this is the first assignment to the variable,
  7500. we associate type \code{t} with the variable \code{lhs.id} in the
  7501. environment. Thus, when the type checker encounters a use of
  7502. variable \code{x}, it can find its type in the environment.}
  7503. %
  7504. \racket{Regarding primitive operators, we recursively analyze the
  7505. arguments and then invoke \code{type\_check\_op} to check whether
  7506. the argument types are allowed.}
  7507. %
  7508. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7509. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7510. \racket{Several auxiliary methods are used in the type checker. The
  7511. method \code{operator-types} defines a dictionary that maps the
  7512. operator names to their parameter and return types. The
  7513. \code{type-equal?} method determines whether two types are equal,
  7514. which for now simply dispatches to \code{equal?} (deep
  7515. equality). The \code{check-type-equal?} method triggers an error if
  7516. the two types are not equal. The \code{type-check-op} method looks
  7517. up the operator in the \code{operator-types} dictionary and then
  7518. checks whether the argument types are equal to the parameter types.
  7519. The result is the return type of the operator.}
  7520. %
  7521. \python{The auxiliary method \code{check\_type\_equal} triggers
  7522. an error if the two types are not equal.}
  7523. \begin{figure}[tbp]
  7524. \begin{tcolorbox}[colback=white]
  7525. {\if\edition\racketEd
  7526. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7527. (define type-check-Lvar-class
  7528. (class object%
  7529. (super-new)
  7530. (define/public (operator-types)
  7531. '((+ . ((Integer Integer) . Integer))
  7532. (- . ((Integer Integer) . Integer))
  7533. (read . (() . Integer))))
  7534. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7535. (define/public (check-type-equal? t1 t2 e)
  7536. (unless (type-equal? t1 t2)
  7537. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7538. (define/public (type-check-op op arg-types e)
  7539. (match (dict-ref (operator-types) op)
  7540. [`(,param-types . ,return-type)
  7541. (for ([at arg-types] [pt param-types])
  7542. (check-type-equal? at pt e))
  7543. return-type]
  7544. [else (error 'type-check-op "unrecognized ~a" op)]))
  7545. (define/public (type-check-exp env)
  7546. (lambda (e)
  7547. (match e
  7548. [(Int n) (values (Int n) 'Integer)]
  7549. [(Var x) (values (Var x) (dict-ref env x))]
  7550. [(Let x e body)
  7551. (define-values (e^ Te) ((type-check-exp env) e))
  7552. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7553. (values (Let x e^ b) Tb)]
  7554. [(Prim op es)
  7555. (define-values (new-es ts)
  7556. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7557. (values (Prim op new-es) (type-check-op op ts e))]
  7558. [else (error 'type-check-exp "couldn't match" e)])))
  7559. (define/public (type-check-program e)
  7560. (match e
  7561. [(Program info body)
  7562. (define-values (body^ Tb) ((type-check-exp '()) body))
  7563. (check-type-equal? Tb 'Integer body)
  7564. (Program info body^)]
  7565. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7566. ))
  7567. (define (type-check-Lvar p)
  7568. (send (new type-check-Lvar-class) type-check-program p))
  7569. \end{lstlisting}
  7570. \fi}
  7571. {\if\edition\pythonEd\pythonColor
  7572. \begin{lstlisting}[escapechar=`]
  7573. class TypeCheckLvar:
  7574. def check_type_equal(self, t1, t2, e):
  7575. if t1 != t2:
  7576. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7577. raise Exception(msg)
  7578. def type_check_exp(self, e, env):
  7579. match e:
  7580. case BinOp(left, (Add() | Sub()), right):
  7581. l = self.type_check_exp(left, env)
  7582. check_type_equal(l, int, left)
  7583. r = self.type_check_exp(right, env)
  7584. check_type_equal(r, int, right)
  7585. return int
  7586. case UnaryOp(USub(), v):
  7587. t = self.type_check_exp(v, env)
  7588. check_type_equal(t, int, v)
  7589. return int
  7590. case Name(id):
  7591. return env[id]
  7592. case Constant(value) if isinstance(value, int):
  7593. return int
  7594. case Call(Name('input_int'), []):
  7595. return int
  7596. def type_check_stmts(self, ss, env):
  7597. if len(ss) == 0:
  7598. return
  7599. match ss[0]:
  7600. case Assign([lhs], value):
  7601. t = self.type_check_exp(value, env)
  7602. if lhs.id in env:
  7603. check_type_equal(env[lhs.id], t, value)
  7604. else:
  7605. env[lhs.id] = t
  7606. return self.type_check_stmts(ss[1:], env)
  7607. case Expr(Call(Name('print'), [arg])):
  7608. t = self.type_check_exp(arg, env)
  7609. check_type_equal(t, int, arg)
  7610. return self.type_check_stmts(ss[1:], env)
  7611. case Expr(value):
  7612. self.type_check_exp(value, env)
  7613. return self.type_check_stmts(ss[1:], env)
  7614. def type_check_P(self, p):
  7615. match p:
  7616. case Module(body):
  7617. self.type_check_stmts(body, {})
  7618. \end{lstlisting}
  7619. \fi}
  7620. \end{tcolorbox}
  7621. \caption{Type checker for the \LangVar{} language.}
  7622. \label{fig:type-check-Lvar}
  7623. \end{figure}
  7624. \begin{figure}[tbp]
  7625. \begin{tcolorbox}[colback=white]
  7626. {\if\edition\racketEd
  7627. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7628. (define type-check-Lif-class
  7629. (class type-check-Lvar-class
  7630. (super-new)
  7631. (inherit check-type-equal?)
  7632. (define/override (operator-types)
  7633. (append '((and . ((Boolean Boolean) . Boolean))
  7634. (or . ((Boolean Boolean) . Boolean))
  7635. (< . ((Integer Integer) . Boolean))
  7636. (<= . ((Integer Integer) . Boolean))
  7637. (> . ((Integer Integer) . Boolean))
  7638. (>= . ((Integer Integer) . Boolean))
  7639. (not . ((Boolean) . Boolean)))
  7640. (super operator-types)))
  7641. (define/override (type-check-exp env)
  7642. (lambda (e)
  7643. (match e
  7644. [(Bool b) (values (Bool b) 'Boolean)]
  7645. [(Prim 'eq? (list e1 e2))
  7646. (define-values (e1^ T1) ((type-check-exp env) e1))
  7647. (define-values (e2^ T2) ((type-check-exp env) e2))
  7648. (check-type-equal? T1 T2 e)
  7649. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7650. [(If cnd thn els)
  7651. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7652. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7653. (define-values (els^ Te) ((type-check-exp env) els))
  7654. (check-type-equal? Tc 'Boolean e)
  7655. (check-type-equal? Tt Te e)
  7656. (values (If cnd^ thn^ els^) Te)]
  7657. [else ((super type-check-exp env) e)])))
  7658. ))
  7659. (define (type-check-Lif p)
  7660. (send (new type-check-Lif-class) type-check-program p))
  7661. \end{lstlisting}
  7662. \fi}
  7663. {\if\edition\pythonEd\pythonColor
  7664. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7665. class TypeCheckLif(TypeCheckLvar):
  7666. def type_check_exp(self, e, env):
  7667. match e:
  7668. case Constant(value) if isinstance(value, bool):
  7669. return bool
  7670. case BinOp(left, Sub(), right):
  7671. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7672. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7673. return int
  7674. case UnaryOp(Not(), v):
  7675. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7676. return bool
  7677. case BoolOp(op, values):
  7678. left = values[0] ; right = values[1]
  7679. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7680. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7681. return bool
  7682. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7683. or isinstance(cmp, NotEq):
  7684. l = self.type_check_exp(left, env)
  7685. r = self.type_check_exp(right, env)
  7686. check_type_equal(l, r, e)
  7687. return bool
  7688. case Compare(left, [cmp], [right]):
  7689. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7690. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7691. return bool
  7692. case IfExp(test, body, orelse):
  7693. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7694. b = self.type_check_exp(body, env)
  7695. o = self.type_check_exp(orelse, env)
  7696. check_type_equal(b, o, e)
  7697. return b
  7698. case _:
  7699. return super().type_check_exp(e, env)
  7700. def type_check_stmts(self, ss, env):
  7701. if len(ss) == 0:
  7702. return
  7703. match ss[0]:
  7704. case If(test, body, orelse):
  7705. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7706. b = self.type_check_stmts(body, env)
  7707. o = self.type_check_stmts(orelse, env)
  7708. check_type_equal(b, o, ss[0])
  7709. return self.type_check_stmts(ss[1:], env)
  7710. case _:
  7711. return super().type_check_stmts(ss, env)
  7712. \end{lstlisting}
  7713. \fi}
  7714. \end{tcolorbox}
  7715. \caption{Type checker for the \LangIf{} language.}
  7716. \label{fig:type-check-Lif}
  7717. \end{figure}
  7718. The definition of the type checker for \LangIf{} is shown in
  7719. figure~\ref{fig:type-check-Lif}.
  7720. %
  7721. The type of a Boolean constant is \BOOLTY{}.
  7722. %
  7723. \racket{The \code{operator-types} function adds dictionary entries for
  7724. the new operators.}
  7725. %
  7726. \python{The logical \code{not} operator requires its argument to be a
  7727. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7728. and logical \code{or} operators.}
  7729. %
  7730. The equality operator requires the two arguments to have the same type,
  7731. and therefore we handle it separately from the other operators.
  7732. %
  7733. \python{The other comparisons (less-than, etc.) require their
  7734. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7735. %
  7736. The condition of an \code{if} must
  7737. be of \BOOLTY{} type, and the two branches must have the same type.
  7738. \begin{exercise}\normalfont\normalsize
  7739. Create ten new test programs in \LangIf{}. Half the programs should
  7740. have a type error. For those programs, create an empty file with the
  7741. same base name and with file extension \code{.tyerr}. For example, if
  7742. the test
  7743. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7744. is expected to error, then create
  7745. an empty file named \code{cond\_test\_14.tyerr}.
  7746. %
  7747. \racket{This indicates to \code{interp-tests} and
  7748. \code{compiler-tests} that a type error is expected. }
  7749. %
  7750. The other half of the test programs should not have type errors.
  7751. %
  7752. \racket{In the \code{run-tests.rkt} script, change the second argument
  7753. of \code{interp-tests} and \code{compiler-tests} to
  7754. \code{type-check-Lif}, which causes the type checker to run prior to
  7755. the compiler passes. Temporarily change the \code{passes} to an
  7756. empty list and run the script, thereby checking that the new test
  7757. programs either type check or do not, as intended.}
  7758. %
  7759. Run the test script to check that these test programs type check as
  7760. expected.
  7761. \end{exercise}
  7762. \clearpage
  7763. \section{The \LangCIf{} Intermediate Language}
  7764. \label{sec:Cif}
  7765. {\if\edition\racketEd
  7766. %
  7767. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7768. comparison operators to the \Exp{} nonterminal and the literals
  7769. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7770. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7771. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7772. comparison operation and the branches are \code{goto} statements,
  7773. making it straightforward to compile \code{if} statements to x86. The
  7774. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7775. expressions. A \code{goto} statement transfers control to the $\Tail$
  7776. expression corresponding to its label.
  7777. %
  7778. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7779. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7780. defines its abstract syntax.
  7781. %
  7782. \fi}
  7783. %
  7784. {\if\edition\pythonEd\pythonColor
  7785. %
  7786. The output of \key{explicate\_control} is a language similar to the
  7787. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7788. \code{goto} statements, so we name it \LangCIf{}.
  7789. %
  7790. The \LangCIf{} language supports the same operators as \LangIf{} but
  7791. the arguments of operators are restricted to atomic expressions. The
  7792. \LangCIf{} language does not include \code{if} expressions, but it does
  7793. include a restricted form of \code{if} statement. The condition must be
  7794. a comparison, and the two branches may contain only \code{goto}
  7795. statements. These restrictions make it easier to translate \code{if}
  7796. statements to x86. The \LangCIf{} language also adds a \code{return}
  7797. statement to finish the program with a specified value.
  7798. %
  7799. The \key{CProgram} construct contains a dictionary mapping labels to
  7800. lists of statements that end with a \emph{tail} statement, which is
  7801. either a \code{return} statement, a \code{goto}, or an
  7802. \code{if} statement.
  7803. %
  7804. A \code{goto} transfers control to the sequence of statements
  7805. associated with its label.
  7806. %
  7807. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7808. and figure~\ref{fig:c1-syntax} shows its
  7809. abstract syntax.
  7810. %
  7811. \fi}
  7812. %
  7813. \newcommand{\CifGrammarRacket}{
  7814. \begin{array}{lcl}
  7815. \Atm &::=& \itm{bool} \\
  7816. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7817. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7818. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7819. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7820. \end{array}
  7821. }
  7822. \newcommand{\CifASTRacket}{
  7823. \begin{array}{lcl}
  7824. \Atm &::=& \BOOL{\itm{bool}} \\
  7825. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7826. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7827. \Tail &::= & \GOTO{\itm{label}} \\
  7828. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7829. \end{array}
  7830. }
  7831. \newcommand{\CifGrammarPython}{
  7832. \begin{array}{lcl}
  7833. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7834. \Exp &::= & \Atm \MID \CREAD{}
  7835. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7836. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7837. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7838. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7839. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7840. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7841. \end{array}
  7842. }
  7843. \newcommand{\CifASTPython}{
  7844. \begin{array}{lcl}
  7845. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7846. \Exp &::= & \Atm \MID \READ{} \\
  7847. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7848. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7849. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7850. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7851. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7852. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7853. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7854. \end{array}
  7855. }
  7856. \begin{figure}[tbp]
  7857. \begin{tcolorbox}[colback=white]
  7858. \small
  7859. {\if\edition\racketEd
  7860. \[
  7861. \begin{array}{l}
  7862. \gray{\CvarGrammarRacket} \\ \hline
  7863. \CifGrammarRacket \\
  7864. \begin{array}{lcl}
  7865. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7866. \end{array}
  7867. \end{array}
  7868. \]
  7869. \fi}
  7870. {\if\edition\pythonEd\pythonColor
  7871. \[
  7872. \begin{array}{l}
  7873. \CifGrammarPython \\
  7874. \begin{array}{lcl}
  7875. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7876. \end{array}
  7877. \end{array}
  7878. \]
  7879. \fi}
  7880. \end{tcolorbox}
  7881. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7882. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7883. \label{fig:c1-concrete-syntax}
  7884. \end{figure}
  7885. \begin{figure}[tp]
  7886. \begin{tcolorbox}[colback=white]
  7887. \small
  7888. {\if\edition\racketEd
  7889. \[
  7890. \begin{array}{l}
  7891. \gray{\CvarASTRacket} \\ \hline
  7892. \CifASTRacket \\
  7893. \begin{array}{lcl}
  7894. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7895. \end{array}
  7896. \end{array}
  7897. \]
  7898. \fi}
  7899. {\if\edition\pythonEd\pythonColor
  7900. \[
  7901. \begin{array}{l}
  7902. \CifASTPython \\
  7903. \begin{array}{lcl}
  7904. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7905. \end{array}
  7906. \end{array}
  7907. \]
  7908. \fi}
  7909. \end{tcolorbox}
  7910. \racket{
  7911. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7912. }
  7913. \index{subject}{Goto@\texttt{Goto}}
  7914. \index{subject}{Return@\texttt{Return}}
  7915. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7916. (figure~\ref{fig:c0-syntax})}.}
  7917. \label{fig:c1-syntax}
  7918. \end{figure}
  7919. \section{The \LangXIf{} Language}
  7920. \label{sec:x86-if}
  7921. \index{subject}{x86}
  7922. To implement Booleans, the new logical operations, the
  7923. comparison operations, and the \key{if} expression\python{ and
  7924. statement}, we delve further into the x86
  7925. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7926. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7927. subset of x86, which includes instructions for logical operations,
  7928. comparisons, and \racket{conditional} jumps.
  7929. %
  7930. \python{The abstract syntax for an \LangXIf{} program contains a
  7931. dictionary mapping labels to sequences of instructions, each of
  7932. which we refer to as a \emph{basic block}\index{subject}{basic
  7933. block}.}
  7934. As x86 does not provide direct support for Booleans, we take the usual
  7935. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7936. \code{False} as $0$.
  7937. Furthermore, x86 does not provide an instruction that directly
  7938. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7939. However, the \code{xorq} instruction can be used to encode \code{not}.
  7940. The \key{xorq} instruction takes two arguments, performs a pairwise
  7941. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7942. and writes the results into its second argument. Recall the following
  7943. truth table for exclusive-or:
  7944. \begin{center}
  7945. \begin{tabular}{l|cc}
  7946. & 0 & 1 \\ \hline
  7947. 0 & 0 & 1 \\
  7948. 1 & 1 & 0
  7949. \end{tabular}
  7950. \end{center}
  7951. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7952. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7953. for the bit $1$, the result is the opposite of the second bit. Thus,
  7954. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7955. the first argument, as follows, where $\Arg$ is the translation of
  7956. $\Atm$ to x86:
  7957. \[
  7958. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7959. \qquad\Rightarrow\qquad
  7960. \begin{array}{l}
  7961. \key{movq}~ \Arg\key{,} \Var\\
  7962. \key{xorq}~ \key{\$1,} \Var
  7963. \end{array}
  7964. \]
  7965. \newcommand{\GrammarXIf}{
  7966. \begin{array}{lcl}
  7967. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7968. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7969. \Arg &::=& \key{\%}\itm{bytereg}\\
  7970. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7971. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7972. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7973. \MID \key{set}cc~\Arg
  7974. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7975. &\MID& \key{j}cc~\itm{label} \\
  7976. \end{array}
  7977. }
  7978. \begin{figure}[tp]
  7979. \begin{tcolorbox}[colback=white]
  7980. \[
  7981. \begin{array}{l}
  7982. \gray{\GrammarXInt} \\ \hline
  7983. \GrammarXIf \\
  7984. \begin{array}{lcl}
  7985. \LangXIfM{} &::= & \key{.globl main} \\
  7986. & & \key{main:} \; \Instr\ldots
  7987. \end{array}
  7988. \end{array}
  7989. \]
  7990. \end{tcolorbox}
  7991. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7992. \label{fig:x86-1-concrete}
  7993. \end{figure}
  7994. \newcommand{\ASTXIfRacket}{
  7995. \begin{array}{lcl}
  7996. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7997. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7998. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7999. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8000. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8001. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8002. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8003. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8004. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8005. \end{array}
  8006. }
  8007. \newcommand{\ASTXIfPython}{
  8008. \begin{array}{lcl}
  8009. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8010. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8011. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8012. \MID \BYTEREG{\itm{bytereg}} \\
  8013. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8014. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8015. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8016. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8017. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8018. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8019. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8020. \end{array}
  8021. }
  8022. \begin{figure}[tp]
  8023. \begin{tcolorbox}[colback=white]
  8024. \small
  8025. {\if\edition\racketEd
  8026. \[\arraycolsep=3pt
  8027. \begin{array}{l}
  8028. \gray{\ASTXIntRacket} \\ \hline
  8029. \ASTXIfRacket \\
  8030. \begin{array}{lcl}
  8031. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8032. \end{array}
  8033. \end{array}
  8034. \]
  8035. \fi}
  8036. %
  8037. {\if\edition\pythonEd\pythonColor
  8038. \[
  8039. \begin{array}{l}
  8040. \gray{\ASTXIntPython} \\ \hline
  8041. \ASTXIfPython \\
  8042. \begin{array}{lcl}
  8043. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8044. \end{array}
  8045. \end{array}
  8046. \]
  8047. \fi}
  8048. \end{tcolorbox}
  8049. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8050. \label{fig:x86-1}
  8051. \end{figure}
  8052. Next we consider the x86 instructions that are relevant for compiling
  8053. the comparison operations. The \key{cmpq} instruction compares its two
  8054. arguments to determine whether one argument is less than, equal to, or
  8055. greater than the other argument. The \key{cmpq} instruction is unusual
  8056. regarding the order of its arguments and where the result is
  8057. placed. The argument order is backward: if you want to test whether
  8058. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8059. \key{cmpq} is placed in the special EFLAGS register. This register
  8060. cannot be accessed directly, but it can be queried by a number of
  8061. instructions, including the \key{set} instruction. The instruction
  8062. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8063. depending on whether the contents of the EFLAGS register matches the
  8064. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8065. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8066. The \key{set} instruction has a quirk in that its destination argument
  8067. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8068. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8069. register. Thankfully, the \key{movzbq} instruction can be used to
  8070. move from a single-byte register to a normal 64-bit register. The
  8071. abstract syntax for the \code{set} instruction differs from the
  8072. concrete syntax in that it separates the instruction name from the
  8073. condition code.
  8074. \python{The x86 instructions for jumping are relevant to the
  8075. compilation of \key{if} expressions.}
  8076. %
  8077. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8078. counter to the address of the instruction after the specified
  8079. label.}
  8080. %
  8081. \racket{The x86 instruction for conditional jump is relevant to the
  8082. compilation of \key{if} expressions.}
  8083. %
  8084. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8085. counter to point to the instruction after \itm{label}, depending on
  8086. whether the result in the EFLAGS register matches the condition code
  8087. \itm{cc}; otherwise, the jump instruction falls through to the next
  8088. instruction. Like the abstract syntax for \code{set}, the abstract
  8089. syntax for conditional jump separates the instruction name from the
  8090. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8091. corresponds to \code{jle foo}. Because the conditional jump instruction
  8092. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8093. a \key{cmpq} instruction to set the EFLAGS register.
  8094. \section{Shrink the \LangIf{} Language}
  8095. \label{sec:shrink-Lif}
  8096. The \code{shrink} pass translates some of the language features into
  8097. other features, thereby reducing the kinds of expressions in the
  8098. language. For example, the short-circuiting nature of the \code{and}
  8099. and \code{or} logical operators can be expressed using \code{if} as
  8100. follows.
  8101. \begin{align*}
  8102. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8103. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8104. \end{align*}
  8105. By performing these translations in the front end of the compiler,
  8106. subsequent passes of the compiler can be shorter.
  8107. On the other hand, translations sometimes reduce the efficiency of the
  8108. generated code by increasing the number of instructions. For example,
  8109. expressing subtraction in terms of addition and negation
  8110. \[
  8111. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8112. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8113. \]
  8114. produces code with two x86 instructions (\code{negq} and \code{addq})
  8115. instead of just one (\code{subq}). Thus, we do not recommend
  8116. translating subtraction into addition and negation.
  8117. \begin{exercise}\normalfont\normalsize
  8118. %
  8119. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8120. the language by translating them to \code{if} expressions in \LangIf{}.
  8121. %
  8122. Create four test programs that involve these operators.
  8123. %
  8124. {\if\edition\racketEd
  8125. In the \code{run-tests.rkt} script, add the following entry for
  8126. \code{shrink} to the list of passes (it should be the only pass at
  8127. this point).
  8128. \begin{lstlisting}
  8129. (list "shrink" shrink interp_Lif type-check-Lif)
  8130. \end{lstlisting}
  8131. This instructs \code{interp-tests} to run the interpreter
  8132. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8133. output of \code{shrink}.
  8134. \fi}
  8135. %
  8136. Run the script to test your compiler on all the test programs.
  8137. \end{exercise}
  8138. {\if\edition\racketEd
  8139. \section{Uniquify Variables}
  8140. \label{sec:uniquify-Lif}
  8141. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8142. \code{if} expressions.
  8143. \begin{exercise}\normalfont\normalsize
  8144. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8145. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8146. \begin{lstlisting}
  8147. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8148. \end{lstlisting}
  8149. Run the script to test your compiler.
  8150. \end{exercise}
  8151. \fi}
  8152. \section{Remove Complex Operands}
  8153. \label{sec:remove-complex-opera-Lif}
  8154. The output language of \code{remove\_complex\_operands} is
  8155. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8156. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8157. but the \code{if} expression is not. All three subexpressions of an
  8158. \code{if} are allowed to be complex expressions, but the operands of
  8159. the \code{not} operator and comparison operators must be atomic.
  8160. %
  8161. \python{We add a new language form, the \code{Begin} expression, to aid
  8162. in the translation of \code{if} expressions. When we recursively
  8163. process the two branches of the \code{if}, we generate temporary
  8164. variables and their initializing expressions. However, these
  8165. expressions may contain side effects and should be executed only
  8166. when the condition of the \code{if} is true (for the ``then''
  8167. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8168. a way to initialize the temporary variables within the two branches
  8169. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8170. form executes the statements $ss$ and then returns the result of
  8171. expression $e$.}
  8172. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8173. the new features in \LangIf{}. In recursively processing
  8174. subexpressions, recall that you should invoke \code{rco\_atom} when
  8175. the output needs to be an \Atm{} (as specified in the grammar for
  8176. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8177. \Exp{}. Regarding \code{if}, it is particularly important
  8178. \emph{not} to replace its condition with a temporary variable, because
  8179. that would interfere with the generation of high-quality output in the
  8180. upcoming \code{explicate\_control} pass.
  8181. \newcommand{\LifMonadASTRacket}{
  8182. \begin{array}{rcl}
  8183. \Atm &::=& \BOOL{\itm{bool}}\\
  8184. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8185. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8186. \MID \IF{\Exp}{\Exp}{\Exp}
  8187. \end{array}
  8188. }
  8189. \newcommand{\LifMonadASTPython}{
  8190. \begin{array}{rcl}
  8191. \Atm &::=& \BOOL{\itm{bool}}\\
  8192. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8193. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8194. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8195. \end{array}
  8196. }
  8197. \begin{figure}[tp]
  8198. \centering
  8199. \begin{tcolorbox}[colback=white]
  8200. {\if\edition\racketEd
  8201. \[
  8202. \begin{array}{l}
  8203. \gray{\LvarMonadASTRacket} \\ \hline
  8204. \LifMonadASTRacket \\
  8205. \begin{array}{rcl}
  8206. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8207. \end{array}
  8208. \end{array}
  8209. \]
  8210. \fi}
  8211. {\if\edition\pythonEd\pythonColor
  8212. \[
  8213. \begin{array}{l}
  8214. \gray{\LvarMonadASTPython} \\ \hline
  8215. \LifMonadASTPython \\
  8216. \begin{array}{rcl}
  8217. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8218. \end{array}
  8219. \end{array}
  8220. \]
  8221. \fi}
  8222. \end{tcolorbox}
  8223. \python{\index{subject}{Begin@\texttt{Begin}}}
  8224. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8225. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8226. \label{fig:Lif-anf-syntax}
  8227. \end{figure}
  8228. \begin{exercise}\normalfont\normalsize
  8229. %
  8230. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8231. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8232. %
  8233. Create three new \LangIf{} programs that exercise the interesting
  8234. code in this pass.
  8235. %
  8236. {\if\edition\racketEd
  8237. In the \code{run-tests.rkt} script, add the following entry to the
  8238. list of \code{passes} and then run the script to test your compiler.
  8239. \begin{lstlisting}
  8240. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8241. \end{lstlisting}
  8242. \fi}
  8243. \end{exercise}
  8244. \section{Explicate Control}
  8245. \label{sec:explicate-control-Lif}
  8246. \racket{Recall that the purpose of \code{explicate\_control} is to
  8247. make the order of evaluation explicit in the syntax of the program.
  8248. With the addition of \key{if}, this becomes more interesting.}
  8249. %
  8250. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8251. %
  8252. The main challenge to overcome is that the condition of an \key{if}
  8253. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8254. condition must be a comparison.
  8255. As a motivating example, consider the following program that has an
  8256. \key{if} expression nested in the condition of another \key{if}:%
  8257. \python{\footnote{Programmers rarely write nested \code{if}
  8258. expressions, but they do write nested expressions involving
  8259. logical \code{and}, which, as we have seen, translates to
  8260. \code{if}.}}
  8261. % cond_test_41.rkt, if_lt_eq.py
  8262. \begin{center}
  8263. \begin{minipage}{0.96\textwidth}
  8264. {\if\edition\racketEd
  8265. \begin{lstlisting}
  8266. (let ([x (read)])
  8267. (let ([y (read)])
  8268. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8269. (+ y 2)
  8270. (+ y 10))))
  8271. \end{lstlisting}
  8272. \fi}
  8273. {\if\edition\pythonEd\pythonColor
  8274. \begin{lstlisting}
  8275. x = input_int()
  8276. y = input_int()
  8277. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8278. \end{lstlisting}
  8279. \fi}
  8280. \end{minipage}
  8281. \end{center}
  8282. %
  8283. The naive way to compile \key{if} and the comparison operations would
  8284. be to handle each of them in isolation, regardless of their context.
  8285. Each comparison would be translated into a \key{cmpq} instruction
  8286. followed by several instructions to move the result from the EFLAGS
  8287. register into a general purpose register or stack location. Each
  8288. \key{if} would be translated into a \key{cmpq} instruction followed by
  8289. a conditional jump. The generated code for the inner \key{if} in this
  8290. example would be as follows:
  8291. \begin{center}
  8292. \begin{minipage}{0.96\textwidth}
  8293. \begin{lstlisting}
  8294. cmpq $1, x
  8295. setl %al
  8296. movzbq %al, tmp
  8297. cmpq $1, tmp
  8298. je then_branch_1
  8299. jmp else_branch_1
  8300. \end{lstlisting}
  8301. \end{minipage}
  8302. \end{center}
  8303. Notice that the three instructions starting with \code{setl} are
  8304. redundant; the conditional jump could come immediately after the first
  8305. \code{cmpq}.
  8306. Our goal is to compile \key{if} expressions so that the relevant
  8307. comparison instruction appears directly before the conditional jump.
  8308. For example, we want to generate the following code for the inner
  8309. \code{if}:
  8310. \begin{center}
  8311. \begin{minipage}{0.96\textwidth}
  8312. \begin{lstlisting}
  8313. cmpq $1, x
  8314. jl then_branch_1
  8315. jmp else_branch_1
  8316. \end{lstlisting}
  8317. \end{minipage}
  8318. \end{center}
  8319. One way to achieve this goal is to reorganize the code at the level of
  8320. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8321. the following code:
  8322. \begin{center}
  8323. \begin{minipage}{0.96\textwidth}
  8324. {\if\edition\racketEd
  8325. \begin{lstlisting}
  8326. (let ([x (read)])
  8327. (let ([y (read)])
  8328. (if (< x 1)
  8329. (if (eq? x 0)
  8330. (+ y 2)
  8331. (+ y 10))
  8332. (if (eq? x 2)
  8333. (+ y 2)
  8334. (+ y 10)))))
  8335. \end{lstlisting}
  8336. \fi}
  8337. {\if\edition\pythonEd\pythonColor
  8338. \begin{lstlisting}
  8339. x = input_int()
  8340. y = input_int()
  8341. print(((y + 2) if x == 0 else (y + 10)) \
  8342. if (x < 1) \
  8343. else ((y + 2) if (x == 2) else (y + 10)))
  8344. \end{lstlisting}
  8345. \fi}
  8346. \end{minipage}
  8347. \end{center}
  8348. Unfortunately, this approach duplicates the two branches from the
  8349. outer \code{if}, and a compiler must never duplicate code! After all,
  8350. the two branches could be very large expressions.
  8351. How can we apply this transformation without duplicating code? In
  8352. other words, how can two different parts of a program refer to one
  8353. piece of code?
  8354. %
  8355. The answer is that we must move away from abstract syntax \emph{trees}
  8356. and instead use \emph{graphs}.
  8357. %
  8358. At the level of x86 assembly, this is straightforward because we can
  8359. label the code for each branch and insert jumps in all the places that
  8360. need to execute the branch. In this way, jump instructions are edges
  8361. in the graph and the basic blocks are the nodes.
  8362. %
  8363. Likewise, our language \LangCIf{} provides the ability to label a
  8364. sequence of statements and to jump to a label via \code{goto}.
  8365. As a preview of what \code{explicate\_control} will do,
  8366. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8367. \code{explicate\_control} on this example. Note how the condition of
  8368. every \code{if} is a comparison operation and that we have not
  8369. duplicated any code but instead have used labels and \code{goto} to
  8370. enable sharing of code.
  8371. \begin{figure}[tbp]
  8372. \begin{tcolorbox}[colback=white]
  8373. {\if\edition\racketEd
  8374. \begin{tabular}{lll}
  8375. \begin{minipage}{0.4\textwidth}
  8376. % cond_test_41.rkt
  8377. \begin{lstlisting}
  8378. (let ([x (read)])
  8379. (let ([y (read)])
  8380. (if (if (< x 1)
  8381. (eq? x 0)
  8382. (eq? x 2))
  8383. (+ y 2)
  8384. (+ y 10))))
  8385. \end{lstlisting}
  8386. \end{minipage}
  8387. &
  8388. $\Rightarrow$
  8389. &
  8390. \begin{minipage}{0.55\textwidth}
  8391. \begin{lstlisting}
  8392. start:
  8393. x = (read);
  8394. y = (read);
  8395. if (< x 1)
  8396. goto block_4;
  8397. else
  8398. goto block_5;
  8399. block_4:
  8400. if (eq? x 0)
  8401. goto block_2;
  8402. else
  8403. goto block_3;
  8404. block_5:
  8405. if (eq? x 2)
  8406. goto block_2;
  8407. else
  8408. goto block_3;
  8409. block_2:
  8410. return (+ y 2);
  8411. block_3:
  8412. return (+ y 10);
  8413. \end{lstlisting}
  8414. \end{minipage}
  8415. \end{tabular}
  8416. \fi}
  8417. {\if\edition\pythonEd\pythonColor
  8418. \begin{tabular}{lll}
  8419. \begin{minipage}{0.4\textwidth}
  8420. % cond_test_41.rkt
  8421. \begin{lstlisting}
  8422. x = input_int()
  8423. y = input_int()
  8424. print(y + 2 \
  8425. if (x == 0 \
  8426. if x < 1 \
  8427. else x == 2) \
  8428. else y + 10)
  8429. \end{lstlisting}
  8430. \end{minipage}
  8431. &
  8432. $\Rightarrow$
  8433. &
  8434. \begin{minipage}{0.55\textwidth}
  8435. \begin{lstlisting}
  8436. start:
  8437. x = input_int()
  8438. y = input_int()
  8439. if x < 1:
  8440. goto block_8
  8441. else:
  8442. goto block_9
  8443. block_8:
  8444. if x == 0:
  8445. goto block_4
  8446. else:
  8447. goto block_5
  8448. block_9:
  8449. if x == 2:
  8450. goto block_6
  8451. else:
  8452. goto block_7
  8453. block_4:
  8454. goto block_2
  8455. block_5:
  8456. goto block_3
  8457. block_6:
  8458. goto block_2
  8459. block_7:
  8460. goto block_3
  8461. block_2:
  8462. tmp_0 = y + 2
  8463. goto block_1
  8464. block_3:
  8465. tmp_0 = y + 10
  8466. goto block_1
  8467. block_1:
  8468. print(tmp_0)
  8469. return 0
  8470. \end{lstlisting}
  8471. \end{minipage}
  8472. \end{tabular}
  8473. \fi}
  8474. \end{tcolorbox}
  8475. \caption{Translation from \LangIf{} to \LangCIf{}
  8476. via the \code{explicate\_control}.}
  8477. \label{fig:explicate-control-s1-38}
  8478. \end{figure}
  8479. {\if\edition\racketEd
  8480. %
  8481. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8482. \code{explicate\_control} for \LangVar{} using two recursive
  8483. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8484. former function translates expressions in tail position, whereas the
  8485. latter function translates expressions on the right-hand side of a
  8486. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8487. have a new kind of position to deal with: the predicate position of
  8488. the \key{if}. We need another function, \code{explicate\_pred}, that
  8489. decides how to compile an \key{if} by analyzing its condition. So,
  8490. \code{explicate\_pred} takes an \LangIf{} expression and two
  8491. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8492. and outputs a tail. In the following paragraphs we discuss specific
  8493. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8494. \code{explicate\_pred} functions.
  8495. %
  8496. \fi}
  8497. %
  8498. {\if\edition\pythonEd\pythonColor
  8499. %
  8500. We recommend implementing \code{explicate\_control} using the
  8501. following four auxiliary functions.
  8502. \begin{description}
  8503. \item[\code{explicate\_effect}] generates code for expressions as
  8504. statements, so their result is ignored and only their side effects
  8505. matter.
  8506. \item[\code{explicate\_assign}] generates code for expressions
  8507. on the right-hand side of an assignment.
  8508. \item[\code{explicate\_pred}] generates code for an \code{if}
  8509. expression or statement by analyzing the condition expression.
  8510. \item[\code{explicate\_stmt}] generates code for statements.
  8511. \end{description}
  8512. These four functions should build the dictionary of basic blocks. The
  8513. following auxiliary function can be used to create a new basic block
  8514. from a list of statements. It returns a \code{goto} statement that
  8515. jumps to the new basic block.
  8516. \begin{center}
  8517. \begin{minipage}{\textwidth}
  8518. \begin{lstlisting}
  8519. def create_block(stmts, basic_blocks):
  8520. label = label_name(generate_name('block'))
  8521. basic_blocks[label] = stmts
  8522. return [Goto(label)]
  8523. \end{lstlisting}
  8524. \end{minipage}
  8525. \end{center}
  8526. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8527. \code{explicate\_control} pass.
  8528. The \code{explicate\_effect} function has three parameters: (1) the
  8529. expression to be compiled; (2) the already-compiled code for this
  8530. expression's \emph{continuation}, that is, the list of statements that
  8531. should execute after this expression; and (3) the dictionary of
  8532. generated basic blocks. The \code{explicate\_effect} function returns
  8533. a list of \LangCIf{} statements and it may add to the dictionary of
  8534. basic blocks.
  8535. %
  8536. Let's consider a few of the cases for the expression to be compiled.
  8537. If the expression to be compiled is a constant, then it can be
  8538. discarded because it has no side effects. If it's a \CREAD{}, then it
  8539. has a side effect and should be preserved. So the expression should be
  8540. translated into a statement using the \code{Expr} AST class. If the
  8541. expression to be compiled is an \code{if} expression, we translate the
  8542. two branches using \code{explicate\_effect} and then translate the
  8543. condition expression using \code{explicate\_pred}, which generates
  8544. code for the entire \code{if}.
  8545. The \code{explicate\_assign} function has four parameters: (1) the
  8546. right-hand side of the assignment, (2) the left-hand side of the
  8547. assignment (the variable), (3) the continuation, and (4) the dictionary
  8548. of basic blocks. The \code{explicate\_assign} function returns a list
  8549. of \LangCIf{} statements, and it may add to the dictionary of basic
  8550. blocks.
  8551. When the right-hand side is an \code{if} expression, there is some
  8552. work to do. In particular, the two branches should be translated using
  8553. \code{explicate\_assign} and the condition expression should be
  8554. translated using \code{explicate\_pred}. Otherwise we can simply
  8555. generate an assignment statement, with the given left and right-hand
  8556. sides, concatenated with its continuation.
  8557. \begin{figure}[tbp]
  8558. \begin{tcolorbox}[colback=white]
  8559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8560. def explicate_effect(e, cont, basic_blocks):
  8561. match e:
  8562. case IfExp(test, body, orelse):
  8563. ...
  8564. case Call(func, args):
  8565. ...
  8566. case Begin(body, result):
  8567. ...
  8568. case _:
  8569. ...
  8570. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8571. match rhs:
  8572. case IfExp(test, body, orelse):
  8573. ...
  8574. case Begin(body, result):
  8575. ...
  8576. case _:
  8577. return [Assign([lhs], rhs)] + cont
  8578. def explicate_pred(cnd, thn, els, basic_blocks):
  8579. match cnd:
  8580. case Compare(left, [op], [right]):
  8581. goto_thn = create_block(thn, basic_blocks)
  8582. goto_els = create_block(els, basic_blocks)
  8583. return [If(cnd, goto_thn, goto_els)]
  8584. case Constant(True):
  8585. return thn;
  8586. case Constant(False):
  8587. return els;
  8588. case UnaryOp(Not(), operand):
  8589. ...
  8590. case IfExp(test, body, orelse):
  8591. ...
  8592. case Begin(body, result):
  8593. ...
  8594. case _:
  8595. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8596. create_block(els, basic_blocks),
  8597. create_block(thn, basic_blocks))]
  8598. def explicate_stmt(s, cont, basic_blocks):
  8599. match s:
  8600. case Assign([lhs], rhs):
  8601. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8602. case Expr(value):
  8603. return explicate_effect(value, cont, basic_blocks)
  8604. case If(test, body, orelse):
  8605. ...
  8606. def explicate_control(p):
  8607. match p:
  8608. case Module(body):
  8609. new_body = [Return(Constant(0))]
  8610. basic_blocks = {}
  8611. for s in reversed(body):
  8612. new_body = explicate_stmt(s, new_body, basic_blocks)
  8613. basic_blocks[label_name('start')] = new_body
  8614. return CProgram(basic_blocks)
  8615. \end{lstlisting}
  8616. \end{tcolorbox}
  8617. \caption{Skeleton for the \code{explicate\_control} pass.}
  8618. \label{fig:explicate-control-Lif}
  8619. \end{figure}
  8620. \fi}
  8621. {\if\edition\racketEd
  8622. \subsection{Explicate Tail and Assign}
  8623. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8624. additional cases for Boolean constants and \key{if}. The cases for
  8625. \code{if} should recursively compile the two branches using either
  8626. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8627. cases should then invoke \code{explicate\_pred} on the condition
  8628. expression, passing in the generated code for the two branches. For
  8629. example, consider the following program with an \code{if} in tail
  8630. position.
  8631. % cond_test_6.rkt
  8632. \begin{lstlisting}
  8633. (let ([x (read)])
  8634. (if (eq? x 0) 42 777))
  8635. \end{lstlisting}
  8636. The two branches are recursively compiled to return statements. We
  8637. then delegate to \code{explicate\_pred}, passing the condition
  8638. \code{(eq? x 0)} and the two return statements. We return to this
  8639. example shortly when we discuss \code{explicate\_pred}.
  8640. Next let us consider a program with an \code{if} on the right-hand
  8641. side of a \code{let}.
  8642. \begin{lstlisting}
  8643. (let ([y (read)])
  8644. (let ([x (if (eq? y 0) 40 777)])
  8645. (+ x 2)))
  8646. \end{lstlisting}
  8647. Note that the body of the inner \code{let} will have already been
  8648. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8649. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8650. to recursively process both branches of the \code{if}, and we do not
  8651. want to duplicate code, so we generate the following block using an
  8652. auxiliary function named \code{create\_block}, discussed in the next
  8653. section.
  8654. \begin{lstlisting}
  8655. block_6:
  8656. return (+ x 2)
  8657. \end{lstlisting}
  8658. We then use \code{goto block\_6;} as the \code{cont} argument for
  8659. compiling the branches. So the two branches compile to
  8660. \begin{center}
  8661. \begin{minipage}{0.2\textwidth}
  8662. \begin{lstlisting}
  8663. x = 40;
  8664. goto block_6;
  8665. \end{lstlisting}
  8666. \end{minipage}
  8667. \hspace{0.5in} and \hspace{0.5in}
  8668. \begin{minipage}{0.2\textwidth}
  8669. \begin{lstlisting}
  8670. x = 777;
  8671. goto block_6;
  8672. \end{lstlisting}
  8673. \end{minipage}
  8674. \end{center}
  8675. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8676. \code{(eq? y 0)} and the previously presented code for the branches.
  8677. \subsection{Create Block}
  8678. We recommend implementing the \code{create\_block} auxiliary function
  8679. as follows, using a global variable \code{basic-blocks} to store a
  8680. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8681. that \code{create\_block} generates a new label and then associates
  8682. the given \code{tail} with the new label in the \code{basic-blocks}
  8683. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8684. new label. However, if the given \code{tail} is already a \code{Goto},
  8685. then there is no need to generate a new label and entry in
  8686. \code{basic-blocks}; we can simply return that \code{Goto}.
  8687. %
  8688. \begin{lstlisting}
  8689. (define (create_block tail)
  8690. (match tail
  8691. [(Goto label) (Goto label)]
  8692. [else
  8693. (let ([label (gensym 'block)])
  8694. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8695. (Goto label))]))
  8696. \end{lstlisting}
  8697. \fi}
  8698. {\if\edition\racketEd
  8699. \subsection{Explicate Predicate}
  8700. The skeleton for the \code{explicate\_pred} function is given in
  8701. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8702. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8703. the code generated by explicate for the \emph{then} branch; and (3)
  8704. \code{els}, the code generated by explicate for the \emph{else}
  8705. branch. The \code{explicate\_pred} function should match on
  8706. \code{cnd} with a case for every kind of expression that can have type
  8707. \BOOLTY{}.
  8708. \begin{figure}[tbp]
  8709. \begin{tcolorbox}[colback=white]
  8710. \begin{lstlisting}
  8711. (define (explicate_pred cnd thn els)
  8712. (match cnd
  8713. [(Var x) ___]
  8714. [(Let x rhs body) ___]
  8715. [(Prim 'not (list e)) ___]
  8716. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8717. (IfStmt (Prim op es) (create_block thn)
  8718. (create_block els))]
  8719. [(Bool b) (if b thn els)]
  8720. [(If cnd^ thn^ els^) ___]
  8721. [else (error "explicate_pred unhandled case" cnd)]))
  8722. \end{lstlisting}
  8723. \end{tcolorbox}
  8724. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8725. \label{fig:explicate-pred}
  8726. \end{figure}
  8727. \fi}
  8728. %
  8729. {\if\edition\pythonEd\pythonColor
  8730. The \code{explicate\_pred} function has four parameters: 1) the
  8731. condition expression, 2) the generated statements for the ``then''
  8732. branch, 3) the generated statements for the ``else'' branch, and 4)
  8733. the dictionary of basic blocks. The \code{explicate\_pred} function
  8734. returns a list of \LangCIf{} statements and it may add to the
  8735. dictionary of basic blocks.
  8736. \fi}
  8737. Consider the case for comparison operators. We translate the
  8738. comparison to an \code{if} statement whose branches are \code{goto}
  8739. statements created by applying \code{create\_block} to the code
  8740. generated for the \code{thn} and \code{els} branches. Let us
  8741. illustrate this translation by returning to the program with an
  8742. \code{if} expression in tail position, shown next. We invoke
  8743. \code{explicate\_pred} on its condition
  8744. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8745. %
  8746. {\if\edition\racketEd
  8747. \begin{lstlisting}
  8748. (let ([x (read)])
  8749. (if (eq? x 0) 42 777))
  8750. \end{lstlisting}
  8751. \fi}
  8752. %
  8753. {\if\edition\pythonEd\pythonColor
  8754. \begin{lstlisting}
  8755. x = input_int()
  8756. 42 if x == 0 else 777
  8757. \end{lstlisting}
  8758. \fi}
  8759. %
  8760. \noindent The two branches \code{42} and \code{777} were already
  8761. compiled to \code{return} statements, from which we now create the
  8762. following blocks:
  8763. %
  8764. \begin{center}
  8765. \begin{minipage}{\textwidth}
  8766. \begin{lstlisting}
  8767. block_1:
  8768. return 42;
  8769. block_2:
  8770. return 777;
  8771. \end{lstlisting}
  8772. \end{minipage}
  8773. \end{center}
  8774. %
  8775. After that, \code{explicate\_pred} compiles the comparison
  8776. \racket{\code{(eq? x 0)}}
  8777. \python{\code{x == 0}}
  8778. to the following \code{if} statement:
  8779. %
  8780. {\if\edition\racketEd
  8781. \begin{center}
  8782. \begin{minipage}{\textwidth}
  8783. \begin{lstlisting}
  8784. if (eq? x 0)
  8785. goto block_1;
  8786. else
  8787. goto block_2;
  8788. \end{lstlisting}
  8789. \end{minipage}
  8790. \end{center}
  8791. \fi}
  8792. {\if\edition\pythonEd\pythonColor
  8793. \begin{center}
  8794. \begin{minipage}{\textwidth}
  8795. \begin{lstlisting}
  8796. if x == 0:
  8797. goto block_1;
  8798. else
  8799. goto block_2;
  8800. \end{lstlisting}
  8801. \end{minipage}
  8802. \end{center}
  8803. \fi}
  8804. Next consider the case for Boolean constants. We perform a kind of
  8805. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8806. either the \code{thn} or \code{els} branch, depending on whether the
  8807. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8808. following program:
  8809. {\if\edition\racketEd
  8810. \begin{lstlisting}
  8811. (if #t 42 777)
  8812. \end{lstlisting}
  8813. \fi}
  8814. {\if\edition\pythonEd\pythonColor
  8815. \begin{lstlisting}
  8816. 42 if True else 777
  8817. \end{lstlisting}
  8818. \fi}
  8819. %
  8820. \noindent Again, the two branches \code{42} and \code{777} were
  8821. compiled to \code{return} statements, so \code{explicate\_pred}
  8822. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8823. code for the \emph{then} branch.
  8824. \begin{lstlisting}
  8825. return 42;
  8826. \end{lstlisting}
  8827. This case demonstrates that we sometimes discard the \code{thn} or
  8828. \code{els} blocks that are input to \code{explicate\_pred}.
  8829. The case for \key{if} expressions in \code{explicate\_pred} is
  8830. particularly illuminating because it deals with the challenges
  8831. discussed previously regarding nested \key{if} expressions
  8832. (figure~\ref{fig:explicate-control-s1-38}). The
  8833. \racket{\lstinline{thn^}}\python{\code{body}} and
  8834. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8835. \key{if} inherit their context from the current one, that is,
  8836. predicate context. So, you should recursively apply
  8837. \code{explicate\_pred} to the
  8838. \racket{\lstinline{thn^}}\python{\code{body}} and
  8839. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8840. those recursive calls, pass \code{thn} and \code{els} as the extra
  8841. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8842. inside each recursive call. As discussed previously, to avoid
  8843. duplicating code, we need to add them to the dictionary of basic
  8844. blocks so that we can instead refer to them by name and execute them
  8845. with a \key{goto}.
  8846. {\if\edition\pythonEd\pythonColor
  8847. %
  8848. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8849. three parameters: (1) the statement to be compiled, (2) the code for its
  8850. continuation, and (3) the dictionary of basic blocks. The
  8851. \code{explicate\_stmt} returns a list of statements, and it may add to
  8852. the dictionary of basic blocks. The cases for assignment and an
  8853. expression-statement are given in full in the skeleton code: they
  8854. simply dispatch to \code{explicate\_assign} and
  8855. \code{explicate\_effect}, respectively. The case for \code{if}
  8856. statements is not given; it is similar to the case for \code{if}
  8857. expressions.
  8858. The \code{explicate\_control} function itself is given in
  8859. figure~\ref{fig:explicate-control-Lif}. It applies
  8860. \code{explicate\_stmt} to each statement in the program, from back to
  8861. front. Thus, the result so far, stored in \code{new\_body}, can be
  8862. used as the continuation parameter in the next call to
  8863. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8864. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8865. the dictionary of basic blocks, labeling it the ``start'' block.
  8866. %
  8867. \fi}
  8868. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8869. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8870. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8871. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8872. %% results from the two recursive calls. We complete the case for
  8873. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8874. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8875. %% the result $B_5$.
  8876. %% \[
  8877. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8878. %% \quad\Rightarrow\quad
  8879. %% B_5
  8880. %% \]
  8881. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8882. %% inherit the current context, so they are in tail position. Thus, the
  8883. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8884. %% \code{explicate\_tail}.
  8885. %% %
  8886. %% We need to pass $B_0$ as the accumulator argument for both of these
  8887. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8888. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8889. %% to the control-flow graph and obtain a promised goto $G_0$.
  8890. %% %
  8891. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8892. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8893. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8894. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8895. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8896. %% \[
  8897. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8898. %% \]
  8899. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8900. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8901. %% should not be confused with the labels for the blocks that appear in
  8902. %% the generated code. We initially construct unlabeled blocks; we only
  8903. %% attach labels to blocks when we add them to the control-flow graph, as
  8904. %% we see in the next case.
  8905. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8906. %% function. The context of the \key{if} is an assignment to some
  8907. %% variable $x$ and then the control continues to some promised block
  8908. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8909. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8910. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8911. %% branches of the \key{if} inherit the current context, so they are in
  8912. %% assignment positions. Let $B_2$ be the result of applying
  8913. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8914. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8915. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8916. %% the result of applying \code{explicate\_pred} to the predicate
  8917. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8918. %% translates to the promise $B_4$.
  8919. %% \[
  8920. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8921. %% \]
  8922. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8923. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8924. \code{remove\_complex\_operands} pass and then the
  8925. \code{explicate\_control} pass on the example program. We walk through
  8926. the output program.
  8927. %
  8928. Following the order of evaluation in the output of
  8929. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8930. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8931. in the predicate of the inner \key{if}. In the output of
  8932. \code{explicate\_control}, in the
  8933. block labeled \code{start}, two assignment statements are followed by an
  8934. \code{if} statement that branches to \code{block\_4} or
  8935. \code{block\_5}. The blocks associated with those labels contain the
  8936. translations of the code
  8937. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8938. and
  8939. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8940. respectively. In particular, we start \code{block\_4} with the
  8941. comparison
  8942. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8943. and then branch to \code{block\_2} or \code{block\_3},
  8944. which correspond to the two branches of the outer \key{if}, that is,
  8945. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8946. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8947. %
  8948. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8949. %
  8950. \python{The \code{block\_1} corresponds to the \code{print} statement
  8951. at the end of the program.}
  8952. {\if\edition\racketEd
  8953. \subsection{Interactions between Explicate and Shrink}
  8954. The way in which the \code{shrink} pass transforms logical operations
  8955. such as \code{and} and \code{or} can impact the quality of code
  8956. generated by \code{explicate\_control}. For example, consider the
  8957. following program:
  8958. % cond_test_21.rkt, and_eq_input.py
  8959. \begin{lstlisting}
  8960. (if (and (eq? (read) 0) (eq? (read) 1))
  8961. 0
  8962. 42)
  8963. \end{lstlisting}
  8964. The \code{and} operation should transform into something that the
  8965. \code{explicate\_pred} function can analyze and descend through to
  8966. reach the underlying \code{eq?} conditions. Ideally, for this program
  8967. your \code{explicate\_control} pass should generate code similar to
  8968. the following:
  8969. \begin{center}
  8970. \begin{minipage}{\textwidth}
  8971. \begin{lstlisting}
  8972. start:
  8973. tmp1 = (read);
  8974. if (eq? tmp1 0) goto block40;
  8975. else goto block39;
  8976. block40:
  8977. tmp2 = (read);
  8978. if (eq? tmp2 1) goto block38;
  8979. else goto block39;
  8980. block38:
  8981. return 0;
  8982. block39:
  8983. return 42;
  8984. \end{lstlisting}
  8985. \end{minipage}
  8986. \end{center}
  8987. \fi}
  8988. \begin{exercise}\normalfont\normalsize
  8989. \racket{
  8990. Implement the pass \code{explicate\_control} by adding the cases for
  8991. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8992. \code{explicate\_assign} functions. Implement the auxiliary function
  8993. \code{explicate\_pred} for predicate contexts.}
  8994. \python{Implement \code{explicate\_control} pass with its
  8995. four auxiliary functions.}
  8996. %
  8997. Create test cases that exercise all the new cases in the code for
  8998. this pass.
  8999. %
  9000. {\if\edition\racketEd
  9001. Add the following entry to the list of \code{passes} in
  9002. \code{run-tests.rkt}:
  9003. \begin{lstlisting}
  9004. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9005. \end{lstlisting}
  9006. and then run \code{run-tests.rkt} to test your compiler.
  9007. \fi}
  9008. \end{exercise}
  9009. \section{Select Instructions}
  9010. \label{sec:select-Lif}
  9011. \index{subject}{select instructions}
  9012. The \code{select\_instructions} pass translates \LangCIf{} to
  9013. \LangXIfVar{}.
  9014. %
  9015. \racket{Recall that we implement this pass using three auxiliary
  9016. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9017. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9018. %
  9019. \racket{For $\Atm$, we have new cases for the Booleans.}
  9020. %
  9021. \python{We begin with the Boolean constants.}
  9022. As previously discussed, we encode them as integers.
  9023. \[
  9024. \TRUE{} \quad\Rightarrow\quad \key{1}
  9025. \qquad\qquad
  9026. \FALSE{} \quad\Rightarrow\quad \key{0}
  9027. \]
  9028. For translating statements, we discuss some of the cases. The
  9029. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9030. discussed at the beginning of this section. Given an assignment, if
  9031. the left-hand-side variable is the same as the argument of \code{not},
  9032. then just the \code{xorq} instruction suffices.
  9033. \[
  9034. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9035. \quad\Rightarrow\quad
  9036. \key{xorq}~\key{\$}1\key{,}~\Var
  9037. \]
  9038. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9039. semantics of x86. In the following translation, let $\Arg$ be the
  9040. result of translating $\Atm$ to x86.
  9041. \[
  9042. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9043. \quad\Rightarrow\quad
  9044. \begin{array}{l}
  9045. \key{movq}~\Arg\key{,}~\Var\\
  9046. \key{xorq}~\key{\$}1\key{,}~\Var
  9047. \end{array}
  9048. \]
  9049. Next consider the cases for equality comparisons. Translating this
  9050. operation to x86 is slightly involved due to the unusual nature of the
  9051. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9052. We recommend translating an assignment with an equality on the
  9053. right-hand side into a sequence of three instructions. \\
  9054. \begin{tabular}{lll}
  9055. \begin{minipage}{0.4\textwidth}
  9056. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9057. \end{minipage}
  9058. &
  9059. $\Rightarrow$
  9060. &
  9061. \begin{minipage}{0.4\textwidth}
  9062. \begin{lstlisting}
  9063. cmpq |$\Arg_2$|, |$\Arg_1$|
  9064. sete %al
  9065. movzbq %al, |$\Var$|
  9066. \end{lstlisting}
  9067. \end{minipage}
  9068. \end{tabular} \\
  9069. The translations for the other comparison operators are similar to
  9070. this but use different condition codes for the \code{set} instruction.
  9071. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9072. \key{goto} and \key{if} statements. Both are straightforward to
  9073. translate to x86.}
  9074. %
  9075. A \key{goto} statement becomes a jump instruction.
  9076. \[
  9077. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9078. \]
  9079. %
  9080. An \key{if} statement becomes a compare instruction followed by a
  9081. conditional jump (for the \emph{then} branch), and the fall-through is to
  9082. a regular jump (for the \emph{else} branch).\\
  9083. \begin{tabular}{lll}
  9084. \begin{minipage}{0.4\textwidth}
  9085. \begin{lstlisting}
  9086. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9087. goto |$\ell_1$||$\racket{\key{;}}$|
  9088. else|$\python{\key{:}}$|
  9089. goto |$\ell_2$||$\racket{\key{;}}$|
  9090. \end{lstlisting}
  9091. \end{minipage}
  9092. &
  9093. $\Rightarrow$
  9094. &
  9095. \begin{minipage}{0.4\textwidth}
  9096. \begin{lstlisting}
  9097. cmpq |$\Arg_2$|, |$\Arg_1$|
  9098. je |$\ell_1$|
  9099. jmp |$\ell_2$|
  9100. \end{lstlisting}
  9101. \end{minipage}
  9102. \end{tabular} \\
  9103. Again, the translations for the other comparison operators are similar to this
  9104. but use different condition codes for the conditional jump instruction.
  9105. \python{Regarding the \key{return} statement, we recommend treating it
  9106. as an assignment to the \key{rax} register followed by a jump to the
  9107. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9108. \begin{exercise}\normalfont\normalsize
  9109. Expand your \code{select\_instructions} pass to handle the new
  9110. features of the \LangCIf{} language.
  9111. %
  9112. {\if\edition\racketEd
  9113. Add the following entry to the list of \code{passes} in
  9114. \code{run-tests.rkt}
  9115. \begin{lstlisting}
  9116. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9117. \end{lstlisting}
  9118. \fi}
  9119. %
  9120. Run the script to test your compiler on all the test programs.
  9121. \end{exercise}
  9122. \section{Register Allocation}
  9123. \label{sec:register-allocation-Lif}
  9124. \index{subject}{register allocation}
  9125. The changes required for compiling \LangIf{} affect liveness analysis,
  9126. building the interference graph, and assigning homes, but the graph
  9127. coloring algorithm itself does not change.
  9128. \subsection{Liveness Analysis}
  9129. \label{sec:liveness-analysis-Lif}
  9130. \index{subject}{liveness analysis}
  9131. Recall that for \LangVar{} we implemented liveness analysis for a
  9132. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9133. the addition of \key{if} expressions to \LangIf{},
  9134. \code{explicate\_control} produces many basic blocks.
  9135. %% We recommend that you create a new auxiliary function named
  9136. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9137. %% control-flow graph.
  9138. The first question is, in what order should we process the basic blocks?
  9139. Recall that to perform liveness analysis on a basic block we need to
  9140. know the live-after set for the last instruction in the block. If a
  9141. basic block has no successors (i.e., contains no jumps to other
  9142. blocks), then it has an empty live-after set and we can immediately
  9143. apply liveness analysis to it. If a basic block has some successors,
  9144. then we need to complete liveness analysis on those blocks
  9145. first. These ordering constraints are the reverse of a
  9146. \emph{topological order}\index{subject}{topological order} on a graph
  9147. representation of the program. In particular, the \emph{control flow
  9148. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9149. of a program has a node for each basic block and an edge for each jump
  9150. from one block to another. It is straightforward to generate a CFG
  9151. from the dictionary of basic blocks. One then transposes the CFG and
  9152. applies the topological sort algorithm.
  9153. %
  9154. %
  9155. \racket{We recommend using the \code{tsort} and \code{transpose}
  9156. functions of the Racket \code{graph} package to accomplish this.}
  9157. %
  9158. \python{We provide implementations of \code{topological\_sort} and
  9159. \code{transpose} in the file \code{graph.py} of the support code.}
  9160. %
  9161. As an aside, a topological ordering is only guaranteed to exist if the
  9162. graph does not contain any cycles. This is the case for the
  9163. control-flow graphs that we generate from \LangIf{} programs.
  9164. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9165. and learn how to handle cycles in the control-flow graph.
  9166. \racket{You need to construct a directed graph to represent the
  9167. control-flow graph. Do not use the \code{directed-graph} of the
  9168. \code{graph} package because that allows at most one edge
  9169. between each pair of vertices, whereas a control-flow graph may have
  9170. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9171. file in the support code implements a graph representation that
  9172. allows multiple edges between a pair of vertices.}
  9173. {\if\edition\racketEd
  9174. The next question is how to analyze jump instructions. Recall that in
  9175. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9176. \code{label->live} that maps each label to the set of live locations
  9177. at the beginning of its block. We use \code{label->live} to determine
  9178. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9179. that we have many basic blocks, \code{label->live} needs to be updated
  9180. as we process the blocks. In particular, after performing liveness
  9181. analysis on a block, we take the live-before set of its first
  9182. instruction and associate that with the block's label in the
  9183. \code{label->live} alist.
  9184. \fi}
  9185. %
  9186. {\if\edition\pythonEd\pythonColor
  9187. %
  9188. The next question is how to analyze jump instructions. The locations
  9189. that are live before a \code{jmp} should be the locations in
  9190. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9191. maintaining a dictionary named \code{live\_before\_block} that maps each
  9192. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9193. block. After performing liveness analysis on each block, we take the
  9194. live-before set of its first instruction and associate that with the
  9195. block's label in the \code{live\_before\_block} dictionary.
  9196. %
  9197. \fi}
  9198. In \LangXIfVar{} we also have the conditional jump
  9199. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9200. this instruction is particularly interesting because during
  9201. compilation, we do not know which way a conditional jump will go. Thus
  9202. we do not know whether to use the live-before set for the block
  9203. associated with the $\itm{label}$ or the live-before set for the
  9204. following instruction. So we use both, by taking the union of the
  9205. live-before sets from the following instruction and from the mapping
  9206. for $\itm{label}$ in
  9207. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9208. The auxiliary functions for computing the variables in an
  9209. instruction's argument and for computing the variables read-from ($R$)
  9210. or written-to ($W$) by an instruction need to be updated to handle the
  9211. new kinds of arguments and instructions in \LangXIfVar{}.
  9212. \begin{exercise}\normalfont\normalsize
  9213. {\if\edition\racketEd
  9214. %
  9215. Update the \code{uncover\_live} pass to apply liveness analysis to
  9216. every basic block in the program.
  9217. %
  9218. Add the following entry to the list of \code{passes} in the
  9219. \code{run-tests.rkt} script:
  9220. \begin{lstlisting}
  9221. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9222. \end{lstlisting}
  9223. \fi}
  9224. {\if\edition\pythonEd\pythonColor
  9225. %
  9226. Update the \code{uncover\_live} function to perform liveness analysis,
  9227. in reverse topological order, on all the basic blocks in the
  9228. program.
  9229. %
  9230. \fi}
  9231. % Check that the live-after sets that you generate for
  9232. % example X matches the following... -Jeremy
  9233. \end{exercise}
  9234. \subsection{Build the Interference Graph}
  9235. \label{sec:build-interference-Lif}
  9236. Many of the new instructions in \LangXIfVar{} can be handled in the
  9237. same way as the instructions in \LangXVar{}.
  9238. % Thus, if your code was
  9239. % already quite general, it will not need to be changed to handle the
  9240. % new instructions. If your code is not general enough, we recommend that
  9241. % you change your code to be more general. For example, you can factor
  9242. % out the computing of the the read and write sets for each kind of
  9243. % instruction into auxiliary functions.
  9244. %
  9245. Some instructions, such as the \key{movzbq} instruction, require special care,
  9246. similar to the \key{movq} instruction. Refer to rule number 1 in
  9247. section~\ref{sec:build-interference}.
  9248. \begin{exercise}\normalfont\normalsize
  9249. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9250. {\if\edition\racketEd
  9251. Add the following entries to the list of \code{passes} in the
  9252. \code{run-tests.rkt} script:
  9253. \begin{lstlisting}
  9254. (list "build_interference" build_interference interp-pseudo-x86-1)
  9255. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9256. \end{lstlisting}
  9257. \fi}
  9258. % Check that the interference graph that you generate for
  9259. % example X matches the following graph G... -Jeremy
  9260. \end{exercise}
  9261. \section{Patch Instructions}
  9262. The new instructions \key{cmpq} and \key{movzbq} have some special
  9263. restrictions that need to be handled in the \code{patch\_instructions}
  9264. pass.
  9265. %
  9266. The second argument of the \key{cmpq} instruction must not be an
  9267. immediate value (such as an integer). So, if you are comparing two
  9268. immediates, we recommend inserting a \key{movq} instruction to put the
  9269. second argument in \key{rax}. On the other hand, if you implemented
  9270. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9271. update it for \LangIf{} and then this situation would not arise.
  9272. %
  9273. As usual, \key{cmpq} may have at most one memory reference.
  9274. %
  9275. The second argument of the \key{movzbq} must be a register.
  9276. \begin{exercise}\normalfont\normalsize
  9277. %
  9278. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9279. %
  9280. {\if\edition\racketEd
  9281. Add the following entry to the list of \code{passes} in
  9282. \code{run-tests.rkt}, and then run this script to test your compiler.
  9283. \begin{lstlisting}
  9284. (list "patch_instructions" patch_instructions interp-x86-1)
  9285. \end{lstlisting}
  9286. \fi}
  9287. \end{exercise}
  9288. {\if\edition\pythonEd\pythonColor
  9289. \section{Prelude and Conclusion}
  9290. \label{sec:prelude-conclusion-cond}
  9291. The generation of the \code{main} function with its prelude and
  9292. conclusion must change to accommodate how the program now consists of
  9293. one or more basic blocks. After the prelude in \code{main}, jump to
  9294. the \code{start} block. Place the conclusion in a basic block labeled
  9295. with \code{conclusion}.
  9296. \fi}
  9297. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9298. \LangIf{} translated to x86, showing the results of
  9299. \code{explicate\_control}, \code{select\_instructions}, and the final
  9300. x86 assembly.
  9301. \begin{figure}[tbp]
  9302. \begin{tcolorbox}[colback=white]
  9303. {\if\edition\racketEd
  9304. \begin{tabular}{lll}
  9305. \begin{minipage}{0.4\textwidth}
  9306. % cond_test_20.rkt, eq_input.py
  9307. \begin{lstlisting}
  9308. (if (eq? (read) 1) 42 0)
  9309. \end{lstlisting}
  9310. $\Downarrow$
  9311. \begin{lstlisting}
  9312. start:
  9313. tmp7951 = (read);
  9314. if (eq? tmp7951 1)
  9315. goto block7952;
  9316. else
  9317. goto block7953;
  9318. block7952:
  9319. return 42;
  9320. block7953:
  9321. return 0;
  9322. \end{lstlisting}
  9323. $\Downarrow$
  9324. \begin{lstlisting}
  9325. start:
  9326. callq read_int
  9327. movq %rax, tmp7951
  9328. cmpq $1, tmp7951
  9329. je block7952
  9330. jmp block7953
  9331. block7953:
  9332. movq $0, %rax
  9333. jmp conclusion
  9334. block7952:
  9335. movq $42, %rax
  9336. jmp conclusion
  9337. \end{lstlisting}
  9338. \end{minipage}
  9339. &
  9340. $\Rightarrow\qquad$
  9341. \begin{minipage}{0.4\textwidth}
  9342. \begin{lstlisting}
  9343. start:
  9344. callq read_int
  9345. movq %rax, %rcx
  9346. cmpq $1, %rcx
  9347. je block7952
  9348. jmp block7953
  9349. block7953:
  9350. movq $0, %rax
  9351. jmp conclusion
  9352. block7952:
  9353. movq $42, %rax
  9354. jmp conclusion
  9355. .globl main
  9356. main:
  9357. pushq %rbp
  9358. movq %rsp, %rbp
  9359. pushq %r13
  9360. pushq %r12
  9361. pushq %rbx
  9362. pushq %r14
  9363. subq $0, %rsp
  9364. jmp start
  9365. conclusion:
  9366. addq $0, %rsp
  9367. popq %r14
  9368. popq %rbx
  9369. popq %r12
  9370. popq %r13
  9371. popq %rbp
  9372. retq
  9373. \end{lstlisting}
  9374. \end{minipage}
  9375. \end{tabular}
  9376. \fi}
  9377. {\if\edition\pythonEd\pythonColor
  9378. \begin{tabular}{lll}
  9379. \begin{minipage}{0.4\textwidth}
  9380. % cond_test_20.rkt, eq_input.py
  9381. \begin{lstlisting}
  9382. print(42 if input_int() == 1 else 0)
  9383. \end{lstlisting}
  9384. $\Downarrow$
  9385. \begin{lstlisting}
  9386. start:
  9387. tmp_0 = input_int()
  9388. if tmp_0 == 1:
  9389. goto block_3
  9390. else:
  9391. goto block_4
  9392. block_3:
  9393. tmp_1 = 42
  9394. goto block_2
  9395. block_4:
  9396. tmp_1 = 0
  9397. goto block_2
  9398. block_2:
  9399. print(tmp_1)
  9400. return 0
  9401. \end{lstlisting}
  9402. $\Downarrow$
  9403. \begin{lstlisting}
  9404. start:
  9405. callq read_int
  9406. movq %rax, tmp_0
  9407. cmpq 1, tmp_0
  9408. je block_3
  9409. jmp block_4
  9410. block_3:
  9411. movq 42, tmp_1
  9412. jmp block_2
  9413. block_4:
  9414. movq 0, tmp_1
  9415. jmp block_2
  9416. block_2:
  9417. movq tmp_1, %rdi
  9418. callq print_int
  9419. movq 0, %rax
  9420. jmp conclusion
  9421. \end{lstlisting}
  9422. \end{minipage}
  9423. &
  9424. $\Rightarrow\qquad$
  9425. \begin{minipage}{0.4\textwidth}
  9426. \begin{lstlisting}
  9427. .globl main
  9428. main:
  9429. pushq %rbp
  9430. movq %rsp, %rbp
  9431. subq $0, %rsp
  9432. jmp start
  9433. start:
  9434. callq read_int
  9435. movq %rax, %rcx
  9436. cmpq $1, %rcx
  9437. je block_3
  9438. jmp block_4
  9439. block_3:
  9440. movq $42, %rcx
  9441. jmp block_2
  9442. block_4:
  9443. movq $0, %rcx
  9444. jmp block_2
  9445. block_2:
  9446. movq %rcx, %rdi
  9447. callq print_int
  9448. movq $0, %rax
  9449. jmp conclusion
  9450. conclusion:
  9451. addq $0, %rsp
  9452. popq %rbp
  9453. retq
  9454. \end{lstlisting}
  9455. \end{minipage}
  9456. \end{tabular}
  9457. \fi}
  9458. \end{tcolorbox}
  9459. \caption{Example compilation of an \key{if} expression to x86, showing
  9460. the results of \code{explicate\_control},
  9461. \code{select\_instructions}, and the final x86 assembly code. }
  9462. \label{fig:if-example-x86}
  9463. \end{figure}
  9464. \begin{figure}[tbp]
  9465. \begin{tcolorbox}[colback=white]
  9466. {\if\edition\racketEd
  9467. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9468. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9469. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9470. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9471. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9472. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9473. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9474. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9475. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9476. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9477. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9478. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9479. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9480. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9481. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9482. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9483. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9484. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9485. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9486. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9487. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9488. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9489. \end{tikzpicture}
  9490. \fi}
  9491. {\if\edition\pythonEd\pythonColor
  9492. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9493. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9494. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9495. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9496. \node (C-1) at (0,0) {\large \LangCIf{}};
  9497. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9498. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9499. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9500. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9501. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9502. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9503. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9504. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9505. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9506. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9507. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9508. \end{tikzpicture}
  9509. \fi}
  9510. \end{tcolorbox}
  9511. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9512. \label{fig:Lif-passes}
  9513. \end{figure}
  9514. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9515. compilation of \LangIf{}.
  9516. \section{Challenge: Optimize Blocks and Remove Jumps}
  9517. \label{sec:opt-jumps}
  9518. We discuss two challenges that involve optimizing the control-flow of
  9519. the program.
  9520. \subsection{Optimize Blocks}
  9521. The algorithm for \code{explicate\_control} that we discussed in
  9522. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9523. blocks. It creates a block whenever a continuation \emph{might} get
  9524. used more than once (for example, whenever the \code{cont} parameter
  9525. is passed into two or more recursive calls). However, some
  9526. continuation arguments may not be used at all. Consider the case for
  9527. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9528. the \code{els} continuation.
  9529. %
  9530. {\if\edition\racketEd
  9531. The following example program falls into this
  9532. case, and it creates two unused blocks.
  9533. \begin{center}
  9534. \begin{tabular}{lll}
  9535. \begin{minipage}{0.4\textwidth}
  9536. % cond_test_82.rkt
  9537. \begin{lstlisting}
  9538. (let ([y (if #t
  9539. (read)
  9540. (if (eq? (read) 0)
  9541. 777
  9542. (let ([x (read)])
  9543. (+ 1 x))))])
  9544. (+ y 2))
  9545. \end{lstlisting}
  9546. \end{minipage}
  9547. &
  9548. $\Rightarrow$
  9549. &
  9550. \begin{minipage}{0.55\textwidth}
  9551. \begin{lstlisting}
  9552. start:
  9553. y = (read);
  9554. goto block_5;
  9555. block_5:
  9556. return (+ y 2);
  9557. block_6:
  9558. y = 777;
  9559. goto block_5;
  9560. block_7:
  9561. x = (read);
  9562. y = (+ 1 x2);
  9563. goto block_5;
  9564. \end{lstlisting}
  9565. \end{minipage}
  9566. \end{tabular}
  9567. \end{center}
  9568. \fi}
  9569. The question is, how can we decide whether to create a basic block?
  9570. \emph{Lazy evaluation}\index{subject}{lazy
  9571. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9572. delaying the creation of a basic block until the point in time at which
  9573. we know that it will be used.
  9574. %
  9575. {\if\edition\racketEd
  9576. %
  9577. Racket provides support for
  9578. lazy evaluation with the
  9579. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9580. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9581. \index{subject}{delay} creates a
  9582. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9583. expressions is postponed. When \key{(force}
  9584. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9585. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9586. result of $e_n$ is cached in the promise and returned. If \code{force}
  9587. is applied again to the same promise, then the cached result is
  9588. returned. If \code{force} is applied to an argument that is not a
  9589. promise, \code{force} simply returns the argument.
  9590. %
  9591. \fi}
  9592. %
  9593. {\if\edition\pythonEd\pythonColor
  9594. %
  9595. Although Python does not provide direct support for lazy evaluation,
  9596. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9597. by wrapping it inside a function with no parameters. We \emph{force}
  9598. its evaluation by calling the function. However, we might need to
  9599. force multiple times, so we store the result of calling the
  9600. function instead of recomputing it each time. The following
  9601. \code{Promise} class handles this memoization process.
  9602. %
  9603. \begin{lstlisting}
  9604. @dataclass
  9605. class Promise:
  9606. fun : typing.Any
  9607. cache : list[stmt] = None
  9608. def force(self):
  9609. if self.cache is None:
  9610. self.cache = self.fun(); return self.cache
  9611. else:
  9612. return self.cache
  9613. \end{lstlisting}
  9614. %
  9615. However, in some cases of \code{explicate\_pred} we return a list
  9616. of statements, and in other cases we return a function that
  9617. computes a list of statements. To uniformly deal with both regular
  9618. data and promises, we define the following \code{force} function that
  9619. checks whether its input is delayed (i.e., whether it is a
  9620. \code{Promise}) and then either (1) forces the promise or (2) returns
  9621. the input.
  9622. %
  9623. \begin{lstlisting}
  9624. def force(promise):
  9625. if isinstance(promise, Promise):
  9626. return promise.force()
  9627. else:
  9628. return promise
  9629. \end{lstlisting}
  9630. %
  9631. \fi}
  9632. We use promises for the input and output of the functions
  9633. \code{explicate\_pred}, \code{explicate\_assign},
  9634. %
  9635. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9636. %
  9637. So, instead of taking and returning \racket{$\Tail$
  9638. expressions}\python{lists of statements}, they take and return
  9639. promises. Furthermore, when we come to a situation in which a
  9640. continuation might be used more than once, as in the case for
  9641. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9642. that creates a basic block for each continuation (if there is not
  9643. already one) and then returns a \code{goto} statement to that basic
  9644. block. When we come to a situation in which we have a promise but need an
  9645. actual piece of code, for example, to create a larger piece of code with a
  9646. constructor such as \code{Seq}, then insert a call to \code{force}.
  9647. %
  9648. {\if\edition\racketEd
  9649. %
  9650. Also, we must modify the \code{create\_block} function to begin with
  9651. \code{delay} to create a promise. When forced, this promise forces the
  9652. original promise. If that returns a \code{Goto} (because the block was
  9653. already added to \code{basic-blocks}), then we return the
  9654. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9655. return a \code{Goto} to the new label.
  9656. \begin{center}
  9657. \begin{minipage}{\textwidth}
  9658. \begin{lstlisting}
  9659. (define (create_block tail)
  9660. (delay
  9661. (define t (force tail))
  9662. (match t
  9663. [(Goto label) (Goto label)]
  9664. [else
  9665. (let ([label (gensym 'block)])
  9666. (set! basic-blocks (cons (cons label t) basic-blocks))
  9667. (Goto label))])))
  9668. \end{lstlisting}
  9669. \end{minipage}
  9670. \end{center}
  9671. \fi}
  9672. {\if\edition\pythonEd\pythonColor
  9673. %
  9674. Here is the new version of the \code{create\_block} auxiliary function
  9675. that works on promises and that checks whether the block consists of a
  9676. solitary \code{goto} statement.\\
  9677. \begin{minipage}{\textwidth}
  9678. \begin{lstlisting}
  9679. def create_block(promise, basic_blocks):
  9680. def delay():
  9681. stmts = force(promise)
  9682. match stmts:
  9683. case [Goto(l)]:
  9684. return [Goto(l)]
  9685. case _:
  9686. label = label_name(generate_name('block'))
  9687. basic_blocks[label] = stmts
  9688. return [Goto(label)]
  9689. return Promise(delay)
  9690. \end{lstlisting}
  9691. \end{minipage}
  9692. \fi}
  9693. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9694. improved \code{explicate\_control} on this example. As you can
  9695. see, the number of basic blocks has been reduced from four blocks (see
  9696. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9697. \begin{figure}[tbp]
  9698. \begin{tcolorbox}[colback=white]
  9699. {\if\edition\racketEd
  9700. \begin{tabular}{lll}
  9701. \begin{minipage}{0.4\textwidth}
  9702. % cond_test_82.rkt
  9703. \begin{lstlisting}
  9704. (let ([y (if #t
  9705. (read)
  9706. (if (eq? (read) 0)
  9707. 777
  9708. (let ([x (read)])
  9709. (+ 1 x))))])
  9710. (+ y 2))
  9711. \end{lstlisting}
  9712. \end{minipage}
  9713. &
  9714. $\Rightarrow$
  9715. &
  9716. \begin{minipage}{0.55\textwidth}
  9717. \begin{lstlisting}
  9718. start:
  9719. y = (read);
  9720. goto block_5;
  9721. block_5:
  9722. return (+ y 2);
  9723. \end{lstlisting}
  9724. \end{minipage}
  9725. \end{tabular}
  9726. \fi}
  9727. {\if\edition\pythonEd\pythonColor
  9728. \begin{tabular}{lll}
  9729. \begin{minipage}{0.4\textwidth}
  9730. % cond_test_41.rkt
  9731. \begin{lstlisting}
  9732. x = input_int()
  9733. y = input_int()
  9734. print(y + 2 \
  9735. if (x == 0 \
  9736. if x < 1 \
  9737. else x == 2) \
  9738. else y + 10)
  9739. \end{lstlisting}
  9740. \end{minipage}
  9741. &
  9742. $\Rightarrow$
  9743. &
  9744. \begin{minipage}{0.55\textwidth}
  9745. \begin{lstlisting}
  9746. start:
  9747. x = input_int()
  9748. y = input_int()
  9749. if x < 1:
  9750. goto block_4
  9751. else:
  9752. goto block_5
  9753. block_4:
  9754. if x == 0:
  9755. goto block_2
  9756. else:
  9757. goto block_3
  9758. block_5:
  9759. if x == 2:
  9760. goto block_2
  9761. else:
  9762. goto block_3
  9763. block_2:
  9764. tmp_0 = y + 2
  9765. goto block_1
  9766. block_3:
  9767. tmp_0 = y + 10
  9768. goto block_1
  9769. block_1:
  9770. print(tmp_0)
  9771. return 0
  9772. \end{lstlisting}
  9773. \end{minipage}
  9774. \end{tabular}
  9775. \fi}
  9776. \end{tcolorbox}
  9777. \caption{Translation from \LangIf{} to \LangCIf{}
  9778. via the improved \code{explicate\_control}.}
  9779. \label{fig:explicate-control-challenge}
  9780. \end{figure}
  9781. %% Recall that in the example output of \code{explicate\_control} in
  9782. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9783. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9784. %% block. The first goal of this challenge assignment is to remove those
  9785. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9786. %% \code{explicate\_control} on the left and shows the result of bypassing
  9787. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9788. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9789. %% \code{block55}. The optimized code on the right of
  9790. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9791. %% \code{then} branch jumping directly to \code{block55}. The story is
  9792. %% similar for the \code{else} branch, as well as for the two branches in
  9793. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9794. %% have been optimized in this way, there are no longer any jumps to
  9795. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9796. %% \begin{figure}[tbp]
  9797. %% \begin{tabular}{lll}
  9798. %% \begin{minipage}{0.4\textwidth}
  9799. %% \begin{lstlisting}
  9800. %% block62:
  9801. %% tmp54 = (read);
  9802. %% if (eq? tmp54 2) then
  9803. %% goto block59;
  9804. %% else
  9805. %% goto block60;
  9806. %% block61:
  9807. %% tmp53 = (read);
  9808. %% if (eq? tmp53 0) then
  9809. %% goto block57;
  9810. %% else
  9811. %% goto block58;
  9812. %% block60:
  9813. %% goto block56;
  9814. %% block59:
  9815. %% goto block55;
  9816. %% block58:
  9817. %% goto block56;
  9818. %% block57:
  9819. %% goto block55;
  9820. %% block56:
  9821. %% return (+ 700 77);
  9822. %% block55:
  9823. %% return (+ 10 32);
  9824. %% start:
  9825. %% tmp52 = (read);
  9826. %% if (eq? tmp52 1) then
  9827. %% goto block61;
  9828. %% else
  9829. %% goto block62;
  9830. %% \end{lstlisting}
  9831. %% \end{minipage}
  9832. %% &
  9833. %% $\Rightarrow$
  9834. %% &
  9835. %% \begin{minipage}{0.55\textwidth}
  9836. %% \begin{lstlisting}
  9837. %% block62:
  9838. %% tmp54 = (read);
  9839. %% if (eq? tmp54 2) then
  9840. %% goto block55;
  9841. %% else
  9842. %% goto block56;
  9843. %% block61:
  9844. %% tmp53 = (read);
  9845. %% if (eq? tmp53 0) then
  9846. %% goto block55;
  9847. %% else
  9848. %% goto block56;
  9849. %% block56:
  9850. %% return (+ 700 77);
  9851. %% block55:
  9852. %% return (+ 10 32);
  9853. %% start:
  9854. %% tmp52 = (read);
  9855. %% if (eq? tmp52 1) then
  9856. %% goto block61;
  9857. %% else
  9858. %% goto block62;
  9859. %% \end{lstlisting}
  9860. %% \end{minipage}
  9861. %% \end{tabular}
  9862. %% \caption{Optimize jumps by removing trivial blocks.}
  9863. %% \label{fig:optimize-jumps}
  9864. %% \end{figure}
  9865. %% The name of this pass is \code{optimize-jumps}. We recommend
  9866. %% implementing this pass in two phases. The first phrase builds a hash
  9867. %% table that maps labels to possibly improved labels. The second phase
  9868. %% changes the target of each \code{goto} to use the improved label. If
  9869. %% the label is for a trivial block, then the hash table should map the
  9870. %% label to the first non-trivial block that can be reached from this
  9871. %% label by jumping through trivial blocks. If the label is for a
  9872. %% non-trivial block, then the hash table should map the label to itself;
  9873. %% we do not want to change jumps to non-trivial blocks.
  9874. %% The first phase can be accomplished by constructing an empty hash
  9875. %% table, call it \code{short-cut}, and then iterating over the control
  9876. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9877. %% then update the hash table, mapping the block's source to the target
  9878. %% of the \code{goto}. Also, the hash table may already have mapped some
  9879. %% labels to the block's source, to you must iterate through the hash
  9880. %% table and update all of those so that they instead map to the target
  9881. %% of the \code{goto}.
  9882. %% For the second phase, we recommend iterating through the $\Tail$ of
  9883. %% each block in the program, updating the target of every \code{goto}
  9884. %% according to the mapping in \code{short-cut}.
  9885. \begin{exercise}\normalfont\normalsize
  9886. Implement the improvements to the \code{explicate\_control} pass.
  9887. Check that it removes trivial blocks in a few example programs. Then
  9888. check that your compiler still passes all your tests.
  9889. \end{exercise}
  9890. \subsection{Remove Jumps}
  9891. There is an opportunity for removing jumps that is apparent in the
  9892. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9893. ends with a jump to \code{block\_5}, and there are no other jumps to
  9894. \code{block\_5} in the rest of the program. In this situation we can
  9895. avoid the runtime overhead of this jump by merging \code{block\_5}
  9896. into the preceding block, which in this case is the \code{start} block.
  9897. Figure~\ref{fig:remove-jumps} shows the output of
  9898. \code{allocate\_registers} on the left and the result of this
  9899. optimization on the right.
  9900. \begin{figure}[tbp]
  9901. \begin{tcolorbox}[colback=white]
  9902. {\if\edition\racketEd
  9903. \begin{tabular}{lll}
  9904. \begin{minipage}{0.5\textwidth}
  9905. % cond_test_82.rkt
  9906. \begin{lstlisting}
  9907. start:
  9908. callq read_int
  9909. movq %rax, %rcx
  9910. jmp block_5
  9911. block_5:
  9912. movq %rcx, %rax
  9913. addq $2, %rax
  9914. jmp conclusion
  9915. \end{lstlisting}
  9916. \end{minipage}
  9917. &
  9918. $\Rightarrow\qquad$
  9919. \begin{minipage}{0.4\textwidth}
  9920. \begin{lstlisting}
  9921. start:
  9922. callq read_int
  9923. movq %rax, %rcx
  9924. movq %rcx, %rax
  9925. addq $2, %rax
  9926. jmp conclusion
  9927. \end{lstlisting}
  9928. \end{minipage}
  9929. \end{tabular}
  9930. \fi}
  9931. {\if\edition\pythonEd\pythonColor
  9932. \begin{tabular}{lll}
  9933. \begin{minipage}{0.5\textwidth}
  9934. % cond_test_20.rkt
  9935. \begin{lstlisting}
  9936. start:
  9937. callq read_int
  9938. movq %rax, tmp_0
  9939. cmpq 1, tmp_0
  9940. je block_3
  9941. jmp block_4
  9942. block_3:
  9943. movq 42, tmp_1
  9944. jmp block_2
  9945. block_4:
  9946. movq 0, tmp_1
  9947. jmp block_2
  9948. block_2:
  9949. movq tmp_1, %rdi
  9950. callq print_int
  9951. movq 0, %rax
  9952. jmp conclusion
  9953. \end{lstlisting}
  9954. \end{minipage}
  9955. &
  9956. $\Rightarrow\qquad$
  9957. \begin{minipage}{0.4\textwidth}
  9958. \begin{lstlisting}
  9959. start:
  9960. callq read_int
  9961. movq %rax, tmp_0
  9962. cmpq 1, tmp_0
  9963. je block_3
  9964. movq 0, tmp_1
  9965. jmp block_2
  9966. block_3:
  9967. movq 42, tmp_1
  9968. jmp block_2
  9969. block_2:
  9970. movq tmp_1, %rdi
  9971. callq print_int
  9972. movq 0, %rax
  9973. jmp conclusion
  9974. \end{lstlisting}
  9975. \end{minipage}
  9976. \end{tabular}
  9977. \fi}
  9978. \end{tcolorbox}
  9979. \caption{Merging basic blocks by removing unnecessary jumps.}
  9980. \label{fig:remove-jumps}
  9981. \end{figure}
  9982. \begin{exercise}\normalfont\normalsize
  9983. %
  9984. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9985. into their preceding basic block, when there is only one preceding
  9986. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9987. %
  9988. {\if\edition\racketEd
  9989. In the \code{run-tests.rkt} script, add the following entry to the
  9990. list of \code{passes} between \code{allocate\_registers}
  9991. and \code{patch\_instructions}:
  9992. \begin{lstlisting}
  9993. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9994. \end{lstlisting}
  9995. \fi}
  9996. %
  9997. Run the script to test your compiler.
  9998. %
  9999. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10000. blocks on several test programs.
  10001. \end{exercise}
  10002. \section{Further Reading}
  10003. \label{sec:cond-further-reading}
  10004. The algorithm for the \code{explicate\_control} pass is based on the
  10005. \code{expose-basic-blocks} pass in the course notes of
  10006. \citet{Dybvig:2010aa}.
  10007. %
  10008. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10009. \citet{Appel:2003fk}, and is related to translations into continuation
  10010. passing
  10011. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10012. %
  10013. The treatment of conditionals in the \code{explicate\_control} pass is
  10014. similar to short-cut Boolean
  10015. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10016. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10017. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10018. \chapter{Loops and Dataflow Analysis}
  10019. \label{ch:Lwhile}
  10020. \setcounter{footnote}{0}
  10021. % TODO: define R'_8
  10022. % TODO: multi-graph
  10023. {\if\edition\racketEd
  10024. %
  10025. In this chapter we study two features that are the hallmarks of
  10026. imperative programming languages: loops and assignments to local
  10027. variables. The following example demonstrates these new features by
  10028. computing the sum of the first five positive integers:
  10029. % similar to loop_test_1.rkt
  10030. \begin{lstlisting}
  10031. (let ([sum 0])
  10032. (let ([i 5])
  10033. (begin
  10034. (while (> i 0)
  10035. (begin
  10036. (set! sum (+ sum i))
  10037. (set! i (- i 1))))
  10038. sum)))
  10039. \end{lstlisting}
  10040. The \code{while} loop consists of a condition and a
  10041. body.\footnote{The \code{while} loop is not a built-in
  10042. feature of the Racket language, but Racket includes many looping
  10043. constructs and it is straightforward to define \code{while} as a
  10044. macro.} The body is evaluated repeatedly so long as the condition
  10045. remains true.
  10046. %
  10047. The \code{set!} consists of a variable and a right-hand side
  10048. expression. The \code{set!} updates value of the variable to the
  10049. value of the right-hand side.
  10050. %
  10051. The primary purpose of both the \code{while} loop and \code{set!} is
  10052. to cause side effects, so they do not give a meaningful result
  10053. value. Instead, their result is the \code{\#<void>} value. The
  10054. expression \code{(void)} is an explicit way to create the
  10055. \code{\#<void>} value, and it has type \code{Void}. The
  10056. \code{\#<void>} value can be passed around just like other values
  10057. inside an \LangLoop{} program, and it can be compared for equality with
  10058. another \code{\#<void>} value. However, there are no other operations
  10059. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10060. Racket defines the \code{void?} predicate that returns \code{\#t}
  10061. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10062. %
  10063. \footnote{Racket's \code{Void} type corresponds to what is often
  10064. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10065. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10066. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10067. %
  10068. With the addition of side effect-producing features such as
  10069. \code{while} loop and \code{set!}, it is helpful to include a language
  10070. feature for sequencing side effects: the \code{begin} expression. It
  10071. consists of one or more subexpressions that are evaluated
  10072. left to right.
  10073. %
  10074. \fi}
  10075. {\if\edition\pythonEd\pythonColor
  10076. %
  10077. In this chapter we study loops, one of the hallmarks of imperative
  10078. programming languages. The following example demonstrates the
  10079. \code{while} loop by computing the sum of the first five positive
  10080. integers.
  10081. \begin{lstlisting}
  10082. sum = 0
  10083. i = 5
  10084. while i > 0:
  10085. sum = sum + i
  10086. i = i - 1
  10087. print(sum)
  10088. \end{lstlisting}
  10089. The \code{while} loop consists of a condition expression and a body (a
  10090. sequence of statements). The body is evaluated repeatedly so long as
  10091. the condition remains true.
  10092. %
  10093. \fi}
  10094. \section{The \LangLoop{} Language}
  10095. \newcommand{\LwhileGrammarRacket}{
  10096. \begin{array}{lcl}
  10097. \Type &::=& \key{Void}\\
  10098. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10099. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10100. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10101. \end{array}
  10102. }
  10103. \newcommand{\LwhileASTRacket}{
  10104. \begin{array}{lcl}
  10105. \Type &::=& \key{Void}\\
  10106. \Exp &::=& \SETBANG{\Var}{\Exp}
  10107. \MID \BEGIN{\Exp^{*}}{\Exp}
  10108. \MID \WHILE{\Exp}{\Exp}
  10109. \MID \VOID{}
  10110. \end{array}
  10111. }
  10112. \newcommand{\LwhileGrammarPython}{
  10113. \begin{array}{rcl}
  10114. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10115. \end{array}
  10116. }
  10117. \newcommand{\LwhileASTPython}{
  10118. \begin{array}{lcl}
  10119. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10120. \end{array}
  10121. }
  10122. \begin{figure}[tp]
  10123. \centering
  10124. \begin{tcolorbox}[colback=white]
  10125. \small
  10126. {\if\edition\racketEd
  10127. \[
  10128. \begin{array}{l}
  10129. \gray{\LintGrammarRacket{}} \\ \hline
  10130. \gray{\LvarGrammarRacket{}} \\ \hline
  10131. \gray{\LifGrammarRacket{}} \\ \hline
  10132. \LwhileGrammarRacket \\
  10133. \begin{array}{lcl}
  10134. \LangLoopM{} &::=& \Exp
  10135. \end{array}
  10136. \end{array}
  10137. \]
  10138. \fi}
  10139. {\if\edition\pythonEd\pythonColor
  10140. \[
  10141. \begin{array}{l}
  10142. \gray{\LintGrammarPython} \\ \hline
  10143. \gray{\LvarGrammarPython} \\ \hline
  10144. \gray{\LifGrammarPython} \\ \hline
  10145. \LwhileGrammarPython \\
  10146. \begin{array}{rcl}
  10147. \LangLoopM{} &::=& \Stmt^{*}
  10148. \end{array}
  10149. \end{array}
  10150. \]
  10151. \fi}
  10152. \end{tcolorbox}
  10153. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10154. \label{fig:Lwhile-concrete-syntax}
  10155. \end{figure}
  10156. \begin{figure}[tp]
  10157. \centering
  10158. \begin{tcolorbox}[colback=white]
  10159. \small
  10160. {\if\edition\racketEd
  10161. \[
  10162. \begin{array}{l}
  10163. \gray{\LintOpAST} \\ \hline
  10164. \gray{\LvarASTRacket{}} \\ \hline
  10165. \gray{\LifASTRacket{}} \\ \hline
  10166. \LwhileASTRacket{} \\
  10167. \begin{array}{lcl}
  10168. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10169. \end{array}
  10170. \end{array}
  10171. \]
  10172. \fi}
  10173. {\if\edition\pythonEd\pythonColor
  10174. \[
  10175. \begin{array}{l}
  10176. \gray{\LintASTPython} \\ \hline
  10177. \gray{\LvarASTPython} \\ \hline
  10178. \gray{\LifASTPython} \\ \hline
  10179. \LwhileASTPython \\
  10180. \begin{array}{lcl}
  10181. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10182. \end{array}
  10183. \end{array}
  10184. \]
  10185. \fi}
  10186. \end{tcolorbox}
  10187. \python{
  10188. \index{subject}{While@\texttt{While}}
  10189. }
  10190. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10191. \label{fig:Lwhile-syntax}
  10192. \end{figure}
  10193. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10194. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10195. shows the definition of its abstract syntax.
  10196. %
  10197. The definitional interpreter for \LangLoop{} is shown in
  10198. figure~\ref{fig:interp-Lwhile}.
  10199. %
  10200. {\if\edition\racketEd
  10201. %
  10202. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10203. and \code{Void}, and we make changes to the cases for \code{Var} and
  10204. \code{Let} regarding variables. To support assignment to variables and
  10205. to make their lifetimes indefinite (see the second example in
  10206. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10207. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10208. value.
  10209. %
  10210. Now we discuss the new cases. For \code{SetBang}, we find the
  10211. variable in the environment to obtain a boxed value, and then we change
  10212. it using \code{set-box!} to the result of evaluating the right-hand
  10213. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10214. %
  10215. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10216. if the result is true, (2) evaluate the body.
  10217. The result value of a \code{while} loop is also \code{\#<void>}.
  10218. %
  10219. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10220. subexpressions \itm{es} for their effects and then evaluates
  10221. and returns the result from \itm{body}.
  10222. %
  10223. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10224. %
  10225. \fi}
  10226. {\if\edition\pythonEd\pythonColor
  10227. %
  10228. We add a new case for \code{While} in the \code{interp\_stmts}
  10229. function, in which we repeatedly interpret the \code{body} so long as the
  10230. \code{test} expression remains true.
  10231. %
  10232. \fi}
  10233. \begin{figure}[tbp]
  10234. \begin{tcolorbox}[colback=white]
  10235. {\if\edition\racketEd
  10236. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10237. (define interp-Lwhile-class
  10238. (class interp-Lif-class
  10239. (super-new)
  10240. (define/override ((interp-exp env) e)
  10241. (define recur (interp-exp env))
  10242. (match e
  10243. [(Let x e body)
  10244. (define new-env (dict-set env x (box (recur e))))
  10245. ((interp-exp new-env) body)]
  10246. [(Var x) (unbox (dict-ref env x))]
  10247. [(SetBang x rhs)
  10248. (set-box! (dict-ref env x) (recur rhs))]
  10249. [(WhileLoop cnd body)
  10250. (define (loop)
  10251. (cond [(recur cnd) (recur body) (loop)]
  10252. [else (void)]))
  10253. (loop)]
  10254. [(Begin es body)
  10255. (for ([e es]) (recur e))
  10256. (recur body)]
  10257. [(Void) (void)]
  10258. [else ((super interp-exp env) e)]))
  10259. ))
  10260. (define (interp-Lwhile p)
  10261. (send (new interp-Lwhile-class) interp-program p))
  10262. \end{lstlisting}
  10263. \fi}
  10264. {\if\edition\pythonEd\pythonColor
  10265. \begin{lstlisting}
  10266. class InterpLwhile(InterpLif):
  10267. def interp_stmt(self, s, env, cont):
  10268. match s:
  10269. case While(test, body, []):
  10270. if self.interp_exp(test, env):
  10271. self.interp_stmts(body + [s] + cont, env)
  10272. else:
  10273. return self.interp_stmts(cont, env)
  10274. case _:
  10275. return super().interp_stmt(s, env, cont)
  10276. \end{lstlisting}
  10277. \fi}
  10278. \end{tcolorbox}
  10279. \caption{Interpreter for \LangLoop{}.}
  10280. \label{fig:interp-Lwhile}
  10281. \end{figure}
  10282. The definition of the type checker for \LangLoop{} is shown in
  10283. figure~\ref{fig:type-check-Lwhile}.
  10284. %
  10285. {\if\edition\racketEd
  10286. %
  10287. The type checking of the \code{SetBang} expression requires the type
  10288. of the variable and the right-hand side to agree. The result type is
  10289. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10290. and the result type is \code{Void}. For \code{Begin}, the result type
  10291. is the type of its last subexpression.
  10292. %
  10293. \fi}
  10294. %
  10295. {\if\edition\pythonEd\pythonColor
  10296. %
  10297. A \code{while} loop is well typed if the type of the \code{test}
  10298. expression is \code{bool} and the statements in the \code{body} are
  10299. well typed.
  10300. %
  10301. \fi}
  10302. \begin{figure}[tbp]
  10303. \begin{tcolorbox}[colback=white]
  10304. {\if\edition\racketEd
  10305. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10306. (define type-check-Lwhile-class
  10307. (class type-check-Lif-class
  10308. (super-new)
  10309. (inherit check-type-equal?)
  10310. (define/override (type-check-exp env)
  10311. (lambda (e)
  10312. (define recur (type-check-exp env))
  10313. (match e
  10314. [(SetBang x rhs)
  10315. (define-values (rhs^ rhsT) (recur rhs))
  10316. (define varT (dict-ref env x))
  10317. (check-type-equal? rhsT varT e)
  10318. (values (SetBang x rhs^) 'Void)]
  10319. [(WhileLoop cnd body)
  10320. (define-values (cnd^ Tc) (recur cnd))
  10321. (check-type-equal? Tc 'Boolean e)
  10322. (define-values (body^ Tbody) ((type-check-exp env) body))
  10323. (values (WhileLoop cnd^ body^) 'Void)]
  10324. [(Begin es body)
  10325. (define-values (es^ ts)
  10326. (for/lists (l1 l2) ([e es]) (recur e)))
  10327. (define-values (body^ Tbody) (recur body))
  10328. (values (Begin es^ body^) Tbody)]
  10329. [else ((super type-check-exp env) e)])))
  10330. ))
  10331. (define (type-check-Lwhile p)
  10332. (send (new type-check-Lwhile-class) type-check-program p))
  10333. \end{lstlisting}
  10334. \fi}
  10335. {\if\edition\pythonEd\pythonColor
  10336. \begin{lstlisting}
  10337. class TypeCheckLwhile(TypeCheckLif):
  10338. def type_check_stmts(self, ss, env):
  10339. if len(ss) == 0:
  10340. return
  10341. match ss[0]:
  10342. case While(test, body, []):
  10343. test_t = self.type_check_exp(test, env)
  10344. check_type_equal(bool, test_t, test)
  10345. body_t = self.type_check_stmts(body, env)
  10346. return self.type_check_stmts(ss[1:], env)
  10347. case _:
  10348. return super().type_check_stmts(ss, env)
  10349. \end{lstlisting}
  10350. \fi}
  10351. \end{tcolorbox}
  10352. \caption{Type checker for the \LangLoop{} language.}
  10353. \label{fig:type-check-Lwhile}
  10354. \end{figure}
  10355. {\if\edition\racketEd
  10356. %
  10357. At first glance, the translation of these language features to x86
  10358. seems straightforward because the \LangCIf{} intermediate language
  10359. already supports all the ingredients that we need: assignment,
  10360. \code{goto}, conditional branching, and sequencing. However,
  10361. complications arise, which we discuss in the next section. After
  10362. that we introduce the changes necessary to the existing passes.
  10363. %
  10364. \fi}
  10365. {\if\edition\pythonEd\pythonColor
  10366. %
  10367. At first glance, the translation of \code{while} loops to x86 seems
  10368. straightforward because the \LangCIf{} intermediate language already
  10369. supports \code{goto} and conditional branching. However, there are
  10370. complications that arise which we discuss in the next section. After
  10371. that we introduce the changes necessary to the existing passes.
  10372. %
  10373. \fi}
  10374. \section{Cyclic Control Flow and Dataflow Analysis}
  10375. \label{sec:dataflow-analysis}
  10376. Up until this point, the programs generated in
  10377. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10378. \code{while} loop introduces a cycle. Does that matter?
  10379. %
  10380. Indeed, it does. Recall that for register allocation, the compiler
  10381. performs liveness analysis to determine which variables can share the
  10382. same register. To accomplish this, we analyzed the control-flow graph
  10383. in reverse topological order
  10384. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10385. well defined only for acyclic graphs.
  10386. Let us return to the example of computing the sum of the first five
  10387. positive integers. Here is the program after instruction
  10388. selection\index{subject}{instruction selection} but before register
  10389. allocation.
  10390. \begin{center}
  10391. {\if\edition\racketEd
  10392. \begin{minipage}{0.45\textwidth}
  10393. \begin{lstlisting}
  10394. (define (main) : Integer
  10395. mainstart:
  10396. movq $0, sum
  10397. movq $5, i
  10398. jmp block5
  10399. block5:
  10400. movq i, tmp3
  10401. cmpq tmp3, $0
  10402. jl block7
  10403. jmp block8
  10404. \end{lstlisting}
  10405. \end{minipage}
  10406. \begin{minipage}{0.45\textwidth}
  10407. \begin{lstlisting}
  10408. block7:
  10409. addq i, sum
  10410. movq $1, tmp4
  10411. negq tmp4
  10412. addq tmp4, i
  10413. jmp block5
  10414. block8:
  10415. movq $27, %rax
  10416. addq sum, %rax
  10417. jmp mainconclusion)
  10418. \end{lstlisting}
  10419. \end{minipage}
  10420. \fi}
  10421. {\if\edition\pythonEd\pythonColor
  10422. \begin{minipage}{0.45\textwidth}
  10423. \begin{lstlisting}
  10424. mainstart:
  10425. movq $0, sum
  10426. movq $5, i
  10427. jmp block5
  10428. block5:
  10429. cmpq $0, i
  10430. jg block7
  10431. jmp block8
  10432. \end{lstlisting}
  10433. \end{minipage}
  10434. \begin{minipage}{0.45\textwidth}
  10435. \begin{lstlisting}
  10436. block7:
  10437. addq i, sum
  10438. subq $1, i
  10439. jmp block5
  10440. block8:
  10441. movq sum, %rdi
  10442. callq print_int
  10443. movq $0, %rax
  10444. jmp mainconclusion
  10445. \end{lstlisting}
  10446. \end{minipage}
  10447. \fi}
  10448. \end{center}
  10449. Recall that liveness analysis works backward, starting at the end
  10450. of each function. For this example we could start with \code{block8}
  10451. because we know what is live at the beginning of the conclusion:
  10452. only \code{rax} and \code{rsp}. So the live-before set
  10453. for \code{block8} is \code{\{rsp,sum\}}.
  10454. %
  10455. Next we might try to analyze \code{block5} or \code{block7}, but
  10456. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10457. we are stuck.
  10458. The way out of this impasse is to realize that we can compute an
  10459. underapproximation of each live-before set by starting with empty
  10460. live-after sets. By \emph{underapproximation}, we mean that the set
  10461. contains only variables that are live for some execution of the
  10462. program, but the set may be missing some variables that are live.
  10463. Next, the underapproximations for each block can be improved by (1)
  10464. updating the live-after set for each block using the approximate
  10465. live-before sets from the other blocks, and (2) performing liveness
  10466. analysis again on each block. In fact, by iterating this process, the
  10467. underapproximations eventually become the correct solutions!
  10468. %
  10469. This approach of iteratively analyzing a control-flow graph is
  10470. applicable to many static analysis problems and goes by the name
  10471. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10472. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10473. Washington.
  10474. Let us apply this approach to the previously presented example. We use
  10475. the empty set for the initial live-before set for each block. Let
  10476. $m_0$ be the following mapping from label names to sets of locations
  10477. (variables and registers):
  10478. \begin{center}
  10479. \begin{lstlisting}
  10480. mainstart: {}, block5: {}, block7: {}, block8: {}
  10481. \end{lstlisting}
  10482. \end{center}
  10483. Using the above live-before approximations, we determine the
  10484. live-after for each block and then apply liveness analysis to each
  10485. block. This produces our next approximation $m_1$ of the live-before
  10486. sets.
  10487. \begin{center}
  10488. \begin{lstlisting}
  10489. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10490. \end{lstlisting}
  10491. \end{center}
  10492. For the second round, the live-after for \code{mainstart} is the
  10493. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10494. the liveness analysis for \code{mainstart} computes the empty set. The
  10495. live-after for \code{block5} is the union of the live-before sets for
  10496. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10497. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10498. sum\}}. The live-after for \code{block7} is the live-before for
  10499. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10500. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10501. Together these yield the following approximation $m_2$ of
  10502. the live-before sets:
  10503. \begin{center}
  10504. \begin{lstlisting}
  10505. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10506. \end{lstlisting}
  10507. \end{center}
  10508. In the preceding iteration, only \code{block5} changed, so we can
  10509. limit our attention to \code{mainstart} and \code{block7}, the two
  10510. blocks that jump to \code{block5}. As a result, the live-before sets
  10511. for \code{mainstart} and \code{block7} are updated to include
  10512. \code{rsp}, yielding the following approximation $m_3$:
  10513. \begin{center}
  10514. \begin{lstlisting}
  10515. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10516. \end{lstlisting}
  10517. \end{center}
  10518. Because \code{block7} changed, we analyze \code{block5} once more, but
  10519. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10520. our approximations have converged, so $m_3$ is the solution.
  10521. This iteration process is guaranteed to converge to a solution by the
  10522. Kleene fixed-point theorem, a general theorem about functions on
  10523. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10524. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10525. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10526. join operator
  10527. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10528. will be working with join semilattices.} When two elements are
  10529. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10530. as much information as $m_i$, so we can think of $m_j$ as a
  10531. better-than-or-equal-to approximation in relation to $m_i$. The
  10532. bottom element $\bot$ represents the complete lack of information,
  10533. that is, the worst approximation. The join operator takes two lattice
  10534. elements and combines their information; that is, it produces the
  10535. least upper bound of the two.\index{subject}{least upper bound}
  10536. A dataflow analysis typically involves two lattices: one lattice to
  10537. represent abstract states and another lattice that aggregates the
  10538. abstract states of all the blocks in the control-flow graph. For
  10539. liveness analysis, an abstract state is a set of locations. We form
  10540. the lattice $L$ by taking its elements to be sets of locations, the
  10541. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10542. set, and the join operator to be set union.
  10543. %
  10544. We form a second lattice $M$ by taking its elements to be mappings
  10545. from the block labels to sets of locations (elements of $L$). We
  10546. order the mappings point-wise, using the ordering of $L$. So, given any
  10547. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10548. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10549. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10550. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10551. We can think of one iteration of liveness analysis applied to the
  10552. whole program as being a function $f$ on the lattice $M$. It takes a
  10553. mapping as input and computes a new mapping.
  10554. \[
  10555. f(m_i) = m_{i+1}
  10556. \]
  10557. Next let us think for a moment about what a final solution $m_s$
  10558. should look like. If we perform liveness analysis using the solution
  10559. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10560. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10561. \[
  10562. f(m_s) = m_s
  10563. \]
  10564. Furthermore, the solution should include only locations that are
  10565. forced to be there by performing liveness analysis on the program, so
  10566. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10567. The Kleene fixed-point theorem states that if a function $f$ is
  10568. monotone (better inputs produce better outputs), then the least fixed
  10569. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10570. chain} obtained by starting at $\bot$ and iterating $f$, as
  10571. follows:\index{subject}{Kleene fixed-point theorem}
  10572. \[
  10573. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10574. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10575. \]
  10576. When a lattice contains only finitely long ascending chains, then
  10577. every Kleene chain tops out at some fixed point after some number of
  10578. iterations of $f$.
  10579. \[
  10580. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10581. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10582. \]
  10583. The liveness analysis is indeed a monotone function and the lattice
  10584. $M$ has finitely long ascending chains because there are only a
  10585. finite number of variables and blocks in the program. Thus we are
  10586. guaranteed that iteratively applying liveness analysis to all blocks
  10587. in the program will eventually produce the least fixed point solution.
  10588. Next let us consider dataflow analysis in general and discuss the
  10589. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10590. %
  10591. The algorithm has four parameters: the control-flow graph \code{G}, a
  10592. function \code{transfer} that applies the analysis to one block, and the
  10593. \code{bottom} and \code{join} operators for the lattice of abstract
  10594. states. The \code{analyze\_dataflow} function is formulated as a
  10595. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10596. function come from the predecessor nodes in the control-flow
  10597. graph. However, liveness analysis is a \emph{backward} dataflow
  10598. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10599. function with the transpose of the control-flow graph.
  10600. The algorithm begins by creating the bottom mapping, represented by a
  10601. hash table. It then pushes all the nodes in the control-flow graph
  10602. onto the work list (a queue). The algorithm repeats the \code{while}
  10603. loop as long as there are items in the work list. In each iteration, a
  10604. node is popped from the work list and processed. The \code{input} for
  10605. the node is computed by taking the join of the abstract states of all
  10606. the predecessor nodes. The \code{transfer} function is then applied to
  10607. obtain the \code{output} abstract state. If the output differs from
  10608. the previous state for this block, the mapping for this block is
  10609. updated and its successor nodes are pushed onto the work list.
  10610. \begin{figure}[tb]
  10611. \begin{tcolorbox}[colback=white]
  10612. {\if\edition\racketEd
  10613. \begin{lstlisting}
  10614. (define (analyze_dataflow G transfer bottom join)
  10615. (define mapping (make-hash))
  10616. (for ([v (in-vertices G)])
  10617. (dict-set! mapping v bottom))
  10618. (define worklist (make-queue))
  10619. (for ([v (in-vertices G)])
  10620. (enqueue! worklist v))
  10621. (define trans-G (transpose G))
  10622. (while (not (queue-empty? worklist))
  10623. (define node (dequeue! worklist))
  10624. (define input (for/fold ([state bottom])
  10625. ([pred (in-neighbors trans-G node)])
  10626. (join state (dict-ref mapping pred))))
  10627. (define output (transfer node input))
  10628. (cond [(not (equal? output (dict-ref mapping node)))
  10629. (dict-set! mapping node output)
  10630. (for ([v (in-neighbors G node)])
  10631. (enqueue! worklist v))]))
  10632. mapping)
  10633. \end{lstlisting}
  10634. \fi}
  10635. {\if\edition\pythonEd\pythonColor
  10636. \begin{lstlisting}
  10637. def analyze_dataflow(G, transfer, bottom, join):
  10638. trans_G = transpose(G)
  10639. mapping = dict((v, bottom) for v in G.vertices())
  10640. worklist = deque(G.vertices)
  10641. while worklist:
  10642. node = worklist.pop()
  10643. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10644. input = reduce(join, inputs, bottom)
  10645. output = transfer(node, input)
  10646. if output != mapping[node]:
  10647. mapping[node] = output
  10648. worklist.extend(G.adjacent(node))
  10649. \end{lstlisting}
  10650. \fi}
  10651. \end{tcolorbox}
  10652. \caption{Generic work list algorithm for dataflow analysis.}
  10653. \label{fig:generic-dataflow}
  10654. \end{figure}
  10655. {\if\edition\racketEd
  10656. \section{Mutable Variables and Remove Complex Operands}
  10657. There is a subtle interaction between the
  10658. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10659. and the left-to-right order of evaluation of Racket. Consider the
  10660. following example:
  10661. \begin{lstlisting}
  10662. (let ([x 2])
  10663. (+ x (begin (set! x 40) x)))
  10664. \end{lstlisting}
  10665. The result of this program is \code{42} because the first read from
  10666. \code{x} produces \code{2} and the second produces \code{40}. However,
  10667. if we naively apply the \code{remove\_complex\_operands} pass to this
  10668. example we obtain the following program whose result is \code{80}!
  10669. \begin{lstlisting}
  10670. (let ([x 2])
  10671. (let ([tmp (begin (set! x 40) x)])
  10672. (+ x tmp)))
  10673. \end{lstlisting}
  10674. The problem is that with mutable variables, the ordering between
  10675. reads and writes is important, and the
  10676. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10677. before the first read of \code{x}.
  10678. We recommend solving this problem by giving special treatment to reads
  10679. from mutable variables, that is, variables that occur on the left-hand
  10680. side of a \code{set!}. We mark each read from a mutable variable with
  10681. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10682. that the read operation is effectful in that it can produce different
  10683. results at different points in time. Let's apply this idea to the
  10684. following variation that also involves a variable that is not mutated:
  10685. % loop_test_24.rkt
  10686. \begin{lstlisting}
  10687. (let ([x 2])
  10688. (let ([y 0])
  10689. (+ y (+ x (begin (set! x 40) x)))))
  10690. \end{lstlisting}
  10691. We first analyze this program to discover that variable \code{x}
  10692. is mutable but \code{y} is not. We then transform the program as
  10693. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10694. \begin{lstlisting}
  10695. (let ([x 2])
  10696. (let ([y 0])
  10697. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10698. \end{lstlisting}
  10699. Now that we have a clear distinction between reads from mutable and
  10700. immutable variables, we can apply the \code{remove\_complex\_operands}
  10701. pass, where reads from immutable variables are still classified as
  10702. atomic expressions but reads from mutable variables are classified as
  10703. complex. Thus, \code{remove\_complex\_operands} yields the following
  10704. program:\\
  10705. \begin{minipage}{\textwidth}
  10706. \begin{lstlisting}
  10707. (let ([x 2])
  10708. (let ([y 0])
  10709. (let ([t1 x])
  10710. (let ([t2 (begin (set! x 40) x)])
  10711. (let ([t3 (+ t1 t2)])
  10712. (+ y t3))))))
  10713. \end{lstlisting}
  10714. \end{minipage}
  10715. The temporary variable \code{t1} gets the value of \code{x} before the
  10716. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10717. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10718. do not generate a temporary variable for the occurrence of \code{y}
  10719. because it's an immutable variable. We want to avoid such unnecessary
  10720. extra temporaries because they would needlessly increase the number of
  10721. variables, making it more likely for some of them to be spilled. The
  10722. result of this program is \code{42}, the same as the result prior to
  10723. \code{remove\_complex\_operands}.
  10724. The approach that we've sketched requires only a small
  10725. modification to \code{remove\_complex\_operands} to handle
  10726. \code{get!}. However, it requires a new pass, called
  10727. \code{uncover-get!}, that we discuss in
  10728. section~\ref{sec:uncover-get-bang}.
  10729. As an aside, this problematic interaction between \code{set!} and the
  10730. pass \code{remove\_complex\_operands} is particular to Racket and not
  10731. its predecessor, the Scheme language. The key difference is that
  10732. Scheme does not specify an order of evaluation for the arguments of an
  10733. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10734. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10735. would be correct results for the example program. Interestingly,
  10736. Racket is implemented on top of the Chez Scheme
  10737. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10738. presented in this section (using extra \code{let} bindings to control
  10739. the order of evaluation) is used in the translation from Racket to
  10740. Scheme~\citep{Flatt:2019tb}.
  10741. \fi} % racket
  10742. Having discussed the complications that arise from adding support for
  10743. assignment and loops, we turn to discussing the individual compilation
  10744. passes.
  10745. {\if\edition\racketEd
  10746. \section{Uncover \texttt{get!}}
  10747. \label{sec:uncover-get-bang}
  10748. The goal of this pass is to mark uses of mutable variables so that
  10749. \code{remove\_complex\_operands} can treat them as complex expressions
  10750. and thereby preserve their ordering relative to the side effects in
  10751. other operands. So, the first step is to collect all the mutable
  10752. variables. We recommend creating an auxiliary function for this,
  10753. named \code{collect-set!}, that recursively traverses expressions,
  10754. returning the set of all variables that occur on the left-hand side of a
  10755. \code{set!}. Here's an excerpt of its implementation.
  10756. \begin{center}
  10757. \begin{minipage}{\textwidth}
  10758. \begin{lstlisting}
  10759. (define (collect-set! e)
  10760. (match e
  10761. [(Var x) (set)]
  10762. [(Int n) (set)]
  10763. [(Let x rhs body)
  10764. (set-union (collect-set! rhs) (collect-set! body))]
  10765. [(SetBang var rhs)
  10766. (set-union (set var) (collect-set! rhs))]
  10767. ...))
  10768. \end{lstlisting}
  10769. \end{minipage}
  10770. \end{center}
  10771. By placing this pass after \code{uniquify}, we need not worry about
  10772. variable shadowing, and our logic for \code{Let} can remain simple, as
  10773. in this excerpt.
  10774. The second step is to mark the occurrences of the mutable variables
  10775. with the new \code{GetBang} AST node (\code{get!} in concrete
  10776. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10777. function, which takes two parameters: the set of mutable variables
  10778. \code{set!-vars} and the expression \code{e} to be processed. The
  10779. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10780. mutable variable or leaves it alone if not.
  10781. \begin{center}
  10782. \begin{minipage}{\textwidth}
  10783. \begin{lstlisting}
  10784. (define ((uncover-get!-exp set!-vars) e)
  10785. (match e
  10786. [(Var x)
  10787. (if (set-member? set!-vars x)
  10788. (GetBang x)
  10789. (Var x))]
  10790. ...))
  10791. \end{lstlisting}
  10792. \end{minipage}
  10793. \end{center}
  10794. To wrap things up, define the \code{uncover-get!} function for
  10795. processing a whole program, using \code{collect-set!} to obtain the
  10796. set of mutable variables and then \code{uncover-get!-exp} to replace
  10797. their occurrences with \code{GetBang}.
  10798. \fi}
  10799. \section{Remove Complex Operands}
  10800. \label{sec:rco-loop}
  10801. {\if\edition\racketEd
  10802. %
  10803. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10804. \code{while} are all complex expressions. The subexpressions of
  10805. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10806. %
  10807. \fi}
  10808. {\if\edition\pythonEd\pythonColor
  10809. %
  10810. The change needed for this pass is to add a case for the \code{while}
  10811. statement. The condition of a \code{while} loop is allowed to be a
  10812. complex expression, just like the condition of the \code{if}
  10813. statement.
  10814. %
  10815. \fi}
  10816. %
  10817. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10818. \LangLoopANF{} of this pass.
  10819. \newcommand{\LwhileMonadASTRacket}{
  10820. \begin{array}{rcl}
  10821. \Atm &::=& \VOID{} \\
  10822. \Exp &::=& \GETBANG{\Var}
  10823. \MID \SETBANG{\Var}{\Exp}
  10824. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10825. &\MID& \WHILE{\Exp}{\Exp}
  10826. \end{array}
  10827. }
  10828. \newcommand{\LwhileMonadASTPython}{
  10829. \begin{array}{rcl}
  10830. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10831. \end{array}
  10832. }
  10833. \begin{figure}[tp]
  10834. \centering
  10835. \begin{tcolorbox}[colback=white]
  10836. \small
  10837. {\if\edition\racketEd
  10838. \[
  10839. \begin{array}{l}
  10840. \gray{\LvarMonadASTRacket} \\ \hline
  10841. \gray{\LifMonadASTRacket} \\ \hline
  10842. \LwhileMonadASTRacket \\
  10843. \begin{array}{rcl}
  10844. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10845. \end{array}
  10846. \end{array}
  10847. \]
  10848. \fi}
  10849. {\if\edition\pythonEd\pythonColor
  10850. \[
  10851. \begin{array}{l}
  10852. \gray{\LvarMonadASTPython} \\ \hline
  10853. \gray{\LifMonadASTPython} \\ \hline
  10854. \LwhileMonadASTPython \\
  10855. \begin{array}{rcl}
  10856. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10857. \end{array}
  10858. \end{array}
  10859. %% \begin{array}{rcl}
  10860. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10861. %% \Exp &::=& \Atm \MID \READ{} \\
  10862. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10863. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10864. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10865. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10866. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10867. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10868. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10869. %% \end{array}
  10870. \]
  10871. \fi}
  10872. \end{tcolorbox}
  10873. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10874. \label{fig:Lwhile-anf-syntax}
  10875. \end{figure}
  10876. {\if\edition\racketEd
  10877. %
  10878. As usual, when a complex expression appears in a grammar position that
  10879. needs to be atomic, such as the argument of a primitive operator, we
  10880. must introduce a temporary variable and bind it to the complex
  10881. expression. This approach applies, unchanged, to handle the new
  10882. language forms. For example, in the following code there are two
  10883. \code{begin} expressions appearing as arguments to the \code{+}
  10884. operator. The output of \code{rco\_exp} is then shown, in which the
  10885. \code{begin} expressions have been bound to temporary
  10886. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10887. allowed to have arbitrary expressions in their right-hand side
  10888. expression, so it is fine to place \code{begin} there.
  10889. %
  10890. \begin{center}
  10891. \begin{tabular}{lcl}
  10892. \begin{minipage}{0.4\textwidth}
  10893. \begin{lstlisting}
  10894. (let ([x2 10])
  10895. (let ([y3 0])
  10896. (+ (+ (begin
  10897. (set! y3 (read))
  10898. (get! x2))
  10899. (begin
  10900. (set! x2 (read))
  10901. (get! y3)))
  10902. (get! x2))))
  10903. \end{lstlisting}
  10904. \end{minipage}
  10905. &
  10906. $\Rightarrow$
  10907. &
  10908. \begin{minipage}{0.4\textwidth}
  10909. \begin{lstlisting}
  10910. (let ([x2 10])
  10911. (let ([y3 0])
  10912. (let ([tmp4 (begin
  10913. (set! y3 (read))
  10914. x2)])
  10915. (let ([tmp5 (begin
  10916. (set! x2 (read))
  10917. y3)])
  10918. (let ([tmp6 (+ tmp4 tmp5)])
  10919. (let ([tmp7 x2])
  10920. (+ tmp6 tmp7)))))))
  10921. \end{lstlisting}
  10922. \end{minipage}
  10923. \end{tabular}
  10924. \end{center}
  10925. \fi}
  10926. \section{Explicate Control \racket{and \LangCLoop{}}}
  10927. \label{sec:explicate-loop}
  10928. \newcommand{\CloopASTRacket}{
  10929. \begin{array}{lcl}
  10930. \Atm &::=& \VOID \\
  10931. \Stmt &::=& \READ{}
  10932. \end{array}
  10933. }
  10934. {\if\edition\racketEd
  10935. Recall that in the \code{explicate\_control} pass we define one helper
  10936. function for each kind of position in the program. For the \LangVar{}
  10937. language of integers and variables, we needed assignment and tail
  10938. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10939. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10940. another kind of position: effect position. Except for the last
  10941. subexpression, the subexpressions inside a \code{begin} are evaluated
  10942. only for their effect. Their result values are discarded. We can
  10943. generate better code by taking this fact into account.
  10944. The output language of \code{explicate\_control} is \LangCLoop{}
  10945. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10946. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10947. and that \code{read} may appear as a statement. The most significant
  10948. difference between the programs generated by \code{explicate\_control}
  10949. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10950. chapter is that the control-flow graphs of the latter may contain
  10951. cycles.
  10952. \begin{figure}[tp]
  10953. \begin{tcolorbox}[colback=white]
  10954. \small
  10955. \[
  10956. \begin{array}{l}
  10957. \gray{\CvarASTRacket} \\ \hline
  10958. \gray{\CifASTRacket} \\ \hline
  10959. \CloopASTRacket \\
  10960. \begin{array}{lcl}
  10961. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10962. \end{array}
  10963. \end{array}
  10964. \]
  10965. \end{tcolorbox}
  10966. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10967. \label{fig:c7-syntax}
  10968. \end{figure}
  10969. The new auxiliary function \code{explicate\_effect} takes an
  10970. expression (in an effect position) and the code for its
  10971. continuation. The function returns a $\Tail$ that includes the
  10972. generated code for the input expression followed by the
  10973. continuation. If the expression is obviously pure, that is, never
  10974. causes side effects, then the expression can be removed, so the result
  10975. is just the continuation.
  10976. %
  10977. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10978. interesting; the generated code is depicted in the following diagram:
  10979. \begin{center}
  10980. \begin{minipage}{0.3\textwidth}
  10981. \xymatrix{
  10982. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10983. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10984. & *+[F]{\txt{\itm{cont}}} \\
  10985. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10986. }
  10987. \end{minipage}
  10988. \end{center}
  10989. We start by creating a fresh label $\itm{loop}$ for the top of the
  10990. loop. Next, recursively process the \itm{body} (in effect position)
  10991. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10992. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10993. \itm{body'} as the \emph{then} branch and the continuation block as the
  10994. \emph{else} branch. The result should be added to the dictionary of
  10995. \code{basic-blocks} with the label \itm{loop}. The result for the
  10996. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10997. The auxiliary functions for tail, assignment, and predicate positions
  10998. need to be updated. The three new language forms, \code{while},
  10999. \code{set!}, and \code{begin}, can appear in assignment and tail
  11000. positions. Only \code{begin} may appear in predicate positions; the
  11001. other two have result type \code{Void}.
  11002. \fi}
  11003. %
  11004. {\if\edition\pythonEd\pythonColor
  11005. %
  11006. The output of this pass is the language \LangCIf{}. No new language
  11007. features are needed in the output, because a \code{while} loop can be
  11008. expressed in terms of \code{goto} and \code{if} statements, which are
  11009. already in \LangCIf{}.
  11010. %
  11011. Add a case for the \code{while} statement to the
  11012. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11013. the condition expression.
  11014. %
  11015. \fi}
  11016. {\if\edition\racketEd
  11017. \section{Select Instructions}
  11018. \label{sec:select-instructions-loop}
  11019. \index{subject}{select instructions}
  11020. Only two small additions are needed in the \code{select\_instructions}
  11021. pass to handle the changes to \LangCLoop{}. First, to handle the
  11022. addition of \VOID{} we simply translate it to \code{0}. Second,
  11023. \code{read} may appear as a stand-alone statement instead of
  11024. appearing only on the right-hand side of an assignment statement. The code
  11025. generation is nearly identical to the one for assignment; just leave
  11026. off the instruction for moving the result into the left-hand side.
  11027. \fi}
  11028. \section{Register Allocation}
  11029. \label{sec:register-allocation-loop}
  11030. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11031. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11032. which complicates the liveness analysis needed for register
  11033. allocation.
  11034. %
  11035. We recommend using the generic \code{analyze\_dataflow} function that
  11036. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11037. perform liveness analysis, replacing the code in
  11038. \code{uncover\_live} that processed the basic blocks in topological
  11039. order (section~\ref{sec:liveness-analysis-Lif}).
  11040. The \code{analyze\_dataflow} function has the following four parameters.
  11041. \begin{enumerate}
  11042. \item The first parameter \code{G} should be passed the transpose
  11043. of the control-flow graph.
  11044. \item The second parameter \code{transfer} should be passed a function
  11045. that applies liveness analysis to a basic block. It takes two
  11046. parameters: the label for the block to analyze and the live-after
  11047. set for that block. The transfer function should return the
  11048. live-before set for the block.
  11049. %
  11050. \racket{Also, as a side effect, it should update the block's
  11051. $\itm{info}$ with the liveness information for each instruction.}
  11052. %
  11053. \python{Also, as a side effect, it should update the live-before and
  11054. live-after sets for each instruction.}
  11055. %
  11056. To implement the \code{transfer} function, you should be able to
  11057. reuse the code you already have for analyzing basic blocks.
  11058. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11059. \code{bottom} and \code{join} for the lattice of abstract states,
  11060. that is, sets of locations. For liveness analysis, the bottom of the
  11061. lattice is the empty set, and the join operator is set union.
  11062. \end{enumerate}
  11063. \begin{figure}[tp]
  11064. \begin{tcolorbox}[colback=white]
  11065. {\if\edition\racketEd
  11066. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11067. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11068. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11069. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11070. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11071. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11072. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11073. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11074. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11075. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11076. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11077. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11078. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11079. \path[->,bend left=15] (Lfun) edge [above] node
  11080. {\ttfamily\footnotesize shrink} (Lfun-2);
  11081. \path[->,bend left=15] (Lfun-2) edge [above] node
  11082. {\ttfamily\footnotesize uniquify} (F1-4);
  11083. \path[->,bend left=15] (F1-4) edge [above] node
  11084. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11085. \path[->,bend left=15] (F1-5) edge [left] node
  11086. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11087. \path[->,bend left=10] (F1-6) edge [above] node
  11088. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11089. \path[->,bend left=15] (C3-2) edge [right] node
  11090. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11091. \path[->,bend right=15] (x86-2) edge [right] node
  11092. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11093. \path[->,bend right=15] (x86-2-1) edge [below] node
  11094. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11095. \path[->,bend right=15] (x86-2-2) edge [right] node
  11096. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11097. \path[->,bend left=15] (x86-3) edge [above] node
  11098. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11099. \path[->,bend left=15] (x86-4) edge [right] node
  11100. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11101. \end{tikzpicture}
  11102. \fi}
  11103. {\if\edition\pythonEd\pythonColor
  11104. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11105. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11106. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11107. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11108. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11109. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11110. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11111. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11112. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11113. \path[->,bend left=15] (Lfun) edge [above] node
  11114. {\ttfamily\footnotesize shrink} (Lfun-2);
  11115. \path[->,bend left=15] (Lfun-2) edge [above] node
  11116. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11117. \path[->,bend left=10] (F1-6) edge [right] node
  11118. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11119. \path[->,bend right=15] (C3-2) edge [right] node
  11120. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11121. \path[->,bend right=15] (x86-2) edge [below] node
  11122. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11123. \path[->,bend left=15] (x86-3) edge [above] node
  11124. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11125. \path[->,bend right=15] (x86-4) edge [below] node
  11126. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11127. \end{tikzpicture}
  11128. \fi}
  11129. \end{tcolorbox}
  11130. \caption{Diagram of the passes for \LangLoop{}.}
  11131. \label{fig:Lwhile-passes}
  11132. \end{figure}
  11133. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11134. for the compilation of \LangLoop{}.
  11135. % Further Reading: dataflow analysis
  11136. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11137. \chapter{Tuples and Garbage Collection}
  11138. \label{ch:Lvec}
  11139. \index{subject}{tuple}
  11140. \index{subject}{vector}
  11141. \setcounter{footnote}{0}
  11142. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11143. %% all the IR grammars are spelled out! \\ --Jeremy}
  11144. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11145. %% the root stack. \\ --Jeremy}
  11146. In this chapter we study the implementation of tuples\racket{, called
  11147. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11148. in which each element may have a different type.
  11149. %
  11150. This language feature is the first to use the computer's
  11151. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11152. indefinite; that is, a tuple lives forever from the programmer's
  11153. viewpoint. Of course, from an implementer's viewpoint, it is important
  11154. to reclaim the space associated with a tuple when it is no longer
  11155. needed, which is why we also study \emph{garbage collection}
  11156. \index{subject}{garbage collection} techniques in this chapter.
  11157. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11158. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11159. language (chapter~\ref{ch:Lwhile}) with tuples.
  11160. %
  11161. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11162. copying live tuples back and forth between two halves of the heap. The
  11163. garbage collector requires coordination with the compiler so that it
  11164. can find all the live tuples.
  11165. %
  11166. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11167. discuss the necessary changes and additions to the compiler passes,
  11168. including a new compiler pass named \code{expose\_allocation}.
  11169. \section{The \LangVec{} Language}
  11170. \label{sec:r3}
  11171. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11172. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11173. the definition of the abstract syntax.
  11174. %
  11175. \racket{The \LangVec{} language includes the forms \code{vector} for
  11176. creating a tuple, \code{vector-ref} for reading an element of a
  11177. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11178. \code{vector-length} for obtaining the number of elements of a
  11179. tuple.}
  11180. %
  11181. \python{The \LangVec{} language adds (1) tuple creation via a
  11182. comma-separated list of expressions; (2) accessing an element of a
  11183. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11184. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11185. comparison operator; and (4) obtaining the number of elements (the
  11186. length) of a tuple. In this chapter, we restrict access indices to
  11187. constant integers.}
  11188. %
  11189. The following program shows an example of the use of tuples. It creates a tuple
  11190. \code{t} containing the elements \code{40},
  11191. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11192. contains just \code{2}. The element at index $1$ of \code{t} is
  11193. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11194. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11195. to which we add \code{2}, the element at index $0$ of the tuple.
  11196. The result of the program is \code{42}.
  11197. %
  11198. {\if\edition\racketEd
  11199. \begin{lstlisting}
  11200. (let ([t (vector 40 #t (vector 2))])
  11201. (if (vector-ref t 1)
  11202. (+ (vector-ref t 0)
  11203. (vector-ref (vector-ref t 2) 0))
  11204. 44))
  11205. \end{lstlisting}
  11206. \fi}
  11207. {\if\edition\pythonEd\pythonColor
  11208. \begin{lstlisting}
  11209. t = 40, True, (2,)
  11210. print(t[0] + t[2][0] if t[1] else 44)
  11211. \end{lstlisting}
  11212. \fi}
  11213. \newcommand{\LtupGrammarRacket}{
  11214. \begin{array}{lcl}
  11215. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11216. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11217. \MID \LP\key{vector-length}\;\Exp\RP \\
  11218. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11219. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11220. \end{array}
  11221. }
  11222. \newcommand{\LtupASTRacket}{
  11223. \begin{array}{lcl}
  11224. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11225. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11226. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11227. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11228. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11229. \end{array}
  11230. }
  11231. \newcommand{\LtupGrammarPython}{
  11232. \begin{array}{rcl}
  11233. \itm{cmp} &::= & \key{is} \\
  11234. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11235. \end{array}
  11236. }
  11237. \newcommand{\LtupASTPython}{
  11238. \begin{array}{lcl}
  11239. \itm{cmp} &::= & \code{Is()} \\
  11240. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11241. &\MID& \LEN{\Exp}
  11242. \end{array}
  11243. }
  11244. \begin{figure}[tbp]
  11245. \centering
  11246. \begin{tcolorbox}[colback=white]
  11247. \small
  11248. {\if\edition\racketEd
  11249. \[
  11250. \begin{array}{l}
  11251. \gray{\LintGrammarRacket{}} \\ \hline
  11252. \gray{\LvarGrammarRacket{}} \\ \hline
  11253. \gray{\LifGrammarRacket{}} \\ \hline
  11254. \gray{\LwhileGrammarRacket} \\ \hline
  11255. \LtupGrammarRacket \\
  11256. \begin{array}{lcl}
  11257. \LangVecM{} &::=& \Exp
  11258. \end{array}
  11259. \end{array}
  11260. \]
  11261. \fi}
  11262. {\if\edition\pythonEd\pythonColor
  11263. \[
  11264. \begin{array}{l}
  11265. \gray{\LintGrammarPython{}} \\ \hline
  11266. \gray{\LvarGrammarPython{}} \\ \hline
  11267. \gray{\LifGrammarPython{}} \\ \hline
  11268. \gray{\LwhileGrammarPython} \\ \hline
  11269. \LtupGrammarPython \\
  11270. \begin{array}{rcl}
  11271. \LangVecM{} &::=& \Stmt^{*}
  11272. \end{array}
  11273. \end{array}
  11274. \]
  11275. \fi}
  11276. \end{tcolorbox}
  11277. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11278. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11279. \label{fig:Lvec-concrete-syntax}
  11280. \end{figure}
  11281. \begin{figure}[tp]
  11282. \centering
  11283. \begin{tcolorbox}[colback=white]
  11284. \small
  11285. {\if\edition\racketEd
  11286. \[
  11287. \begin{array}{l}
  11288. \gray{\LintOpAST} \\ \hline
  11289. \gray{\LvarASTRacket{}} \\ \hline
  11290. \gray{\LifASTRacket{}} \\ \hline
  11291. \gray{\LwhileASTRacket{}} \\ \hline
  11292. \LtupASTRacket{} \\
  11293. \begin{array}{lcl}
  11294. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11295. \end{array}
  11296. \end{array}
  11297. \]
  11298. \fi}
  11299. {\if\edition\pythonEd\pythonColor
  11300. \[
  11301. \begin{array}{l}
  11302. \gray{\LintASTPython} \\ \hline
  11303. \gray{\LvarASTPython} \\ \hline
  11304. \gray{\LifASTPython} \\ \hline
  11305. \gray{\LwhileASTPython} \\ \hline
  11306. \LtupASTPython \\
  11307. \begin{array}{lcl}
  11308. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11309. \end{array}
  11310. \end{array}
  11311. \]
  11312. \fi}
  11313. \end{tcolorbox}
  11314. \caption{The abstract syntax of \LangVec{}.}
  11315. \label{fig:Lvec-syntax}
  11316. \end{figure}
  11317. Tuples raise several interesting new issues. First, variable binding
  11318. performs a shallow copy in dealing with tuples, which means that
  11319. different variables can refer to the same tuple; that is, two
  11320. variables can be \emph{aliases}\index{subject}{alias} for the same
  11321. entity. Consider the following example, in which \code{t1} and
  11322. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11323. different tuple value with equal elements. The result of the
  11324. program is \code{42}.
  11325. \begin{center}
  11326. \begin{minipage}{0.96\textwidth}
  11327. {\if\edition\racketEd
  11328. \begin{lstlisting}
  11329. (let ([t1 (vector 3 7)])
  11330. (let ([t2 t1])
  11331. (let ([t3 (vector 3 7)])
  11332. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11333. 42
  11334. 0))))
  11335. \end{lstlisting}
  11336. \fi}
  11337. {\if\edition\pythonEd\pythonColor
  11338. \begin{lstlisting}
  11339. t1 = 3, 7
  11340. t2 = t1
  11341. t3 = 3, 7
  11342. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11343. \end{lstlisting}
  11344. \fi}
  11345. \end{minipage}
  11346. \end{center}
  11347. {\if\edition\racketEd
  11348. Whether two variables are aliased or not affects what happens
  11349. when the underlying tuple is mutated\index{subject}{mutation}.
  11350. Consider the following example in which \code{t1} and \code{t2}
  11351. again refer to the same tuple value.
  11352. \begin{center}
  11353. \begin{minipage}{0.96\textwidth}
  11354. \begin{lstlisting}
  11355. (let ([t1 (vector 3 7)])
  11356. (let ([t2 t1])
  11357. (let ([_ (vector-set! t2 0 42)])
  11358. (vector-ref t1 0))))
  11359. \end{lstlisting}
  11360. \end{minipage}
  11361. \end{center}
  11362. The mutation through \code{t2} is visible in referencing the tuple
  11363. from \code{t1}, so the result of this program is \code{42}.
  11364. \fi}
  11365. The next issue concerns the lifetime of tuples. When does a tuple's
  11366. lifetime end? Notice that \LangVec{} does not include an operation
  11367. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11368. to any notion of static scoping.
  11369. %
  11370. {\if\edition\racketEd
  11371. %
  11372. For example, the following program returns \code{42} even though the
  11373. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11374. that reads from the vector to which it was bound.
  11375. \begin{center}
  11376. \begin{minipage}{0.96\textwidth}
  11377. \begin{lstlisting}
  11378. (let ([v (vector (vector 44))])
  11379. (let ([x (let ([w (vector 42)])
  11380. (let ([_ (vector-set! v 0 w)])
  11381. 0))])
  11382. (+ x (vector-ref (vector-ref v 0) 0))))
  11383. \end{lstlisting}
  11384. \end{minipage}
  11385. \end{center}
  11386. \fi}
  11387. %
  11388. {\if\edition\pythonEd\pythonColor
  11389. %
  11390. For example, the following program returns \code{42} even though the
  11391. variable \code{x} goes out of scope when the function returns, prior
  11392. to reading the tuple element at index $0$. (We study the compilation
  11393. of functions in chapter~\ref{ch:Lfun}.)
  11394. %
  11395. \begin{center}
  11396. \begin{minipage}{0.96\textwidth}
  11397. \begin{lstlisting}
  11398. def f():
  11399. x = 42, 43
  11400. return x
  11401. t = f()
  11402. print(t[0])
  11403. \end{lstlisting}
  11404. \end{minipage}
  11405. \end{center}
  11406. \fi}
  11407. %
  11408. From the perspective of programmer-observable behavior, tuples live
  11409. forever. However, if they really lived forever then many long-running
  11410. programs would run out of memory. To solve this problem, the
  11411. language's runtime system performs automatic garbage collection.
  11412. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11413. \LangVec{} language.
  11414. %
  11415. \racket{We define the \code{vector}, \code{vector-ref},
  11416. \code{vector-set!}, and \code{vector-length} operations for
  11417. \LangVec{} in terms of the corresponding operations in Racket. One
  11418. subtle point is that the \code{vector-set!} operation returns the
  11419. \code{\#<void>} value.}
  11420. %
  11421. \python{We represent tuples with Python lists in the interpreter
  11422. because we need to write to them
  11423. (section~\ref{sec:expose-allocation}). (Python tuples are
  11424. immutable.) We define element access, the \code{is} operator, and
  11425. the \code{len} operator for \LangVec{} in terms of the corresponding
  11426. operations in Python.}
  11427. \begin{figure}[tbp]
  11428. \begin{tcolorbox}[colback=white]
  11429. {\if\edition\racketEd
  11430. \begin{lstlisting}
  11431. (define interp-Lvec-class
  11432. (class interp-Lwhile-class
  11433. (super-new)
  11434. (define/override (interp-op op)
  11435. (match op
  11436. ['eq? (lambda (v1 v2)
  11437. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11438. (and (boolean? v1) (boolean? v2))
  11439. (and (vector? v1) (vector? v2))
  11440. (and (void? v1) (void? v2)))
  11441. (eq? v1 v2)]))]
  11442. ['vector vector]
  11443. ['vector-length vector-length]
  11444. ['vector-ref vector-ref]
  11445. ['vector-set! vector-set!]
  11446. [else (super interp-op op)]
  11447. ))
  11448. (define/override ((interp-exp env) e)
  11449. (match e
  11450. [(HasType e t) ((interp-exp env) e)]
  11451. [else ((super interp-exp env) e)]
  11452. ))
  11453. ))
  11454. (define (interp-Lvec p)
  11455. (send (new interp-Lvec-class) interp-program p))
  11456. \end{lstlisting}
  11457. \fi}
  11458. %
  11459. {\if\edition\pythonEd\pythonColor
  11460. \begin{lstlisting}
  11461. class InterpLtup(InterpLwhile):
  11462. def interp_cmp(self, cmp):
  11463. match cmp:
  11464. case Is():
  11465. return lambda x, y: x is y
  11466. case _:
  11467. return super().interp_cmp(cmp)
  11468. def interp_exp(self, e, env):
  11469. match e:
  11470. case Tuple(es, Load()):
  11471. return tuple([self.interp_exp(e, env) for e in es])
  11472. case Subscript(tup, index, Load()):
  11473. t = self.interp_exp(tup, env)
  11474. n = self.interp_exp(index, env)
  11475. return t[n]
  11476. case _:
  11477. return super().interp_exp(e, env)
  11478. \end{lstlisting}
  11479. \fi}
  11480. \end{tcolorbox}
  11481. \caption{Interpreter for the \LangVec{} language.}
  11482. \label{fig:interp-Lvec}
  11483. \end{figure}
  11484. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11485. \LangVec{}.
  11486. %
  11487. The type of a tuple is a
  11488. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11489. type for each of its elements.
  11490. %
  11491. \racket{To create the s-expression for the \code{Vector} type, we use the
  11492. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11493. operator} \code{,@} to insert the list \code{t*} without its usual
  11494. start and end parentheses. \index{subject}{unquote-splicing}}
  11495. %
  11496. The type of accessing the ith element of a tuple is the ith element
  11497. type of the tuple's type, if there is one. If not, an error is
  11498. signaled. Note that the index \code{i} is required to be a constant
  11499. integer (and not, for example, a call to
  11500. \racket{\code{read}}\python{input\_int}) so that the type checker
  11501. can determine the element's type given the tuple type.
  11502. %
  11503. \racket{
  11504. Regarding writing an element to a tuple, the element's type must
  11505. be equal to the ith element type of the tuple's type.
  11506. The result type is \code{Void}.}
  11507. %% When allocating a tuple,
  11508. %% we need to know which elements of the tuple are themselves tuples for
  11509. %% the purposes of garbage collection. We can obtain this information
  11510. %% during type checking. The type checker shown in
  11511. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11512. %% expression; it also
  11513. %% %
  11514. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11515. %% where $T$ is the tuple's type.
  11516. %
  11517. %records the type of each tuple expression in a new field named \code{has\_type}.
  11518. \begin{figure}[tp]
  11519. \begin{tcolorbox}[colback=white]
  11520. {\if\edition\racketEd
  11521. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11522. (define type-check-Lvec-class
  11523. (class type-check-Lif-class
  11524. (super-new)
  11525. (inherit check-type-equal?)
  11526. (define/override (type-check-exp env)
  11527. (lambda (e)
  11528. (define recur (type-check-exp env))
  11529. (match e
  11530. [(Prim 'vector es)
  11531. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11532. (define t `(Vector ,@t*))
  11533. (values (Prim 'vector e*) t)]
  11534. [(Prim 'vector-ref (list e1 (Int i)))
  11535. (define-values (e1^ t) (recur e1))
  11536. (match t
  11537. [`(Vector ,ts ...)
  11538. (unless (and (0 . <= . i) (i . < . (length ts)))
  11539. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11540. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11541. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11542. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11543. (define-values (e-vec t-vec) (recur e1))
  11544. (define-values (e-elt^ t-elt) (recur elt))
  11545. (match t-vec
  11546. [`(Vector ,ts ...)
  11547. (unless (and (0 . <= . i) (i . < . (length ts)))
  11548. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11549. (check-type-equal? (list-ref ts i) t-elt e)
  11550. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11551. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11552. [(Prim 'vector-length (list e))
  11553. (define-values (e^ t) (recur e))
  11554. (match t
  11555. [`(Vector ,ts ...)
  11556. (values (Prim 'vector-length (list e^)) 'Integer)]
  11557. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11558. [(Prim 'eq? (list arg1 arg2))
  11559. (define-values (e1 t1) (recur arg1))
  11560. (define-values (e2 t2) (recur arg2))
  11561. (match* (t1 t2)
  11562. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11563. [(other wise) (check-type-equal? t1 t2 e)])
  11564. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11565. [else ((super type-check-exp env) e)]
  11566. )))
  11567. ))
  11568. (define (type-check-Lvec p)
  11569. (send (new type-check-Lvec-class) type-check-program p))
  11570. \end{lstlisting}
  11571. \fi}
  11572. {\if\edition\pythonEd\pythonColor
  11573. \begin{lstlisting}
  11574. class TypeCheckLtup(TypeCheckLwhile):
  11575. def type_check_exp(self, e, env):
  11576. match e:
  11577. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11578. l = self.type_check_exp(left, env)
  11579. r = self.type_check_exp(right, env)
  11580. check_type_equal(l, r, e)
  11581. return bool
  11582. case Tuple(es, Load()):
  11583. ts = [self.type_check_exp(e, env) for e in es]
  11584. e.has_type = TupleType(ts)
  11585. return e.has_type
  11586. case Subscript(tup, Constant(i), Load()):
  11587. tup_ty = self.type_check_exp(tup, env)
  11588. i_ty = self.type_check_exp(Constant(i), env)
  11589. check_type_equal(i_ty, int, i)
  11590. match tup_ty:
  11591. case TupleType(ts):
  11592. return ts[i]
  11593. case _:
  11594. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11595. case _:
  11596. return super().type_check_exp(e, env)
  11597. \end{lstlisting}
  11598. \fi}
  11599. \end{tcolorbox}
  11600. \caption{Type checker for the \LangVec{} language.}
  11601. \label{fig:type-check-Lvec}
  11602. \end{figure}
  11603. \section{Garbage Collection}
  11604. \label{sec:GC}
  11605. Garbage collection is a runtime technique for reclaiming space on the
  11606. heap that will not be used in the future of the running program. We
  11607. use the term \emph{object}\index{subject}{object} to refer to any
  11608. value that is stored in the heap, which for now includes only
  11609. tuples.%
  11610. %
  11611. \footnote{The term \emph{object} as it is used in the context of
  11612. object-oriented programming has a more specific meaning than the
  11613. way in which we use the term here.}
  11614. %
  11615. Unfortunately, it is impossible to know precisely which objects will
  11616. be accessed in the future and which will not. Instead, garbage
  11617. collectors overapproximate the set of objects that will be accessed by
  11618. identifying which objects can possibly be accessed. The running
  11619. program can directly access objects that are in registers and on the
  11620. procedure call stack. It can also transitively access the elements of
  11621. tuples, starting with a tuple whose address is in a register or on the
  11622. procedure call stack. We define the \emph{root
  11623. set}\index{subject}{root set} to be all the tuple addresses that are
  11624. in registers or on the procedure call stack. We define the \emph{live
  11625. objects}\index{subject}{live objects} to be the objects that are
  11626. reachable from the root set. Garbage collectors reclaim the space that
  11627. is allocated to objects that are no longer live. \index{subject}{allocate}
  11628. That means that some objects may not get reclaimed as soon as they could be,
  11629. but at least
  11630. garbage collectors do not reclaim the space dedicated to objects that
  11631. will be accessed in the future! The programmer can influence which
  11632. objects get reclaimed by causing them to become unreachable.
  11633. So the goal of the garbage collector is twofold:
  11634. \begin{enumerate}
  11635. \item to preserve all the live objects, and
  11636. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11637. \end{enumerate}
  11638. \subsection{Two-Space Copying Collector}
  11639. Here we study a relatively simple algorithm for garbage collection
  11640. that is the basis of many state-of-the-art garbage
  11641. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11642. particular, we describe a two-space copying
  11643. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11644. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11645. collector} \index{subject}{two-space copying collector}
  11646. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11647. what happens in a two-space collector, showing two time steps, prior
  11648. to garbage collection (on the top) and after garbage collection (on
  11649. the bottom). In a two-space collector, the heap is divided into two
  11650. parts named the FromSpace\index{subject}{FromSpace} and the
  11651. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11652. FromSpace until there is not enough room for the next allocation
  11653. request. At that point, the garbage collector goes to work to make
  11654. room for the next allocation.
  11655. A copying collector makes more room by copying all the live objects
  11656. from the FromSpace into the ToSpace and then performs a sleight of
  11657. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11658. as the new ToSpace. In the example shown in
  11659. figure~\ref{fig:copying-collector}, the root set consists of three
  11660. pointers, one in a register and two on the stack. All the live
  11661. objects have been copied to the ToSpace (the right-hand side of
  11662. figure~\ref{fig:copying-collector}) in a way that preserves the
  11663. pointer relationships. For example, the pointer in the register still
  11664. points to a tuple that in turn points to two other tuples. There are
  11665. four tuples that are not reachable from the root set and therefore do
  11666. not get copied into the ToSpace.
  11667. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11668. created by a well-typed program in \LangVec{} because it contains a
  11669. cycle. However, creating cycles will be possible once we get to
  11670. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11671. to deal with cycles to begin with, so we will not need to revisit this
  11672. issue.
  11673. \begin{figure}[tbp]
  11674. \centering
  11675. \begin{tcolorbox}[colback=white]
  11676. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11677. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11678. \\[5ex]
  11679. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11680. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11681. \end{tcolorbox}
  11682. \caption{A copying collector in action.}
  11683. \label{fig:copying-collector}
  11684. \end{figure}
  11685. \subsection{Graph Copying via Cheney's Algorithm}
  11686. \label{sec:cheney}
  11687. \index{subject}{Cheney's algorithm}
  11688. Let us take a closer look at the copying of the live objects. The
  11689. allocated\index{subject}{allocate} objects and pointers can be viewed
  11690. as a graph, and we need to copy the part of the graph that is
  11691. reachable from the root set. To make sure that we copy all the
  11692. reachable vertices in the graph, we need an exhaustive graph traversal
  11693. algorithm, such as depth-first search or breadth-first
  11694. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11695. take into account the possibility of cycles by marking which vertices
  11696. have already been visited, so to ensure termination of the
  11697. algorithm. These search algorithms also use a data structure such as a
  11698. stack or queue as a to-do list to keep track of the vertices that need
  11699. to be visited. We use breadth-first search and a trick due to
  11700. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11701. copying tuples into the ToSpace.
  11702. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11703. copy progresses. The queue is represented by a chunk of contiguous
  11704. memory at the beginning of the ToSpace, using two pointers to track
  11705. the front and the back of the queue, called the \emph{free pointer}
  11706. and the \emph{scan pointer}, respectively. The algorithm starts by
  11707. copying all tuples that are immediately reachable from the root set
  11708. into the ToSpace to form the initial queue. When we copy a tuple, we
  11709. mark the old tuple to indicate that it has been visited. We discuss
  11710. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11711. that any pointers inside the copied tuples in the queue still point
  11712. back to the FromSpace. Once the initial queue has been created, the
  11713. algorithm enters a loop in which it repeatedly processes the tuple at
  11714. the front of the queue and pops it off the queue. To process a tuple,
  11715. the algorithm copies all the objects that are directly reachable from it
  11716. to the ToSpace, placing them at the back of the queue. The algorithm
  11717. then updates the pointers in the popped tuple so that they point to the
  11718. newly copied objects.
  11719. \begin{figure}[tbp]
  11720. \centering
  11721. \begin{tcolorbox}[colback=white]
  11722. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11723. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11724. \end{tcolorbox}
  11725. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11726. \label{fig:cheney}
  11727. \end{figure}
  11728. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11729. tuple whose second element is $42$ to the back of the queue. The other
  11730. pointer goes to a tuple that has already been copied, so we do not
  11731. need to copy it again, but we do need to update the pointer to the new
  11732. location. This can be accomplished by storing a \emph{forwarding
  11733. pointer}\index{subject}{forwarding pointer} to the new location in the
  11734. old tuple, when we initially copied the tuple into the
  11735. ToSpace. This completes one step of the algorithm. The algorithm
  11736. continues in this way until the queue is empty; that is, when the scan
  11737. pointer catches up with the free pointer.
  11738. \subsection{Data Representation}
  11739. \label{sec:data-rep-gc}
  11740. The garbage collector places some requirements on the data
  11741. representations used by our compiler. First, the garbage collector
  11742. needs to distinguish between pointers and other kinds of data such as
  11743. integers. The following are several ways to accomplish this:
  11744. \begin{enumerate}
  11745. \item Attach a tag to each object that identifies what type of
  11746. object it is~\citep{McCarthy:1960dz}.
  11747. \item Store different types of objects in different
  11748. regions~\citep{Steele:1977ab}.
  11749. \item Use type information from the program to either (a) generate
  11750. type-specific code for collecting, or (b) generate tables that
  11751. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11752. \end{enumerate}
  11753. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11754. need to tag objects in any case, so option 1 is a natural choice for those
  11755. languages. However, \LangVec{} is a statically typed language, so it
  11756. would be unfortunate to require tags on every object, especially small
  11757. and pervasive objects like integers and Booleans. Option 3 is the
  11758. best-performing choice for statically typed languages, but it comes with
  11759. a relatively high implementation complexity. To keep this chapter
  11760. within a reasonable scope of complexity, we recommend a combination of options
  11761. 1 and 2, using separate strategies for the stack and the heap.
  11762. Regarding the stack, we recommend using a separate stack for pointers,
  11763. which we call the \emph{root stack}\index{subject}{root stack}
  11764. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11765. That is, when a local variable needs to be spilled and is of type
  11766. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11767. root stack instead of putting it on the procedure call
  11768. stack. Furthermore, we always spill tuple-typed variables if they are
  11769. live during a call to the collector, thereby ensuring that no pointers
  11770. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11771. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11772. contrasts it with the data layout using a root stack. The root stack
  11773. contains the two pointers from the regular stack and also the pointer
  11774. in the second register.
  11775. \begin{figure}[tbp]
  11776. \centering
  11777. \begin{tcolorbox}[colback=white]
  11778. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11779. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11780. \end{tcolorbox}
  11781. \caption{Maintaining a root stack to facilitate garbage collection.}
  11782. \label{fig:shadow-stack}
  11783. \end{figure}
  11784. The problem of distinguishing between pointers and other kinds of data
  11785. also arises inside each tuple on the heap. We solve this problem by
  11786. attaching a tag, an extra 64 bits, to each
  11787. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11788. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11789. Note that we have drawn the bits in a big-endian way, from right to left,
  11790. with bit location 0 (the least significant bit) on the far right,
  11791. which corresponds to the direction of the x86 shifting instructions
  11792. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11793. is dedicated to specifying which elements of the tuple are pointers,
  11794. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11795. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11796. data. The pointer mask starts at bit location 7. We limit tuples to a
  11797. maximum size of fifty elements, so we need 50 bits for the pointer
  11798. mask.%
  11799. %
  11800. \footnote{A production-quality compiler would handle
  11801. arbitrarily sized tuples and use a more complex approach.}
  11802. %
  11803. The tag also contains two other pieces of information. The length of
  11804. the tuple (number of elements) is stored in bits at locations 1 through
  11805. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11806. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11807. has not yet been copied. If the bit has value 0, then the entire tag
  11808. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11809. zero in any case, because our tuples are 8-byte aligned.)
  11810. \begin{figure}[tbp]
  11811. \centering
  11812. \begin{tcolorbox}[colback=white]
  11813. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11814. \end{tcolorbox}
  11815. \caption{Representation of tuples in the heap.}
  11816. \label{fig:tuple-rep}
  11817. \end{figure}
  11818. \subsection{Implementation of the Garbage Collector}
  11819. \label{sec:organize-gz}
  11820. \index{subject}{prelude}
  11821. An implementation of the copying collector is provided in the
  11822. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11823. interface to the garbage collector that is used by the compiler. The
  11824. \code{initialize} function creates the FromSpace, ToSpace, and root
  11825. stack and should be called in the prelude of the \code{main}
  11826. function. The arguments of \code{initialize} are the root stack size
  11827. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11828. good choice for both. The \code{initialize} function puts the address
  11829. of the beginning of the FromSpace into the global variable
  11830. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11831. the address that is one past the last element of the FromSpace. We use
  11832. half-open intervals to represent chunks of
  11833. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11834. points to the first element of the root stack.
  11835. As long as there is room left in the FromSpace, your generated code
  11836. can allocate\index{subject}{allocate} tuples simply by moving the
  11837. \code{free\_ptr} forward.
  11838. %
  11839. The amount of room left in the FromSpace is the difference between the
  11840. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11841. function should be called when there is not enough room left in the
  11842. FromSpace for the next allocation. The \code{collect} function takes
  11843. a pointer to the current top of the root stack (one past the last item
  11844. that was pushed) and the number of bytes that need to be
  11845. allocated. The \code{collect} function performs the copying collection
  11846. and leaves the heap in a state such that there is enough room for the
  11847. next allocation.
  11848. \begin{figure}[tbp]
  11849. \begin{tcolorbox}[colback=white]
  11850. \begin{lstlisting}
  11851. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11852. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11853. int64_t* free_ptr;
  11854. int64_t* fromspace_begin;
  11855. int64_t* fromspace_end;
  11856. int64_t** rootstack_begin;
  11857. \end{lstlisting}
  11858. \end{tcolorbox}
  11859. \caption{The compiler's interface to the garbage collector.}
  11860. \label{fig:gc-header}
  11861. \end{figure}
  11862. %% \begin{exercise}
  11863. %% In the file \code{runtime.c} you will find the implementation of
  11864. %% \code{initialize} and a partial implementation of \code{collect}.
  11865. %% The \code{collect} function calls another function, \code{cheney},
  11866. %% to perform the actual copy, and that function is left to the reader
  11867. %% to implement. The following is the prototype for \code{cheney}.
  11868. %% \begin{lstlisting}
  11869. %% static void cheney(int64_t** rootstack_ptr);
  11870. %% \end{lstlisting}
  11871. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11872. %% rootstack (which is an array of pointers). The \code{cheney} function
  11873. %% also communicates with \code{collect} through the global
  11874. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11875. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11876. %% the ToSpace:
  11877. %% \begin{lstlisting}
  11878. %% static int64_t* tospace_begin;
  11879. %% static int64_t* tospace_end;
  11880. %% \end{lstlisting}
  11881. %% The job of the \code{cheney} function is to copy all the live
  11882. %% objects (reachable from the root stack) into the ToSpace, update
  11883. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11884. %% update the root stack so that it points to the objects in the
  11885. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11886. %% and ToSpace.
  11887. %% \end{exercise}
  11888. The introduction of garbage collection has a nontrivial impact on our
  11889. compiler passes. We introduce a new compiler pass named
  11890. \code{expose\_allocation} that elaborates the code for allocating
  11891. tuples. We also make significant changes to
  11892. \code{select\_instructions}, \code{build\_interference},
  11893. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11894. make minor changes in several more passes.
  11895. The following program serves as our running example. It creates
  11896. two tuples, one nested inside the other. Both tuples have length
  11897. one. The program accesses the element in the inner tuple.
  11898. % tests/vectors_test_17.rkt
  11899. {\if\edition\racketEd
  11900. \begin{lstlisting}
  11901. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11902. \end{lstlisting}
  11903. \fi}
  11904. % tests/tuple/get_get.py
  11905. {\if\edition\pythonEd\pythonColor
  11906. \begin{lstlisting}
  11907. v1 = (42,)
  11908. v2 = (v1,)
  11909. print(v2[0][0])
  11910. \end{lstlisting}
  11911. \fi}
  11912. %% {\if\edition\racketEd
  11913. %% \section{Shrink}
  11914. %% \label{sec:shrink-Lvec}
  11915. %% Recall that the \code{shrink} pass translates the primitives operators
  11916. %% into a smaller set of primitives.
  11917. %% %
  11918. %% This pass comes after type checking, and the type checker adds a
  11919. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11920. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11921. %% \fi}
  11922. \section{Expose Allocation}
  11923. \label{sec:expose-allocation}
  11924. The pass \code{expose\_allocation} lowers tuple creation into making a
  11925. conditional call to the collector followed by allocating the
  11926. appropriate amount of memory and initializing it. We choose to place
  11927. the \code{expose\_allocation} pass before
  11928. \code{remove\_complex\_operands} because it generates
  11929. code that contains complex operands.
  11930. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11931. that replaces tuple creation with new lower-level forms that we use in the
  11932. translation of tuple creation.
  11933. %
  11934. {\if\edition\racketEd
  11935. \[
  11936. \begin{array}{lcl}
  11937. \Exp &::=& (\key{collect} \,\itm{int})
  11938. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11939. \MID (\key{global-value} \,\itm{name})
  11940. \end{array}
  11941. \]
  11942. \fi}
  11943. {\if\edition\pythonEd\pythonColor
  11944. \[
  11945. \begin{array}{lcl}
  11946. \Exp &::=& \cdots\\
  11947. &\MID& \key{collect}(\itm{int})
  11948. \MID \key{allocate}(\itm{int},\itm{type})
  11949. \MID \key{global\_value}(\itm{name}) \\
  11950. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11951. \end{array}
  11952. \]
  11953. \fi}
  11954. %
  11955. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11956. make sure that there are $n$ bytes ready to be allocated. During
  11957. instruction selection\index{subject}{instruction selection},
  11958. the \CCOLLECT{$n$} form will become a call to
  11959. the \code{collect} function in \code{runtime.c}.
  11960. %
  11961. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11962. space at the front for the 64-bit tag), but the elements are not
  11963. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11964. of the tuple:
  11965. %
  11966. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11967. %
  11968. where $\Type_i$ is the type of the $i$th element.
  11969. %
  11970. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11971. variable, such as \code{free\_ptr}.
  11972. \racket{
  11973. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11974. can be obtained by running the
  11975. \code{type-check-Lvec-has-type} type checker immediately before the
  11976. \code{expose\_allocation} pass. This version of the type checker
  11977. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11978. around each tuple creation. The concrete syntax
  11979. for \code{HasType} is \code{has-type}.}
  11980. The following shows the transformation of tuple creation into (1) a
  11981. sequence of temporary variable bindings for the initializing
  11982. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11983. \code{allocate}, and (4) the initialization of the tuple. The
  11984. \itm{len} placeholder refers to the length of the tuple, and
  11985. \itm{bytes} is the total number of bytes that need to be allocated for
  11986. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11987. %
  11988. \python{The \itm{type} needed for the second argument of the
  11989. \code{allocate} form can be obtained from the \code{has\_type} field
  11990. of the tuple AST node, which is stored there by running the type
  11991. checker for \LangVec{} immediately before this pass.}
  11992. %
  11993. \begin{center}
  11994. \begin{minipage}{\textwidth}
  11995. {\if\edition\racketEd
  11996. \begin{lstlisting}
  11997. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11998. |$\Longrightarrow$|
  11999. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12000. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12001. (global-value fromspace_end))
  12002. (void)
  12003. (collect |\itm{bytes}|))])
  12004. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12005. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12006. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12007. |$v$|) ... )))) ...)
  12008. \end{lstlisting}
  12009. \fi}
  12010. {\if\edition\pythonEd\pythonColor
  12011. \begin{lstlisting}
  12012. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12013. |$\Longrightarrow$|
  12014. begin:
  12015. |$x_0$| = |$e_0$|
  12016. |$\vdots$|
  12017. |$x_{n-1}$| = |$e_{n-1}$|
  12018. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12019. 0
  12020. else:
  12021. collect(|\itm{bytes}|)
  12022. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12023. |$v$|[0] = |$x_0$|
  12024. |$\vdots$|
  12025. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12026. |$v$|
  12027. \end{lstlisting}
  12028. \fi}
  12029. \end{minipage}
  12030. \end{center}
  12031. %
  12032. \noindent The sequencing of the initializing expressions
  12033. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12034. they may trigger garbage collection and we cannot have an allocated
  12035. but uninitialized tuple on the heap during a collection.
  12036. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12037. \code{expose\_allocation} pass on our running example.
  12038. \begin{figure}[tbp]
  12039. \begin{tcolorbox}[colback=white]
  12040. % tests/s2_17.rkt
  12041. {\if\edition\racketEd
  12042. \begin{lstlisting}
  12043. (vector-ref
  12044. (vector-ref
  12045. (let ([vecinit6
  12046. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12047. (global-value fromspace_end))
  12048. (void)
  12049. (collect 16))])
  12050. (let ([alloc2 (allocate 1 (Vector Integer))])
  12051. (let ([_3 (vector-set! alloc2 0 42)])
  12052. alloc2)))])
  12053. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12054. (global-value fromspace_end))
  12055. (void)
  12056. (collect 16))])
  12057. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12058. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12059. alloc5))))
  12060. 0)
  12061. 0)
  12062. \end{lstlisting}
  12063. \fi}
  12064. {\if\edition\pythonEd\pythonColor
  12065. \begin{lstlisting}
  12066. v1 = begin:
  12067. init.514 = 42
  12068. if (free_ptr + 16) < fromspace_end:
  12069. else:
  12070. collect(16)
  12071. alloc.513 = allocate(1,tuple[int])
  12072. alloc.513[0] = init.514
  12073. alloc.513
  12074. v2 = begin:
  12075. init.516 = v1
  12076. if (free_ptr + 16) < fromspace_end:
  12077. else:
  12078. collect(16)
  12079. alloc.515 = allocate(1,tuple[tuple[int]])
  12080. alloc.515[0] = init.516
  12081. alloc.515
  12082. print(v2[0][0])
  12083. \end{lstlisting}
  12084. \fi}
  12085. \end{tcolorbox}
  12086. \caption{Output of the \code{expose\_allocation} pass.}
  12087. \label{fig:expose-alloc-output}
  12088. \end{figure}
  12089. \section{Remove Complex Operands}
  12090. \label{sec:remove-complex-opera-Lvec}
  12091. {\if\edition\racketEd
  12092. %
  12093. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12094. should be treated as complex operands.
  12095. %
  12096. \fi}
  12097. %
  12098. {\if\edition\pythonEd\pythonColor
  12099. %
  12100. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12101. and tuple access should be treated as complex operands. The
  12102. subexpressions of tuple access must be atomic.
  12103. %
  12104. \fi}
  12105. %% A new case for
  12106. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12107. %% handled carefully to prevent the \code{Prim} node from being separated
  12108. %% from its enclosing \code{HasType}.
  12109. Figure~\ref{fig:Lvec-anf-syntax}
  12110. shows the grammar for the output language \LangAllocANF{} of this
  12111. pass, which is \LangAlloc{} in monadic normal form.
  12112. \newcommand{\LtupMonadASTRacket}{
  12113. \begin{array}{rcl}
  12114. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12115. \MID \GLOBALVALUE{\Var}
  12116. \end{array}
  12117. }
  12118. \newcommand{\LtupMonadASTPython}{
  12119. \begin{array}{rcl}
  12120. \Exp &::=& \GET{\Atm}{\Atm} \\
  12121. &\MID& \LEN{\Atm}\\
  12122. &\MID& \ALLOCATE{\Int}{\Type}
  12123. \MID \GLOBALVALUE{\Var} \\
  12124. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12125. &\MID& \COLLECT{\Int}
  12126. \end{array}
  12127. }
  12128. \begin{figure}[tp]
  12129. \centering
  12130. \begin{tcolorbox}[colback=white]
  12131. \small
  12132. {\if\edition\racketEd
  12133. \[
  12134. \begin{array}{l}
  12135. \gray{\LvarMonadASTRacket} \\ \hline
  12136. \gray{\LifMonadASTRacket} \\ \hline
  12137. \gray{\LwhileMonadASTRacket} \\ \hline
  12138. \LtupMonadASTRacket \\
  12139. \begin{array}{rcl}
  12140. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12141. \end{array}
  12142. \end{array}
  12143. \]
  12144. \fi}
  12145. {\if\edition\pythonEd\pythonColor
  12146. \[
  12147. \begin{array}{l}
  12148. \gray{\LvarMonadASTPython} \\ \hline
  12149. \gray{\LifMonadASTPython} \\ \hline
  12150. \gray{\LwhileMonadASTPython} \\ \hline
  12151. \LtupMonadASTPython \\
  12152. \begin{array}{rcl}
  12153. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12154. \end{array}
  12155. \end{array}
  12156. \]
  12157. \fi}
  12158. \end{tcolorbox}
  12159. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12160. \label{fig:Lvec-anf-syntax}
  12161. \end{figure}
  12162. \section{Explicate Control and the \LangCVec{} Language}
  12163. \label{sec:explicate-control-r3}
  12164. \newcommand{\CtupASTRacket}{
  12165. \begin{array}{lcl}
  12166. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12167. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12168. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12169. &\MID& \VECLEN{\Atm} \\
  12170. &\MID& \GLOBALVALUE{\Var} \\
  12171. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12172. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12173. \end{array}
  12174. }
  12175. \newcommand{\CtupASTPython}{
  12176. \begin{array}{lcl}
  12177. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12178. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12179. \Stmt &::=& \COLLECT{\Int} \\
  12180. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12181. \end{array}
  12182. }
  12183. \begin{figure}[tp]
  12184. \begin{tcolorbox}[colback=white]
  12185. \small
  12186. {\if\edition\racketEd
  12187. \[
  12188. \begin{array}{l}
  12189. \gray{\CvarASTRacket} \\ \hline
  12190. \gray{\CifASTRacket} \\ \hline
  12191. \gray{\CloopASTRacket} \\ \hline
  12192. \CtupASTRacket \\
  12193. \begin{array}{lcl}
  12194. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12195. \end{array}
  12196. \end{array}
  12197. \]
  12198. \fi}
  12199. {\if\edition\pythonEd\pythonColor
  12200. \[
  12201. \begin{array}{l}
  12202. \gray{\CifASTPython} \\ \hline
  12203. \CtupASTPython \\
  12204. \begin{array}{lcl}
  12205. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12206. \end{array}
  12207. \end{array}
  12208. \]
  12209. \fi}
  12210. \end{tcolorbox}
  12211. \caption{The abstract syntax of \LangCVec{}, extending
  12212. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12213. (figure~\ref{fig:c1-syntax})}.}
  12214. \label{fig:c2-syntax}
  12215. \end{figure}
  12216. The output of \code{explicate\_control} is a program in the
  12217. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12218. shows the definition of the abstract syntax.
  12219. %
  12220. %% \racket{(The concrete syntax is defined in
  12221. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12222. %
  12223. The new expressions of \LangCVec{} include \key{allocate},
  12224. %
  12225. \racket{\key{vector-ref}, and \key{vector-set!},}
  12226. %
  12227. \python{accessing tuple elements,}
  12228. %
  12229. and \key{global\_value}.
  12230. %
  12231. \python{\LangCVec{} also includes the \code{collect} statement and
  12232. assignment to a tuple element.}
  12233. %
  12234. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12235. %
  12236. The \code{explicate\_control} pass can treat these new forms much like
  12237. the other forms that we've already encountered. The output of the
  12238. \code{explicate\_control} pass on the running example is shown on the
  12239. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12240. section.
  12241. \section{Select Instructions and the \LangXGlobal{} Language}
  12242. \label{sec:select-instructions-gc}
  12243. \index{subject}{select instructions}
  12244. %% void (rep as zero)
  12245. %% allocate
  12246. %% collect (callq collect)
  12247. %% vector-ref
  12248. %% vector-set!
  12249. %% vector-length
  12250. %% global (postpone)
  12251. In this pass we generate x86 code for most of the new operations that
  12252. are needed to compile tuples, including \code{Allocate},
  12253. \code{Collect}, and accessing tuple elements.
  12254. %
  12255. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12256. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12257. \ref{fig:x86-2}). \index{subject}{x86}
  12258. The tuple read and write forms translate into \code{movq}
  12259. instructions. (The $+1$ in the offset serves to move past the tag at the
  12260. beginning of the tuple representation.)
  12261. %
  12262. \begin{center}
  12263. \begin{minipage}{\textwidth}
  12264. {\if\edition\racketEd
  12265. \begin{lstlisting}
  12266. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12267. |$\Longrightarrow$|
  12268. movq |$\itm{tup}'$|, %r11
  12269. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12270. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12271. |$\Longrightarrow$|
  12272. movq |$\itm{tup}'$|, %r11
  12273. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12274. movq $0, |$\itm{lhs'}$|
  12275. \end{lstlisting}
  12276. \fi}
  12277. {\if\edition\pythonEd\pythonColor
  12278. \begin{lstlisting}
  12279. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12280. |$\Longrightarrow$|
  12281. movq |$\itm{tup}'$|, %r11
  12282. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12283. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12284. |$\Longrightarrow$|
  12285. movq |$\itm{tup}'$|, %r11
  12286. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12287. \end{lstlisting}
  12288. \fi}
  12289. \end{minipage}
  12290. \end{center}
  12291. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12292. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12293. are obtained by translating from \LangCVec{} to x86.
  12294. %
  12295. The move of $\itm{tup}'$ to
  12296. register \code{r11} ensures that the offset expression
  12297. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12298. removing \code{r11} from consideration by the register allocating.
  12299. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12300. \code{rax}. Then the generated code for tuple assignment would be
  12301. \begin{lstlisting}
  12302. movq |$\itm{tup}'$|, %rax
  12303. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12304. \end{lstlisting}
  12305. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12306. \code{patch\_instructions} would insert a move through \code{rax}
  12307. as follows:
  12308. \begin{lstlisting}
  12309. movq |$\itm{tup}'$|, %rax
  12310. movq |$\itm{rhs}'$|, %rax
  12311. movq %rax, |$8(n+1)$|(%rax)
  12312. \end{lstlisting}
  12313. However, this sequence of instructions does not work because we're
  12314. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12315. $\itm{rhs}'$) at the same time!
  12316. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12317. be translated into a sequence of instructions that read the tag of the
  12318. tuple and extract the 6 bits that represent the tuple length, which
  12319. are the bits starting at index 1 and going up to and including bit 6.
  12320. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12321. (shift right) can be used to accomplish this.
  12322. We compile the \code{allocate} form to operations on the
  12323. \code{free\_ptr}, as shown next. This approach is called
  12324. \emph{inline allocation} because it implements allocation without a
  12325. function call by simply incrementing the allocation pointer. It is much
  12326. more efficient than calling a function for each allocation. The
  12327. address in the \code{free\_ptr} is the next free address in the
  12328. FromSpace, so we copy it into \code{r11} and then move it forward by
  12329. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12330. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12331. the tag. We then initialize the \itm{tag} and finally copy the
  12332. address in \code{r11} to the left-hand side. Refer to
  12333. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12334. %
  12335. \racket{We recommend using the Racket operations
  12336. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12337. during compilation.}
  12338. %
  12339. \python{We recommend using the bitwise-or operator \code{|} and the
  12340. shift-left operator \code{<<} to compute the tag during
  12341. compilation.}
  12342. %
  12343. The type annotation in the \code{allocate} form is used to determine
  12344. the pointer mask region of the tag.
  12345. %
  12346. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12347. address of the \code{free\_ptr} global variable using a special
  12348. instruction-pointer-relative addressing mode of the x86-64 processor.
  12349. In particular, the assembler computes the distance $d$ between the
  12350. address of \code{free\_ptr} and where the \code{rip} would be at that
  12351. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12352. \code{$d$(\%rip)}, which at runtime will compute the address of
  12353. \code{free\_ptr}.
  12354. %
  12355. {\if\edition\racketEd
  12356. \begin{lstlisting}
  12357. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12358. |$\Longrightarrow$|
  12359. movq free_ptr(%rip), %r11
  12360. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12361. movq $|$\itm{tag}$|, 0(%r11)
  12362. movq %r11, |$\itm{lhs}'$|
  12363. \end{lstlisting}
  12364. \fi}
  12365. {\if\edition\pythonEd\pythonColor
  12366. \begin{lstlisting}
  12367. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12368. |$\Longrightarrow$|
  12369. movq free_ptr(%rip), %r11
  12370. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12371. movq $|$\itm{tag}$|, 0(%r11)
  12372. movq %r11, |$\itm{lhs}'$|
  12373. \end{lstlisting}
  12374. \fi}
  12375. %
  12376. The \code{collect} form is compiled to a call to the \code{collect}
  12377. function in the runtime. The arguments to \code{collect} are (1) the
  12378. top of the root stack, and (2) the number of bytes that need to be
  12379. allocated. We use another dedicated register, \code{r15}, to store
  12380. the pointer to the top of the root stack. Therefore \code{r15} is not
  12381. available for use by the register allocator.
  12382. %
  12383. {\if\edition\racketEd
  12384. \begin{lstlisting}
  12385. (collect |$\itm{bytes}$|)
  12386. |$\Longrightarrow$|
  12387. movq %r15, %rdi
  12388. movq $|\itm{bytes}|, %rsi
  12389. callq collect
  12390. \end{lstlisting}
  12391. \fi}
  12392. {\if\edition\pythonEd\pythonColor
  12393. \begin{lstlisting}
  12394. collect(|$\itm{bytes}$|)
  12395. |$\Longrightarrow$|
  12396. movq %r15, %rdi
  12397. movq $|\itm{bytes}|, %rsi
  12398. callq collect
  12399. \end{lstlisting}
  12400. \fi}
  12401. \newcommand{\GrammarXGlobal}{
  12402. \begin{array}{lcl}
  12403. \Arg &::=& \itm{label} \key{(\%rip)}
  12404. \end{array}
  12405. }
  12406. \newcommand{\ASTXGlobalRacket}{
  12407. \begin{array}{lcl}
  12408. \Arg &::=& \GLOBAL{\itm{label}}
  12409. \end{array}
  12410. }
  12411. \begin{figure}[tp]
  12412. \begin{tcolorbox}[colback=white]
  12413. \[
  12414. \begin{array}{l}
  12415. \gray{\GrammarXInt} \\ \hline
  12416. \gray{\GrammarXIf} \\ \hline
  12417. \GrammarXGlobal \\
  12418. \begin{array}{lcl}
  12419. \LangXGlobalM{} &::= & \key{.globl main} \\
  12420. & & \key{main:} \; \Instr^{*}
  12421. \end{array}
  12422. \end{array}
  12423. \]
  12424. \end{tcolorbox}
  12425. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12426. \label{fig:x86-2-concrete}
  12427. \end{figure}
  12428. \begin{figure}[tp]
  12429. \begin{tcolorbox}[colback=white]
  12430. \small
  12431. {\if\edition\racketEd
  12432. \[
  12433. \begin{array}{l}
  12434. \gray{\ASTXIntRacket} \\ \hline
  12435. \gray{\ASTXIfRacket} \\ \hline
  12436. \ASTXGlobalRacket \\
  12437. \begin{array}{lcl}
  12438. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12439. \end{array}
  12440. \end{array}
  12441. \]
  12442. \fi}
  12443. {\if\edition\pythonEd\pythonColor
  12444. \[
  12445. \begin{array}{l}
  12446. \gray{\ASTXIntPython} \\ \hline
  12447. \gray{\ASTXIfPython} \\ \hline
  12448. \ASTXGlobalRacket \\
  12449. \begin{array}{lcl}
  12450. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12451. \end{array}
  12452. \end{array}
  12453. \]
  12454. \fi}
  12455. \end{tcolorbox}
  12456. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12457. \label{fig:x86-2}
  12458. \end{figure}
  12459. The definitions of the concrete and abstract syntax of the
  12460. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12461. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12462. of global variables.
  12463. %
  12464. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12465. \code{select\_instructions} pass on the running example.
  12466. \begin{figure}[tbp]
  12467. \centering
  12468. \begin{tcolorbox}[colback=white]
  12469. {\if\edition\racketEd
  12470. % tests/s2_17.rkt
  12471. \begin{tabular}{lll}
  12472. \begin{minipage}{0.5\textwidth}
  12473. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12474. start:
  12475. tmp9 = (global-value free_ptr);
  12476. tmp0 = (+ tmp9 16);
  12477. tmp1 = (global-value fromspace_end);
  12478. if (< tmp0 tmp1)
  12479. goto block0;
  12480. else
  12481. goto block1;
  12482. block0:
  12483. _4 = (void);
  12484. goto block9;
  12485. block1:
  12486. (collect 16)
  12487. goto block9;
  12488. block9:
  12489. alloc2 = (allocate 1 (Vector Integer));
  12490. _3 = (vector-set! alloc2 0 42);
  12491. vecinit6 = alloc2;
  12492. tmp2 = (global-value free_ptr);
  12493. tmp3 = (+ tmp2 16);
  12494. tmp4 = (global-value fromspace_end);
  12495. if (< tmp3 tmp4)
  12496. goto block7;
  12497. else
  12498. goto block8;
  12499. block7:
  12500. _8 = (void);
  12501. goto block6;
  12502. block8:
  12503. (collect 16)
  12504. goto block6;
  12505. block6:
  12506. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12507. _7 = (vector-set! alloc5 0 vecinit6);
  12508. tmp5 = (vector-ref alloc5 0);
  12509. return (vector-ref tmp5 0);
  12510. \end{lstlisting}
  12511. \end{minipage}
  12512. &$\Rightarrow$&
  12513. \begin{minipage}{0.4\textwidth}
  12514. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12515. start:
  12516. movq free_ptr(%rip), tmp9
  12517. movq tmp9, tmp0
  12518. addq $16, tmp0
  12519. movq fromspace_end(%rip), tmp1
  12520. cmpq tmp1, tmp0
  12521. jl block0
  12522. jmp block1
  12523. block0:
  12524. movq $0, _4
  12525. jmp block9
  12526. block1:
  12527. movq %r15, %rdi
  12528. movq $16, %rsi
  12529. callq collect
  12530. jmp block9
  12531. block9:
  12532. movq free_ptr(%rip), %r11
  12533. addq $16, free_ptr(%rip)
  12534. movq $3, 0(%r11)
  12535. movq %r11, alloc2
  12536. movq alloc2, %r11
  12537. movq $42, 8(%r11)
  12538. movq $0, _3
  12539. movq alloc2, vecinit6
  12540. movq free_ptr(%rip), tmp2
  12541. movq tmp2, tmp3
  12542. addq $16, tmp3
  12543. movq fromspace_end(%rip), tmp4
  12544. cmpq tmp4, tmp3
  12545. jl block7
  12546. jmp block8
  12547. block7:
  12548. movq $0, _8
  12549. jmp block6
  12550. block8:
  12551. movq %r15, %rdi
  12552. movq $16, %rsi
  12553. callq collect
  12554. jmp block6
  12555. block6:
  12556. movq free_ptr(%rip), %r11
  12557. addq $16, free_ptr(%rip)
  12558. movq $131, 0(%r11)
  12559. movq %r11, alloc5
  12560. movq alloc5, %r11
  12561. movq vecinit6, 8(%r11)
  12562. movq $0, _7
  12563. movq alloc5, %r11
  12564. movq 8(%r11), tmp5
  12565. movq tmp5, %r11
  12566. movq 8(%r11), %rax
  12567. jmp conclusion
  12568. \end{lstlisting}
  12569. \end{minipage}
  12570. \end{tabular}
  12571. \fi}
  12572. {\if\edition\pythonEd
  12573. % tests/tuple/get_get.py
  12574. \begin{tabular}{lll}
  12575. \begin{minipage}{0.5\textwidth}
  12576. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12577. start:
  12578. init.514 = 42
  12579. tmp.517 = free_ptr
  12580. tmp.518 = (tmp.517 + 16)
  12581. tmp.519 = fromspace_end
  12582. if tmp.518 < tmp.519:
  12583. goto block.529
  12584. else:
  12585. goto block.530
  12586. block.529:
  12587. goto block.528
  12588. block.530:
  12589. collect(16)
  12590. goto block.528
  12591. block.528:
  12592. alloc.513 = allocate(1,tuple[int])
  12593. alloc.513:tuple[int][0] = init.514
  12594. v1 = alloc.513
  12595. init.516 = v1
  12596. tmp.520 = free_ptr
  12597. tmp.521 = (tmp.520 + 16)
  12598. tmp.522 = fromspace_end
  12599. if tmp.521 < tmp.522:
  12600. goto block.526
  12601. else:
  12602. goto block.527
  12603. block.526:
  12604. goto block.525
  12605. block.527:
  12606. collect(16)
  12607. goto block.525
  12608. block.525:
  12609. alloc.515 = allocate(1,tuple[tuple[int]])
  12610. alloc.515:tuple[tuple[int]][0] = init.516
  12611. v2 = alloc.515
  12612. tmp.523 = v2[0]
  12613. tmp.524 = tmp.523[0]
  12614. print(tmp.524)
  12615. return 0
  12616. \end{lstlisting}
  12617. \end{minipage}
  12618. &$\Rightarrow$&
  12619. \begin{minipage}{0.4\textwidth}
  12620. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12621. start:
  12622. movq $42, init.514
  12623. movq free_ptr(%rip), tmp.517
  12624. movq tmp.517, tmp.518
  12625. addq $16, tmp.518
  12626. movq fromspace_end(%rip), tmp.519
  12627. cmpq tmp.519, tmp.518
  12628. jl block.529
  12629. jmp block.530
  12630. block.529:
  12631. jmp block.528
  12632. block.530:
  12633. movq %r15, %rdi
  12634. movq $16, %rsi
  12635. callq collect
  12636. jmp block.528
  12637. block.528:
  12638. movq free_ptr(%rip), %r11
  12639. addq $16, free_ptr(%rip)
  12640. movq $3, 0(%r11)
  12641. movq %r11, alloc.513
  12642. movq alloc.513, %r11
  12643. movq init.514, 8(%r11)
  12644. movq alloc.513, v1
  12645. movq v1, init.516
  12646. movq free_ptr(%rip), tmp.520
  12647. movq tmp.520, tmp.521
  12648. addq $16, tmp.521
  12649. movq fromspace_end(%rip), tmp.522
  12650. cmpq tmp.522, tmp.521
  12651. jl block.526
  12652. jmp block.527
  12653. block.526:
  12654. jmp block.525
  12655. block.527:
  12656. movq %r15, %rdi
  12657. movq $16, %rsi
  12658. callq collect
  12659. jmp block.525
  12660. block.525:
  12661. movq free_ptr(%rip), %r11
  12662. addq $16, free_ptr(%rip)
  12663. movq $131, 0(%r11)
  12664. movq %r11, alloc.515
  12665. movq alloc.515, %r11
  12666. movq init.516, 8(%r11)
  12667. movq alloc.515, v2
  12668. movq v2, %r11
  12669. movq 8(%r11), %r11
  12670. movq %r11, tmp.523
  12671. movq tmp.523, %r11
  12672. movq 8(%r11), %r11
  12673. movq %r11, tmp.524
  12674. movq tmp.524, %rdi
  12675. callq print_int
  12676. movq $0, %rax
  12677. jmp conclusion
  12678. \end{lstlisting}
  12679. \end{minipage}
  12680. \end{tabular}
  12681. \fi}
  12682. \end{tcolorbox}
  12683. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12684. \code{select\_instructions} (\emph{right}) on the running example.}
  12685. \label{fig:select-instr-output-gc}
  12686. \end{figure}
  12687. \clearpage
  12688. \section{Register Allocation}
  12689. \label{sec:reg-alloc-gc}
  12690. \index{subject}{register allocation}
  12691. As discussed previously in this chapter, the garbage collector needs to
  12692. access all the pointers in the root set, that is, all variables that
  12693. are tuples. It will be the responsibility of the register allocator
  12694. to make sure that
  12695. \begin{enumerate}
  12696. \item the root stack is used for spilling tuple-typed variables, and
  12697. \item if a tuple-typed variable is live during a call to the
  12698. collector, it must be spilled to ensure that it is visible to the
  12699. collector.
  12700. \end{enumerate}
  12701. The latter responsibility can be handled during construction of the
  12702. interference graph, by adding interference edges between the call-live
  12703. tuple-typed variables and all the callee-saved registers. (They
  12704. already interfere with the caller-saved registers.)
  12705. %
  12706. \racket{The type information for variables is in the \code{Program}
  12707. form, so we recommend adding another parameter to the
  12708. \code{build\_interference} function to communicate this alist.}
  12709. %
  12710. \python{The type information for variables is generated by the type
  12711. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12712. the \code{CProgram} AST mode. You'll need to propagate that
  12713. information so that it is available in this pass.}
  12714. The spilling of tuple-typed variables to the root stack can be handled
  12715. after graph coloring, in choosing how to assign the colors
  12716. (integers) to registers and stack locations. The
  12717. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12718. changes to also record the number of spills to the root stack.
  12719. % build-interference
  12720. %
  12721. % callq
  12722. % extra parameter for var->type assoc. list
  12723. % update 'program' and 'if'
  12724. % allocate-registers
  12725. % allocate spilled vectors to the rootstack
  12726. % don't change color-graph
  12727. % TODO:
  12728. %\section{Patch Instructions}
  12729. %[mention that global variables are memory references]
  12730. \section{Prelude and Conclusion}
  12731. \label{sec:print-x86-gc}
  12732. \label{sec:prelude-conclusion-x86-gc}
  12733. \index{subject}{prelude}\index{subject}{conclusion}
  12734. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12735. \code{prelude\_and\_conclusion} pass on the running example. In the
  12736. prelude of the \code{main} function, we allocate space
  12737. on the root stack to make room for the spills of tuple-typed
  12738. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12739. taking care that the root stack grows up instead of down. For the
  12740. running example, there was just one spill, so we increment \code{r15}
  12741. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12742. One issue that deserves special care is that there may be a call to
  12743. \code{collect} prior to the initializing assignments for all the
  12744. variables in the root stack. We do not want the garbage collector to
  12745. mistakenly determine that some uninitialized variable is a pointer that
  12746. needs to be followed. Thus, we zero out all locations on the root
  12747. stack in the prelude of \code{main}. In
  12748. figure~\ref{fig:print-x86-output-gc}, the instruction
  12749. %
  12750. \lstinline{movq $0, 0(%r15)}
  12751. %
  12752. is sufficient to accomplish this task because there is only one spill.
  12753. In general, we have to clear as many words as there are spills of
  12754. tuple-typed variables. The garbage collector tests each root to see
  12755. if it is null prior to dereferencing it.
  12756. \begin{figure}[htbp]
  12757. \begin{tcolorbox}[colback=white]
  12758. {\if\edition\racketEd
  12759. \begin{minipage}[t]{0.5\textwidth}
  12760. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12761. .globl main
  12762. main:
  12763. pushq %rbp
  12764. movq %rsp, %rbp
  12765. subq $0, %rsp
  12766. movq $65536, %rdi
  12767. movq $65536, %rsi
  12768. callq initialize
  12769. movq rootstack_begin(%rip), %r15
  12770. movq $0, 0(%r15)
  12771. addq $8, %r15
  12772. jmp start
  12773. conclusion:
  12774. subq $8, %r15
  12775. addq $0, %rsp
  12776. popq %rbp
  12777. retq
  12778. \end{lstlisting}
  12779. \end{minipage}
  12780. \fi}
  12781. {\if\edition\pythonEd
  12782. \begin{minipage}[t]{0.5\textwidth}
  12783. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12784. .globl main
  12785. main:
  12786. pushq %rbp
  12787. movq %rsp, %rbp
  12788. pushq %rbx
  12789. subq $8, %rsp
  12790. movq $65536, %rdi
  12791. movq $16, %rsi
  12792. callq initialize
  12793. movq rootstack_begin(%rip), %r15
  12794. movq $0, 0(%r15)
  12795. addq $8, %r15
  12796. jmp start
  12797. conclusion:
  12798. subq $8, %r15
  12799. addq $8, %rsp
  12800. popq %rbx
  12801. popq %rbp
  12802. retq
  12803. \end{lstlisting}
  12804. \end{minipage}
  12805. \fi}
  12806. \end{tcolorbox}
  12807. \caption{The prelude and conclusion for the running example.}
  12808. \label{fig:print-x86-output-gc}
  12809. \end{figure}
  12810. \begin{figure}[tbp]
  12811. \begin{tcolorbox}[colback=white]
  12812. {\if\edition\racketEd
  12813. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12814. \node (Lvec) at (0,2) {\large \LangVec{}};
  12815. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12816. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12817. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12818. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12819. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12820. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12821. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12822. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12823. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12824. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12825. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12826. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12827. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12828. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12829. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12830. \path[->,bend left=15] (Lvec-4) edge [right] node
  12831. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12832. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12833. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12834. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12835. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12836. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12837. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12838. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12839. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12840. \end{tikzpicture}
  12841. \fi}
  12842. {\if\edition\pythonEd\pythonColor
  12843. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12844. \node (Lvec) at (0,2) {\large \LangVec{}};
  12845. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12846. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12847. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12848. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12849. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12850. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12851. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12852. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12853. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12854. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12855. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12856. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12857. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12858. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12859. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12860. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12861. \end{tikzpicture}
  12862. \fi}
  12863. \end{tcolorbox}
  12864. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12865. \label{fig:Lvec-passes}
  12866. \end{figure}
  12867. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12868. for the compilation of \LangVec{}.
  12869. \clearpage
  12870. {\if\edition\racketEd
  12871. \section{Challenge: Simple Structures}
  12872. \label{sec:simple-structures}
  12873. \index{subject}{struct}
  12874. \index{subject}{structure}
  12875. The language \LangStruct{} extends \LangVec{} with support for simple
  12876. structures. The definition of its concrete syntax is shown in
  12877. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12878. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12879. in Typed Racket is a user-defined data type that contains named fields
  12880. and that is heap allocated\index{subject}{heap allocated},
  12881. similarly to a vector. The following is an
  12882. example of a structure definition, in this case the definition of a
  12883. \code{point} type:
  12884. \begin{lstlisting}
  12885. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12886. \end{lstlisting}
  12887. \newcommand{\LstructGrammarRacket}{
  12888. \begin{array}{lcl}
  12889. \Type &::=& \Var \\
  12890. \Exp &::=& (\Var\;\Exp \ldots)\\
  12891. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12892. \end{array}
  12893. }
  12894. \newcommand{\LstructASTRacket}{
  12895. \begin{array}{lcl}
  12896. \Type &::=& \VAR{\Var} \\
  12897. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12898. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12899. \end{array}
  12900. }
  12901. \begin{figure}[tbp]
  12902. \centering
  12903. \begin{tcolorbox}[colback=white]
  12904. \[
  12905. \begin{array}{l}
  12906. \gray{\LintGrammarRacket{}} \\ \hline
  12907. \gray{\LvarGrammarRacket{}} \\ \hline
  12908. \gray{\LifGrammarRacket{}} \\ \hline
  12909. \gray{\LwhileGrammarRacket} \\ \hline
  12910. \gray{\LtupGrammarRacket} \\ \hline
  12911. \LstructGrammarRacket \\
  12912. \begin{array}{lcl}
  12913. \LangStruct{} &::=& \Def \ldots \; \Exp
  12914. \end{array}
  12915. \end{array}
  12916. \]
  12917. \end{tcolorbox}
  12918. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12919. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12920. \label{fig:Lstruct-concrete-syntax}
  12921. \end{figure}
  12922. \begin{figure}[tbp]
  12923. \centering
  12924. \begin{tcolorbox}[colback=white]
  12925. \small
  12926. \[
  12927. \begin{array}{l}
  12928. \gray{\LintASTRacket{}} \\ \hline
  12929. \gray{\LvarASTRacket{}} \\ \hline
  12930. \gray{\LifASTRacket{}} \\ \hline
  12931. \gray{\LwhileASTRacket} \\ \hline
  12932. \gray{\LtupASTRacket} \\ \hline
  12933. \LstructASTRacket \\
  12934. \begin{array}{lcl}
  12935. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12936. \end{array}
  12937. \end{array}
  12938. \]
  12939. \end{tcolorbox}
  12940. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12941. (figure~\ref{fig:Lvec-syntax}).}
  12942. \label{fig:Lstruct-syntax}
  12943. \end{figure}
  12944. An instance of a structure is created using function-call syntax, with
  12945. the name of the structure in the function position, as follows:
  12946. \begin{lstlisting}
  12947. (point 7 12)
  12948. \end{lstlisting}
  12949. Function-call syntax is also used to read a field of a structure. The
  12950. function name is formed by the structure name, a dash, and the field
  12951. name. The following example uses \code{point-x} and \code{point-y} to
  12952. access the \code{x} and \code{y} fields of two point instances:
  12953. \begin{center}
  12954. \begin{lstlisting}
  12955. (let ([pt1 (point 7 12)])
  12956. (let ([pt2 (point 4 3)])
  12957. (+ (- (point-x pt1) (point-x pt2))
  12958. (- (point-y pt1) (point-y pt2)))))
  12959. \end{lstlisting}
  12960. \end{center}
  12961. Similarly, to write to a field of a structure, use its set function,
  12962. whose name starts with \code{set-}, followed by the structure name,
  12963. then a dash, then the field name, and finally with an exclamation
  12964. mark. The following example uses \code{set-point-x!} to change the
  12965. \code{x} field from \code{7} to \code{42}:
  12966. \begin{center}
  12967. \begin{lstlisting}
  12968. (let ([pt (point 7 12)])
  12969. (let ([_ (set-point-x! pt 42)])
  12970. (point-x pt)))
  12971. \end{lstlisting}
  12972. \end{center}
  12973. \begin{exercise}\normalfont\normalsize
  12974. Create a type checker for \LangStruct{} by extending the type
  12975. checker for \LangVec{}. Extend your compiler with support for simple
  12976. structures, compiling \LangStruct{} to x86 assembly code. Create
  12977. five new test cases that use structures, and test your compiler.
  12978. \end{exercise}
  12979. % TODO: create an interpreter for L_struct
  12980. \clearpage
  12981. \fi}
  12982. \section{Challenge: Arrays}
  12983. \label{sec:arrays}
  12984. % TODO mention trapped-error
  12985. In this chapter we have studied tuples, that is, heterogeneous
  12986. sequences of elements whose length is determined at compile time. This
  12987. challenge is also about sequences, but this time the length is
  12988. determined at runtime and all the elements have the same type (they
  12989. are homogeneous). We use the term \emph{array} for this latter kind of
  12990. sequence.
  12991. %
  12992. \racket{
  12993. The Racket language does not distinguish between tuples and arrays;
  12994. they are both represented by vectors. However, Typed Racket
  12995. distinguishes between tuples and arrays: the \code{Vector} type is for
  12996. tuples, and the \code{Vectorof} type is for arrays.}%
  12997. \python{Arrays correspond to the \code{list} type in the Python language.}
  12998. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12999. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13000. presents the definition of the abstract syntax, extending \LangVec{}
  13001. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13002. \racket{\code{make-vector} primitive operator for creating an array,
  13003. whose arguments are the length of the array and an initial value for
  13004. all the elements in the array.}%
  13005. \python{bracket notation for creating an array literal.}
  13006. \racket{The \code{vector-length},
  13007. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13008. for tuples become overloaded for use with arrays.}
  13009. \python{
  13010. The subscript operator becomes overloaded for use with arrays and tuples
  13011. and now may appear on the left-hand side of an assignment.
  13012. Note that the index of the subscript, when applied to an array, may be an
  13013. arbitrary expression and not exclusively a constant integer.
  13014. The \code{len} function is also applicable to arrays.
  13015. }
  13016. %
  13017. We include integer multiplication in \LangArray{} because it is
  13018. useful in many examples involving arrays such as computing the
  13019. inner product of two arrays (figure~\ref{fig:inner_product}).
  13020. \newcommand{\LarrayGrammarRacket}{
  13021. \begin{array}{lcl}
  13022. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13023. \Exp &::=& \CMUL{\Exp}{\Exp}
  13024. \MID \CMAKEVEC{\Exp}{\Exp}
  13025. \end{array}
  13026. }
  13027. \newcommand{\LarrayASTRacket}{
  13028. \begin{array}{lcl}
  13029. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13030. \Exp &::=& \MUL{\Exp}{\Exp}
  13031. \MID \MAKEVEC{\Exp}{\Exp}
  13032. \end{array}
  13033. }
  13034. \newcommand{\LarrayGrammarPython}{
  13035. \begin{array}{lcl}
  13036. \Type &::=& \key{list}\LS\Type\RS \\
  13037. \Exp &::=& \CMUL{\Exp}{\Exp}
  13038. \MID \CGET{\Exp}{\Exp}
  13039. \MID \LS \Exp \code{,} \ldots \RS \\
  13040. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13041. \end{array}
  13042. }
  13043. \newcommand{\LarrayASTPython}{
  13044. \begin{array}{lcl}
  13045. \Type &::=& \key{ListType}\LP\Type\RP \\
  13046. \Exp &::=& \MUL{\Exp}{\Exp}
  13047. \MID \GET{\Exp}{\Exp} \\
  13048. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13049. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13050. \end{array}
  13051. }
  13052. \begin{figure}[tp]
  13053. \centering
  13054. \begin{tcolorbox}[colback=white]
  13055. \small
  13056. {\if\edition\racketEd
  13057. \[
  13058. \begin{array}{l}
  13059. \gray{\LintGrammarRacket{}} \\ \hline
  13060. \gray{\LvarGrammarRacket{}} \\ \hline
  13061. \gray{\LifGrammarRacket{}} \\ \hline
  13062. \gray{\LwhileGrammarRacket} \\ \hline
  13063. \gray{\LtupGrammarRacket} \\ \hline
  13064. \LarrayGrammarRacket \\
  13065. \begin{array}{lcl}
  13066. \LangArray{} &::=& \Exp
  13067. \end{array}
  13068. \end{array}
  13069. \]
  13070. \fi}
  13071. {\if\edition\pythonEd\pythonColor
  13072. \[
  13073. \begin{array}{l}
  13074. \gray{\LintGrammarPython{}} \\ \hline
  13075. \gray{\LvarGrammarPython{}} \\ \hline
  13076. \gray{\LifGrammarPython{}} \\ \hline
  13077. \gray{\LwhileGrammarPython} \\ \hline
  13078. \gray{\LtupGrammarPython} \\ \hline
  13079. \LarrayGrammarPython \\
  13080. \begin{array}{rcl}
  13081. \LangArrayM{} &::=& \Stmt^{*}
  13082. \end{array}
  13083. \end{array}
  13084. \]
  13085. \fi}
  13086. \end{tcolorbox}
  13087. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13088. \label{fig:Lvecof-concrete-syntax}
  13089. \end{figure}
  13090. \begin{figure}[tp]
  13091. \centering
  13092. \begin{tcolorbox}[colback=white]
  13093. \small
  13094. {\if\edition\racketEd
  13095. \[
  13096. \begin{array}{l}
  13097. \gray{\LintASTRacket{}} \\ \hline
  13098. \gray{\LvarASTRacket{}} \\ \hline
  13099. \gray{\LifASTRacket{}} \\ \hline
  13100. \gray{\LwhileASTRacket} \\ \hline
  13101. \gray{\LtupASTRacket} \\ \hline
  13102. \LarrayASTRacket \\
  13103. \begin{array}{lcl}
  13104. \LangArray{} &::=& \Exp
  13105. \end{array}
  13106. \end{array}
  13107. \]
  13108. \fi}
  13109. {\if\edition\pythonEd\pythonColor
  13110. \[
  13111. \begin{array}{l}
  13112. \gray{\LintASTPython{}} \\ \hline
  13113. \gray{\LvarASTPython{}} \\ \hline
  13114. \gray{\LifASTPython{}} \\ \hline
  13115. \gray{\LwhileASTPython} \\ \hline
  13116. \gray{\LtupASTPython} \\ \hline
  13117. \LarrayASTPython \\
  13118. \begin{array}{rcl}
  13119. \LangArrayM{} &::=& \Stmt^{*}
  13120. \end{array}
  13121. \end{array}
  13122. \]
  13123. \fi}
  13124. \end{tcolorbox}
  13125. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13126. \label{fig:Lvecof-syntax}
  13127. \end{figure}
  13128. \begin{figure}[tp]
  13129. \begin{tcolorbox}[colback=white]
  13130. {\if\edition\racketEd
  13131. % TODO: remove the function from the following example, like the python version -Jeremy
  13132. \begin{lstlisting}
  13133. (let ([A (make-vector 2 2)])
  13134. (let ([B (make-vector 2 3)])
  13135. (let ([i 0])
  13136. (let ([prod 0])
  13137. (begin
  13138. (while (< i n)
  13139. (begin
  13140. (set! prod (+ prod (* (vector-ref A i)
  13141. (vector-ref B i))))
  13142. (set! i (+ i 1))))
  13143. prod)))))
  13144. \end{lstlisting}
  13145. \fi}
  13146. {\if\edition\pythonEd\pythonColor
  13147. \begin{lstlisting}
  13148. A = [2, 2]
  13149. B = [3, 3]
  13150. i = 0
  13151. prod = 0
  13152. while i != len(A):
  13153. prod = prod + A[i] * B[i]
  13154. i = i + 1
  13155. print(prod)
  13156. \end{lstlisting}
  13157. \fi}
  13158. \end{tcolorbox}
  13159. \caption{Example program that computes the inner product.}
  13160. \label{fig:inner_product}
  13161. \end{figure}
  13162. {\if\edition\racketEd
  13163. %
  13164. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13165. checker for \LangArray{}. The result type of
  13166. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13167. of the initializing expression. The length expression is required to
  13168. have type \code{Integer}. The type checking of the operators
  13169. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13170. updated to handle the situation in which the vector has type
  13171. \code{Vectorof}. In these cases we translate the operators to their
  13172. \code{vectorof} form so that later passes can easily distinguish
  13173. between operations on tuples versus arrays. We override the
  13174. \code{operator-types} method to provide the type signature for
  13175. multiplication: it takes two integers and returns an integer. \fi}
  13176. {\if\edition\pythonEd\pythonColor
  13177. %
  13178. The type checker for \LangArray{} is defined in
  13179. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  13180. is \code{list[T]}, where \code{T} is the type of the initializing
  13181. expressions. The type checking of the \code{len} function and the
  13182. subscript operator are updated to handle lists. The type checker now
  13183. also handles a subscript on the left-hand side of an assignment.
  13184. Regarding multiplication, it takes two integers and returns an
  13185. integer.
  13186. %
  13187. \fi}
  13188. \begin{figure}[tbp]
  13189. \begin{tcolorbox}[colback=white]
  13190. {\if\edition\racketEd
  13191. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13192. (define type-check-Lvecof-class
  13193. (class type-check-Lvec-class
  13194. (super-new)
  13195. (inherit check-type-equal?)
  13196. (define/override (operator-types)
  13197. (append '((* . ((Integer Integer) . Integer)))
  13198. (super operator-types)))
  13199. (define/override (type-check-exp env)
  13200. (lambda (e)
  13201. (define recur (type-check-exp env))
  13202. (match e
  13203. [(Prim 'make-vector (list e1 e2))
  13204. (define-values (e1^ t1) (recur e1))
  13205. (define-values (e2^ elt-type) (recur e2))
  13206. (define vec-type `(Vectorof ,elt-type))
  13207. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13208. [(Prim 'vector-ref (list e1 e2))
  13209. (define-values (e1^ t1) (recur e1))
  13210. (define-values (e2^ t2) (recur e2))
  13211. (match* (t1 t2)
  13212. [(`(Vectorof ,elt-type) 'Integer)
  13213. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13214. [(other wise) ((super type-check-exp env) e)])]
  13215. [(Prim 'vector-set! (list e1 e2 e3) )
  13216. (define-values (e-vec t-vec) (recur e1))
  13217. (define-values (e2^ t2) (recur e2))
  13218. (define-values (e-arg^ t-arg) (recur e3))
  13219. (match t-vec
  13220. [`(Vectorof ,elt-type)
  13221. (check-type-equal? elt-type t-arg e)
  13222. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13223. [else ((super type-check-exp env) e)])]
  13224. [(Prim 'vector-length (list e1))
  13225. (define-values (e1^ t1) (recur e1))
  13226. (match t1
  13227. [`(Vectorof ,t)
  13228. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13229. [else ((super type-check-exp env) e)])]
  13230. [else ((super type-check-exp env) e)])))
  13231. ))
  13232. (define (type-check-Lvecof p)
  13233. (send (new type-check-Lvecof-class) type-check-program p))
  13234. \end{lstlisting}
  13235. \fi}
  13236. {\if\edition\pythonEd\pythonColor
  13237. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13238. class TypeCheckLarray(TypeCheckLtup):
  13239. def type_check_exp(self, e, env):
  13240. match e:
  13241. case ast.List(es, Load()):
  13242. ts = [self.type_check_exp(e, env) for e in es]
  13243. elt_ty = ts[0]
  13244. for (ty, elt) in zip(ts, es):
  13245. self.check_type_equal(elt_ty, ty, elt)
  13246. e.has_type = ListType(elt_ty)
  13247. return e.has_type
  13248. case Call(Name('len'), [tup]):
  13249. tup_t = self.type_check_exp(tup, env)
  13250. tup.has_type = tup_t
  13251. match tup_t:
  13252. case TupleType(ts):
  13253. return IntType()
  13254. case ListType(ty):
  13255. return IntType()
  13256. case _:
  13257. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13258. case Subscript(tup, index, Load()):
  13259. tup_ty = self.type_check_exp(tup, env)
  13260. index_ty = self.type_check_exp(index, env)
  13261. self.check_type_equal(index_ty, IntType(), index)
  13262. match tup_ty:
  13263. case TupleType(ts):
  13264. match index:
  13265. case Constant(i):
  13266. return ts[i]
  13267. case _:
  13268. raise Exception('subscript required constant integer index')
  13269. case ListType(ty):
  13270. return ty
  13271. case _:
  13272. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13273. case BinOp(left, Mult(), right):
  13274. l = self.type_check_exp(left, env)
  13275. self.check_type_equal(l, IntType(), left)
  13276. r = self.type_check_exp(right, env)
  13277. self.check_type_equal(r, IntType(), right)
  13278. return IntType()
  13279. case _:
  13280. return super().type_check_exp(e, env)
  13281. \end{lstlisting}
  13282. \fi}
  13283. \end{tcolorbox}
  13284. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13285. \label{fig:type-check-Lvecof}
  13286. \end{figure}
  13287. {\if\edition\pythonEd
  13288. \begin{figure}[tbp]
  13289. \begin{tcolorbox}[colback=white]
  13290. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13291. def type_check_stmts(self, ss, env):
  13292. if len(ss) == 0:
  13293. return VoidType()
  13294. match ss[0]:
  13295. case Assign([Subscript(tup, index, Store())], value):
  13296. tup_t = self.type_check_exp(tup, env)
  13297. value_t = self.type_check_exp(value, env)
  13298. index_ty = self.type_check_exp(index, env)
  13299. self.check_type_equal(index_ty, IntType(), index)
  13300. match tup_t:
  13301. case ListType(ty):
  13302. self.check_type_equal(ty, value_t, ss[0])
  13303. case TupleType(ts):
  13304. return self.type_check_stmts(ss, env)
  13305. case _:
  13306. raise Exception('type_check_stmts: '
  13307. 'expected tuple or list, not ' + repr(tup_t))
  13308. return self.type_check_stmts(ss[1:], env)
  13309. case _:
  13310. return super().type_check_stmts(ss, env)
  13311. \end{lstlisting}
  13312. \end{tcolorbox}
  13313. \caption{Type checker for the \LangArray{} language, part 2.}
  13314. \label{fig:type-check-Lvecof-part2}
  13315. \end{figure}
  13316. \fi}
  13317. The definition of the interpreter for \LangArray{} is shown in
  13318. \racket{figure~\ref{fig:interp-Lvecof}}
  13319. \python{figures~\ref{fig:interp-Lvecof} and \ref{fig:type-check-Lvecof-part2}}.
  13320. \racket{The \code{make-vector} operator is
  13321. interpreted using Racket's \code{make-vector} function,
  13322. and multiplication is interpreted using \code{fx*},
  13323. which is multiplication for \code{fixnum} integers.
  13324. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13325. we translate array access operations
  13326. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13327. which we interpret using \code{vector} operations with additional
  13328. bounds checks that signal a \code{trapped-error}.
  13329. }
  13330. %
  13331. \python{We implement list creation with a Python list comprehension,
  13332. and multiplication is implemented with 64-bit multiplication. We
  13333. add a case to handle a subscript on the left-hand side of
  13334. assignment. Other uses of subscript can be handled by the existing
  13335. code for tuples.}
  13336. \begin{figure}[tbp]
  13337. \begin{tcolorbox}[colback=white]
  13338. {\if\edition\racketEd
  13339. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13340. (define interp-Lvecof-class
  13341. (class interp-Lvec-class
  13342. (super-new)
  13343. (define/override (interp-op op)
  13344. (match op
  13345. ['make-vector make-vector]
  13346. ['vectorof-length vector-length]
  13347. ['vectorof-ref
  13348. (lambda (v i)
  13349. (if (< i (vector-length v))
  13350. (vector-ref v i)
  13351. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13352. ['vectorof-set!
  13353. (lambda (v i e)
  13354. (if (< i (vector-length v))
  13355. (vector-set! v i e)
  13356. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13357. [else (super interp-op op)]))
  13358. ))
  13359. (define (interp-Lvecof p)
  13360. (send (new interp-Lvecof-class) interp-program p))
  13361. \end{lstlisting}
  13362. \fi}
  13363. {\if\edition\pythonEd\pythonColor
  13364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13365. class InterpLarray(InterpLtup):
  13366. def interp_exp(self, e, env):
  13367. match e:
  13368. case ast.List(es, Load()):
  13369. return [self.interp_exp(e, env) for e in es]
  13370. case BinOp(left, Mult(), right):
  13371. l = self.interp_exp(left, env)
  13372. r = self.interp_exp(right, env)
  13373. return mul64(l, r)
  13374. case Subscript(tup, index, Load()):
  13375. t = self.interp_exp(tup, env)
  13376. n = self.interp_exp(index, env)
  13377. if n < len(t):
  13378. return t[n]
  13379. else:
  13380. raise TrappedError('array index out of bounds')
  13381. case _:
  13382. return super().interp_exp(e, env)
  13383. def interp_stmt(self, s, env, cont):
  13384. match s:
  13385. case Assign([Subscript(tup, index)], value):
  13386. t = self.interp_exp(tup, env)
  13387. n = self.interp_exp(index, env)
  13388. if n < len(t):
  13389. t[n] = self.interp_exp(value, env)
  13390. else:
  13391. raise TrappedError('array index out of bounds')
  13392. return self.interp_stmts(cont, env)
  13393. case _:
  13394. return super().interp_stmt(s, env, cont)
  13395. \end{lstlisting}
  13396. \fi}
  13397. \end{tcolorbox}
  13398. \caption{Interpreter for \LangArray{}.}
  13399. \label{fig:interp-Lvecof}
  13400. \end{figure}
  13401. \subsection{Data Representation}
  13402. \label{sec:array-rep}
  13403. Just as with tuples, we store arrays on the heap, which means that the
  13404. garbage collector will need to inspect arrays. An immediate thought is
  13405. to use the same representation for arrays that we use for tuples.
  13406. However, we limit tuples to a length of fifty so that their length and
  13407. pointer mask can fit into the 64-bit tag at the beginning of each
  13408. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13409. millions of elements, so we need more bits to store the length.
  13410. However, because arrays are homogeneous, we need only 1 bit for the
  13411. pointer mask instead of 1 bit per array element. Finally, the
  13412. garbage collector must be able to distinguish between tuples
  13413. and arrays, so we need to reserve one bit for that purpose. We
  13414. arrive at the following layout for the 64-bit tag at the beginning of
  13415. an array:
  13416. \begin{itemize}
  13417. \item The right-most bit is the forwarding bit, just as in a tuple.
  13418. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13419. that it is not.
  13420. \item The next bit to the left is the pointer mask. A $0$ indicates
  13421. that none of the elements are pointers to the heap, and a $1$
  13422. indicates that all the elements are pointers.
  13423. \item The next $60$ bits store the length of the array.
  13424. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13425. and an array ($1$).
  13426. \item The left-most bit is reserved as explained in
  13427. chapter~\ref{ch:Lgrad}.
  13428. \end{itemize}
  13429. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13430. %% differentiate the kinds of values that have been injected into the
  13431. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13432. %% to indicate that the value is an array.
  13433. In the following subsections we provide hints regarding how to update
  13434. the passes to handle arrays.
  13435. \subsection{Overload Resolution}
  13436. \label{sec:array-resolution}
  13437. As noted previously, with the addition of arrays, several operators
  13438. have become \emph{overloaded}; that is, they can be applied to values
  13439. of more than one type. In this case, the element access and length
  13440. operators can be applied to both tuples and arrays. This kind of
  13441. overloading is quite common in programming languages, so many
  13442. compilers perform \emph{overload resolution}\index{subject}{overload
  13443. resolution} to handle it. The idea is to translate each overloaded
  13444. operator into different operators for the different types.
  13445. Implement a new pass named \code{resolve}.
  13446. Translate the reading of an array element
  13447. into a call to
  13448. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13449. and the writing of an array element to
  13450. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13451. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13452. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13453. When these operators are applied to tuples, leave them as is.
  13454. %
  13455. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13456. field, which can be inspected to determine whether the operator
  13457. is applied to a tuple or an array.}
  13458. \subsection{Bounds Checking}
  13459. Recall that the interpreter for \LangArray{} signals a
  13460. \code{trapped-error} when there is an array access that is out of
  13461. bounds. Therefore your compiler is obliged to also catch these errors
  13462. during execution and halt, signaling an error. We recommend inserting
  13463. a new pass named \code{check\_bounds} that inserts code around each
  13464. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13465. \python{subscript} operation to ensure that the index is greater than
  13466. or equal to zero and less than the array's length. If not, the program
  13467. should halt, for which we recommend using a new primitive operation
  13468. named \code{exit}.
  13469. %% \subsection{Reveal Casts}
  13470. %% The array-access operators \code{vectorof-ref} and
  13471. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13472. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13473. %% that the type checker cannot tell whether the index will be in bounds,
  13474. %% so the bounds check must be performed at run time. Recall that the
  13475. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13476. %% an \code{If} around a vector reference for update to check whether
  13477. %% the index is less than the length. You should do the same for
  13478. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13479. %% In addition, the handling of the \code{any-vector} operators in
  13480. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13481. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13482. %% generated code should test whether the tag is for tuples (\code{010})
  13483. %% or arrays (\code{110}) and then dispatch to either
  13484. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13485. %% we add a case in \code{select\_instructions} to generate the
  13486. %% appropriate instructions for accessing the array length from the
  13487. %% header of an array.
  13488. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13489. %% the generated code needs to check that the index is less than the
  13490. %% vector length, so like the code for \code{any-vector-length}, check
  13491. %% the tag to determine whether to use \code{any-vector-length} or
  13492. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13493. %% is complete, the generated code can use \code{any-vector-ref} and
  13494. %% \code{any-vector-set!} for both tuples and arrays because the
  13495. %% instructions used for those operators do not look at the tag at the
  13496. %% front of the tuple or array.
  13497. \subsection{Expose Allocation}
  13498. This pass should translate array creation into lower-level
  13499. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13500. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13501. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13502. array. The \code{AllocateArray} AST node allocates an array of the
  13503. length specified by the $\Exp$ (of type \INTTY), but does not
  13504. initialize the elements of the array. Generate code in this pass to
  13505. initialize the elements analogous to the case for tuples.
  13506. {\if\edition\racketEd
  13507. \subsection{Uncover \texttt{get!}}
  13508. \label{sec:uncover-get-bang-vecof}
  13509. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13510. \code{uncover-get!-exp}.
  13511. \fi}
  13512. \subsection{Remove Complex Operands}
  13513. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13514. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13515. complex, and its subexpression must be atomic.
  13516. \subsection{Explicate Control}
  13517. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13518. \code{explicate\_assign}.
  13519. \subsection{Select Instructions}
  13520. \index{subject}{select instructions}
  13521. Generate instructions for \code{AllocateArray} similar to those for
  13522. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13523. except that the tag at the front of the array should instead use the
  13524. representation discussed in section~\ref{sec:array-rep}.
  13525. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13526. extract the length from the tag.
  13527. The instructions generated for accessing an element of an array differ
  13528. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13529. that the index is not a constant so you need to generate instructions
  13530. that compute the offset at runtime.
  13531. Compile the \code{exit} primitive into a call to the \code{exit}
  13532. function of the C standard library, with an argument of $255$.
  13533. %% Also, note that assignment to an array element may appear in
  13534. %% as a stand-alone statement, so make sure to handle that situation in
  13535. %% this pass.
  13536. %% Finally, the instructions for \code{any-vectorof-length} should be
  13537. %% similar to those for \code{vectorof-length}, except that one must
  13538. %% first project the array by writing zeroes into the $3$-bit tag
  13539. \begin{exercise}\normalfont\normalsize
  13540. Implement a compiler for the \LangArray{} language by extending your
  13541. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13542. programs, including the one shown in figure~\ref{fig:inner_product}
  13543. and also a program that multiplies two matrices. Note that although
  13544. matrices are two-dimensional arrays, they can be encoded into
  13545. one-dimensional arrays by laying out each row in the array, one after
  13546. the next.
  13547. \end{exercise}
  13548. {\if\edition\racketEd
  13549. \section{Challenge: Generational Collection}
  13550. The copying collector described in section~\ref{sec:GC} can incur
  13551. significant runtime overhead because the call to \code{collect} takes
  13552. time proportional to all the live data. One way to reduce this
  13553. overhead is to reduce how much data is inspected in each call to
  13554. \code{collect}. In particular, researchers have observed that recently
  13555. allocated data is more likely to become garbage then data that has
  13556. survived one or more previous calls to \code{collect}. This insight
  13557. motivated the creation of \emph{generational garbage collectors}
  13558. \index{subject}{generational garbage collector} that
  13559. (1) segregate data according to its age into two or more generations;
  13560. (2) allocate less space for younger generations, so collecting them is
  13561. faster, and more space for the older generations; and (3) perform
  13562. collection on the younger generations more frequently than on older
  13563. generations~\citep{Wilson:1992fk}.
  13564. For this challenge assignment, the goal is to adapt the copying
  13565. collector implemented in \code{runtime.c} to use two generations, one
  13566. for young data and one for old data. Each generation consists of a
  13567. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13568. \code{collect} function to use the two generations:
  13569. \begin{enumerate}
  13570. \item Copy the young generation's FromSpace to its ToSpace and then
  13571. switch the role of the ToSpace and FromSpace.
  13572. \item If there is enough space for the requested number of bytes in
  13573. the young FromSpace, then return from \code{collect}.
  13574. \item If there is not enough space in the young FromSpace for the
  13575. requested bytes, then move the data from the young generation to the
  13576. old one with the following steps:
  13577. \begin{enumerate}
  13578. \item[a.] If there is enough room in the old FromSpace, copy the young
  13579. FromSpace to the old FromSpace and then return.
  13580. \item[b.] If there is not enough room in the old FromSpace, then collect
  13581. the old generation by copying the old FromSpace to the old ToSpace
  13582. and swap the roles of the old FromSpace and ToSpace.
  13583. \item[c.] If there is enough room now, copy the young FromSpace to the
  13584. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13585. and ToSpace for the old generation. Copy the young FromSpace and
  13586. the old FromSpace into the larger FromSpace for the old
  13587. generation and then return.
  13588. \end{enumerate}
  13589. \end{enumerate}
  13590. We recommend that you generalize the \code{cheney} function so that it
  13591. can be used for all the copies mentioned: between the young FromSpace
  13592. and ToSpace, between the old FromSpace and ToSpace, and between the
  13593. young FromSpace and old FromSpace. This can be accomplished by adding
  13594. parameters to \code{cheney} that replace its use of the global
  13595. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13596. \code{tospace\_begin}, and \code{tospace\_end}.
  13597. Note that the collection of the young generation does not traverse the
  13598. old generation. This introduces a potential problem: there may be
  13599. young data that is reachable only through pointers in the old
  13600. generation. If these pointers are not taken into account, the
  13601. collector could throw away young data that is live! One solution,
  13602. called \emph{pointer recording}, is to maintain a set of all the
  13603. pointers from the old generation into the new generation and consider
  13604. this set as part of the root set. To maintain this set, the compiler
  13605. must insert extra instructions around every \code{vector-set!}. If the
  13606. vector being modified is in the old generation, and if the value being
  13607. written is a pointer into the new generation, then that pointer must
  13608. be added to the set. Also, if the value being overwritten was a
  13609. pointer into the new generation, then that pointer should be removed
  13610. from the set.
  13611. \begin{exercise}\normalfont\normalsize
  13612. Adapt the \code{collect} function in \code{runtime.c} to implement
  13613. generational garbage collection, as outlined in this section.
  13614. Update the code generation for \code{vector-set!} to implement
  13615. pointer recording. Make sure that your new compiler and runtime
  13616. execute without error on your test suite.
  13617. \end{exercise}
  13618. \fi}
  13619. \section{Further Reading}
  13620. \citet{Appel90} describes many data representation approaches
  13621. including the ones used in the compilation of Standard ML.
  13622. There are many alternatives to copying collectors (and their bigger
  13623. siblings, the generational collectors) with regard to garbage
  13624. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13625. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13626. collectors are that allocation is fast (just a comparison and pointer
  13627. increment), there is no fragmentation, cyclic garbage is collected,
  13628. and the time complexity of collection depends only on the amount of
  13629. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13630. main disadvantages of a two-space copying collector is that it uses a
  13631. lot of extra space and takes a long time to perform the copy, though
  13632. these problems are ameliorated in generational collectors.
  13633. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13634. small objects and generate a lot of garbage, so copying and
  13635. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13636. Garbage collection is an active research topic, especially concurrent
  13637. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13638. developing new techniques and revisiting old
  13639. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13640. meet every year at the International Symposium on Memory Management to
  13641. present these findings.
  13642. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13643. \chapter{Functions}
  13644. \label{ch:Lfun}
  13645. \index{subject}{function}
  13646. \setcounter{footnote}{0}
  13647. This chapter studies the compilation of a subset of \racket{Typed
  13648. Racket}\python{Python} in which only top-level function definitions
  13649. are allowed. This kind of function appears in the C programming
  13650. language, and it serves as an important stepping-stone to implementing
  13651. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13652. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13653. \section{The \LangFun{} Language}
  13654. The concrete syntax and abstract syntax for function definitions and
  13655. function application are shown in
  13656. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13657. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13658. with zero or more function definitions. The function names from these
  13659. definitions are in scope for the entire program, including all the
  13660. function definitions, and therefore the ordering of function
  13661. definitions does not matter.
  13662. %
  13663. \python{The abstract syntax for function parameters in
  13664. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13665. consists of a parameter name and its type. This design differs from
  13666. Python's \code{ast} module, which has a more complex structure for
  13667. function parameters to handle keyword parameters,
  13668. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13669. complex Python abstract syntax into the simpler syntax shown in
  13670. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13671. \code{FunctionDef} constructor are for decorators and a type
  13672. comment, neither of which are used by our compiler. We recommend
  13673. replacing them with \code{None} in the \code{shrink} pass.
  13674. }
  13675. %
  13676. The concrete syntax for function application
  13677. \index{subject}{function application}
  13678. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13679. where the first expression
  13680. must evaluate to a function and the remaining expressions are the arguments. The
  13681. abstract syntax for function application is
  13682. $\APPLY{\Exp}{\Exp^*}$.
  13683. %% The syntax for function application does not include an explicit
  13684. %% keyword, which is error prone when using \code{match}. To alleviate
  13685. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13686. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13687. Functions are first-class in the sense that a function pointer
  13688. \index{subject}{function pointer} is data and can be stored in memory or passed
  13689. as a parameter to another function. Thus, there is a function
  13690. type, written
  13691. {\if\edition\racketEd
  13692. \begin{lstlisting}
  13693. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13694. \end{lstlisting}
  13695. \fi}
  13696. {\if\edition\pythonEd\pythonColor
  13697. \begin{lstlisting}
  13698. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13699. \end{lstlisting}
  13700. \fi}
  13701. %
  13702. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13703. through $\Type_n$ and whose return type is $\Type_R$. The main
  13704. limitation of these functions (with respect to
  13705. \racket{Racket}\python{Python} functions) is that they are not
  13706. lexically scoped. That is, the only external entities that can be
  13707. referenced from inside a function body are other globally defined
  13708. functions. The syntax of \LangFun{} prevents function definitions from
  13709. being nested inside each other.
  13710. \newcommand{\LfunGrammarRacket}{
  13711. \begin{array}{lcl}
  13712. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13713. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13714. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13715. \end{array}
  13716. }
  13717. \newcommand{\LfunASTRacket}{
  13718. \begin{array}{lcl}
  13719. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13720. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13721. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13722. \end{array}
  13723. }
  13724. \newcommand{\LfunGrammarPython}{
  13725. \begin{array}{lcl}
  13726. \Type &::=& \key{int}
  13727. \MID \key{bool} \MID \key{void}
  13728. \MID \key{tuple}\LS \Type^+ \RS
  13729. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13730. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13731. \Stmt &::=& \CRETURN{\Exp} \\
  13732. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13733. \end{array}
  13734. }
  13735. \newcommand{\LfunASTPython}{
  13736. \begin{array}{lcl}
  13737. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13738. \MID \key{TupleType}\LS\Type^+\RS\\
  13739. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13740. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13741. \Stmt &::=& \RETURN{\Exp} \\
  13742. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13743. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13744. \end{array}
  13745. }
  13746. \begin{figure}[tp]
  13747. \centering
  13748. \begin{tcolorbox}[colback=white]
  13749. \small
  13750. {\if\edition\racketEd
  13751. \[
  13752. \begin{array}{l}
  13753. \gray{\LintGrammarRacket{}} \\ \hline
  13754. \gray{\LvarGrammarRacket{}} \\ \hline
  13755. \gray{\LifGrammarRacket{}} \\ \hline
  13756. \gray{\LwhileGrammarRacket} \\ \hline
  13757. \gray{\LtupGrammarRacket} \\ \hline
  13758. \LfunGrammarRacket \\
  13759. \begin{array}{lcl}
  13760. \LangFunM{} &::=& \Def \ldots \; \Exp
  13761. \end{array}
  13762. \end{array}
  13763. \]
  13764. \fi}
  13765. {\if\edition\pythonEd\pythonColor
  13766. \[
  13767. \begin{array}{l}
  13768. \gray{\LintGrammarPython{}} \\ \hline
  13769. \gray{\LvarGrammarPython{}} \\ \hline
  13770. \gray{\LifGrammarPython{}} \\ \hline
  13771. \gray{\LwhileGrammarPython} \\ \hline
  13772. \gray{\LtupGrammarPython} \\ \hline
  13773. \LfunGrammarPython \\
  13774. \begin{array}{rcl}
  13775. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13776. \end{array}
  13777. \end{array}
  13778. \]
  13779. \fi}
  13780. \end{tcolorbox}
  13781. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13782. \label{fig:Lfun-concrete-syntax}
  13783. \end{figure}
  13784. \begin{figure}[tp]
  13785. \centering
  13786. \begin{tcolorbox}[colback=white]
  13787. \small
  13788. {\if\edition\racketEd
  13789. \[
  13790. \begin{array}{l}
  13791. \gray{\LintOpAST} \\ \hline
  13792. \gray{\LvarASTRacket{}} \\ \hline
  13793. \gray{\LifASTRacket{}} \\ \hline
  13794. \gray{\LwhileASTRacket{}} \\ \hline
  13795. \gray{\LtupASTRacket{}} \\ \hline
  13796. \LfunASTRacket \\
  13797. \begin{array}{lcl}
  13798. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13799. \end{array}
  13800. \end{array}
  13801. \]
  13802. \fi}
  13803. {\if\edition\pythonEd\pythonColor
  13804. \[
  13805. \begin{array}{l}
  13806. \gray{\LintASTPython{}} \\ \hline
  13807. \gray{\LvarASTPython{}} \\ \hline
  13808. \gray{\LifASTPython{}} \\ \hline
  13809. \gray{\LwhileASTPython} \\ \hline
  13810. \gray{\LtupASTPython} \\ \hline
  13811. \LfunASTPython \\
  13812. \begin{array}{rcl}
  13813. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13814. \end{array}
  13815. \end{array}
  13816. \]
  13817. \fi}
  13818. \end{tcolorbox}
  13819. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13820. \label{fig:Lfun-syntax}
  13821. \end{figure}
  13822. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13823. representative example of defining and using functions in \LangFun{}.
  13824. We define a function \code{map} that applies some other function
  13825. \code{f} to both elements of a tuple and returns a new tuple
  13826. containing the results. We also define a function \code{inc}. The
  13827. program applies \code{map} to \code{inc} and
  13828. %
  13829. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13830. %
  13831. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13832. %
  13833. from which we return \code{42}.
  13834. \begin{figure}[tbp]
  13835. \begin{tcolorbox}[colback=white]
  13836. {\if\edition\racketEd
  13837. \begin{lstlisting}
  13838. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13839. : (Vector Integer Integer)
  13840. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13841. (define (inc [x : Integer]) : Integer
  13842. (+ x 1))
  13843. (vector-ref (map inc (vector 0 41)) 1)
  13844. \end{lstlisting}
  13845. \fi}
  13846. {\if\edition\pythonEd\pythonColor
  13847. \begin{lstlisting}
  13848. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13849. return f(v[0]), f(v[1])
  13850. def inc(x : int) -> int:
  13851. return x + 1
  13852. print(map(inc, (0, 41))[1])
  13853. \end{lstlisting}
  13854. \fi}
  13855. \end{tcolorbox}
  13856. \caption{Example of using functions in \LangFun{}.}
  13857. \label{fig:Lfun-function-example}
  13858. \end{figure}
  13859. The definitional interpreter for \LangFun{} is shown in
  13860. figure~\ref{fig:interp-Lfun}. The case for the
  13861. %
  13862. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13863. %
  13864. AST is responsible for setting up the mutual recursion between the
  13865. top-level function definitions.
  13866. %
  13867. \racket{We use the classic back-patching
  13868. \index{subject}{back-patching} approach that uses mutable variables
  13869. and makes two passes over the function
  13870. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13871. top-level environment using a mutable cons cell for each function
  13872. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13873. for each function is incomplete; it does not yet include the environment.
  13874. Once the top-level environment has been constructed, we iterate over it and
  13875. update the \code{lambda} values to use the top-level environment.}
  13876. %
  13877. \python{We create a dictionary named \code{env} and fill it in
  13878. by mapping each function name to a new \code{Function} value,
  13879. each of which stores a reference to the \code{env}.
  13880. (We define the class \code{Function} for this purpose.)}
  13881. %
  13882. To interpret a function \racket{application}\python{call}, we match
  13883. the result of the function expression to obtain a function value. We
  13884. then extend the function's environment with the mapping of parameters to
  13885. argument values. Finally, we interpret the body of the function in
  13886. this extended environment.
  13887. \begin{figure}[tp]
  13888. \begin{tcolorbox}[colback=white]
  13889. {\if\edition\racketEd
  13890. \begin{lstlisting}
  13891. (define interp-Lfun-class
  13892. (class interp-Lvec-class
  13893. (super-new)
  13894. (define/override ((interp-exp env) e)
  13895. (define recur (interp-exp env))
  13896. (match e
  13897. [(Apply fun args)
  13898. (define fun-val (recur fun))
  13899. (define arg-vals (for/list ([e args]) (recur e)))
  13900. (match fun-val
  13901. [`(function (,xs ...) ,body ,fun-env)
  13902. (define params-args (for/list ([x xs] [arg arg-vals])
  13903. (cons x (box arg))))
  13904. (define new-env (append params-args fun-env))
  13905. ((interp-exp new-env) body)]
  13906. [else
  13907. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13908. [else ((super interp-exp env) e)]
  13909. ))
  13910. (define/public (interp-def d)
  13911. (match d
  13912. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13913. (cons f (box `(function ,xs ,body ())))]))
  13914. (define/override (interp-program p)
  13915. (match p
  13916. [(ProgramDefsExp info ds body)
  13917. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13918. (for/list ([f (in-dict-values top-level)])
  13919. (set-box! f (match (unbox f)
  13920. [`(function ,xs ,body ())
  13921. `(function ,xs ,body ,top-level)])))
  13922. ((interp-exp top-level) body))]))
  13923. ))
  13924. (define (interp-Lfun p)
  13925. (send (new interp-Lfun-class) interp-program p))
  13926. \end{lstlisting}
  13927. \fi}
  13928. {\if\edition\pythonEd\pythonColor
  13929. \begin{lstlisting}
  13930. class InterpLfun(InterpLtup):
  13931. def apply_fun(self, fun, args, e):
  13932. match fun:
  13933. case Function(name, xs, body, env):
  13934. new_env = env.copy().update(zip(xs, args))
  13935. return self.interp_stmts(body, new_env)
  13936. case _:
  13937. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13938. def interp_exp(self, e, env):
  13939. match e:
  13940. case Call(Name('input_int'), []):
  13941. return super().interp_exp(e, env)
  13942. case Call(func, args):
  13943. f = self.interp_exp(func, env)
  13944. vs = [self.interp_exp(arg, env) for arg in args]
  13945. return self.apply_fun(f, vs, e)
  13946. case _:
  13947. return super().interp_exp(e, env)
  13948. def interp_stmt(self, s, env, cont):
  13949. match s:
  13950. case Return(value):
  13951. return self.interp_exp(value, env)
  13952. case FunctionDef(name, params, bod, dl, returns, comment):
  13953. if isinstance(params, ast.arguments):
  13954. ps = [p.arg for p in params.args]
  13955. else:
  13956. ps = [x for (x,t) in params]
  13957. env[name] = Function(name, ps, bod, env)
  13958. return self.interp_stmts(cont, env)
  13959. case _:
  13960. return super().interp_stmt(s, env, cont)
  13961. def interp(self, p):
  13962. match p:
  13963. case Module(ss):
  13964. env = {}
  13965. self.interp_stmts(ss, env)
  13966. if 'main' in env.keys():
  13967. self.apply_fun(env['main'], [], None)
  13968. case _:
  13969. raise Exception('interp: unexpected ' + repr(p))
  13970. \end{lstlisting}
  13971. \fi}
  13972. \end{tcolorbox}
  13973. \caption{Interpreter for the \LangFun{} language.}
  13974. \label{fig:interp-Lfun}
  13975. \end{figure}
  13976. %\margincomment{TODO: explain type checker}
  13977. The type checker for \LangFun{} is shown in
  13978. figure~\ref{fig:type-check-Lfun}.
  13979. %
  13980. \python{(We omit the code that parses function parameters into the
  13981. simpler abstract syntax.)}
  13982. %
  13983. Similarly to the interpreter, the case for the
  13984. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13985. %
  13986. AST is responsible for setting up the mutual recursion between the
  13987. top-level function definitions. We begin by create a mapping
  13988. \code{env} from every function name to its type. We then type check
  13989. the program using this mapping.
  13990. %
  13991. In the case for function \racket{application}\python{call}, we match
  13992. the type of the function expression to a function type and check that
  13993. the types of the argument expressions are equal to the function's
  13994. parameter types. The type of the \racket{application}\python{call} as
  13995. a whole is the return type from the function type.
  13996. \begin{figure}[tp]
  13997. \begin{tcolorbox}[colback=white]
  13998. {\if\edition\racketEd
  13999. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14000. (define type-check-Lfun-class
  14001. (class type-check-Lvec-class
  14002. (super-new)
  14003. (inherit check-type-equal?)
  14004. (define/public (type-check-apply env e es)
  14005. (define-values (e^ ty) ((type-check-exp env) e))
  14006. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14007. ((type-check-exp env) e)))
  14008. (match ty
  14009. [`(,ty^* ... -> ,rt)
  14010. (for ([arg-ty ty*] [param-ty ty^*])
  14011. (check-type-equal? arg-ty param-ty (Apply e es)))
  14012. (values e^ e* rt)]))
  14013. (define/override (type-check-exp env)
  14014. (lambda (e)
  14015. (match e
  14016. [(FunRef f n)
  14017. (values (FunRef f n) (dict-ref env f))]
  14018. [(Apply e es)
  14019. (define-values (e^ es^ rt) (type-check-apply env e es))
  14020. (values (Apply e^ es^) rt)]
  14021. [(Call e es)
  14022. (define-values (e^ es^ rt) (type-check-apply env e es))
  14023. (values (Call e^ es^) rt)]
  14024. [else ((super type-check-exp env) e)])))
  14025. (define/public (type-check-def env)
  14026. (lambda (e)
  14027. (match e
  14028. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14029. (define new-env (append (map cons xs ps) env))
  14030. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14031. (check-type-equal? ty^ rt body)
  14032. (Def f p:t* rt info body^)])))
  14033. (define/public (fun-def-type d)
  14034. (match d
  14035. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14036. (define/override (type-check-program e)
  14037. (match e
  14038. [(ProgramDefsExp info ds body)
  14039. (define env (for/list ([d ds])
  14040. (cons (Def-name d) (fun-def-type d))))
  14041. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14042. (define-values (body^ ty) ((type-check-exp env) body))
  14043. (check-type-equal? ty 'Integer body)
  14044. (ProgramDefsExp info ds^ body^)]))))
  14045. (define (type-check-Lfun p)
  14046. (send (new type-check-Lfun-class) type-check-program p))
  14047. \end{lstlisting}
  14048. \fi}
  14049. {\if\edition\pythonEd\pythonColor
  14050. \begin{lstlisting}
  14051. class TypeCheckLfun(TypeCheckLtup):
  14052. def type_check_exp(self, e, env):
  14053. match e:
  14054. case Call(Name('input_int'), []):
  14055. return super().type_check_exp(e, env)
  14056. case Call(func, args):
  14057. func_t = self.type_check_exp(func, env)
  14058. args_t = [self.type_check_exp(arg, env) for arg in args]
  14059. match func_t:
  14060. case FunctionType(params_t, return_t):
  14061. for (arg_t, param_t) in zip(args_t, params_t):
  14062. check_type_equal(param_t, arg_t, e)
  14063. return return_t
  14064. case _:
  14065. raise Exception('type_check_exp: in call, unexpected ' +
  14066. repr(func_t))
  14067. case _:
  14068. return super().type_check_exp(e, env)
  14069. def type_check_stmts(self, ss, env):
  14070. if len(ss) == 0:
  14071. return
  14072. match ss[0]:
  14073. case FunctionDef(name, params, body, dl, returns, comment):
  14074. new_env = env.copy().update(params)
  14075. rt = self.type_check_stmts(body, new_env)
  14076. check_type_equal(returns, rt, ss[0])
  14077. return self.type_check_stmts(ss[1:], env)
  14078. case Return(value):
  14079. return self.type_check_exp(value, env)
  14080. case _:
  14081. return super().type_check_stmts(ss, env)
  14082. def type_check(self, p):
  14083. match p:
  14084. case Module(body):
  14085. env = {}
  14086. for s in body:
  14087. match s:
  14088. case FunctionDef(name, params, bod, dl, returns, comment):
  14089. if name in env:
  14090. raise Exception('type_check: function ' +
  14091. repr(name) + ' defined twice')
  14092. params_t = [t for (x,t) in params]
  14093. env[name] = FunctionType(params_t, returns)
  14094. self.type_check_stmts(body, env)
  14095. case _:
  14096. raise Exception('type_check: unexpected ' + repr(p))
  14097. \end{lstlisting}
  14098. \fi}
  14099. \end{tcolorbox}
  14100. \caption{Type checker for the \LangFun{} language.}
  14101. \label{fig:type-check-Lfun}
  14102. \end{figure}
  14103. \clearpage
  14104. \section{Functions in x86}
  14105. \label{sec:fun-x86}
  14106. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14107. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14108. %% \margincomment{\tiny Talk about the return address on the
  14109. %% stack and what callq and retq does.\\ --Jeremy }
  14110. The x86 architecture provides a few features to support the
  14111. implementation of functions. We have already seen that there are
  14112. labels in x86 so that one can refer to the location of an instruction,
  14113. as is needed for jump instructions. Labels can also be used to mark
  14114. the beginning of the instructions for a function. Going further, we
  14115. can obtain the address of a label by using the \key{leaq}
  14116. instruction. For example, the following puts the address of the
  14117. \code{inc} label into the \code{rbx} register:
  14118. \begin{lstlisting}
  14119. leaq inc(%rip), %rbx
  14120. \end{lstlisting}
  14121. Recall from section~\ref{sec:select-instructions-gc} that
  14122. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14123. addressing.
  14124. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14125. to functions whose locations were given by a label, such as
  14126. \code{read\_int}. To support function calls in this chapter we instead
  14127. jump to functions whose location are given by an address in
  14128. a register; that is, we use \emph{indirect function calls}. The
  14129. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14130. before the register name.\index{subject}{indirect function call}
  14131. \begin{lstlisting}
  14132. callq *%rbx
  14133. \end{lstlisting}
  14134. \subsection{Calling Conventions}
  14135. \label{sec:calling-conventions-fun}
  14136. \index{subject}{calling conventions}
  14137. The \code{callq} instruction provides partial support for implementing
  14138. functions: it pushes the return address on the stack and it jumps to
  14139. the target. However, \code{callq} does not handle
  14140. \begin{enumerate}
  14141. \item parameter passing,
  14142. \item pushing frames on the procedure call stack and popping them off,
  14143. or
  14144. \item determining how registers are shared by different functions.
  14145. \end{enumerate}
  14146. Regarding parameter passing, recall that the x86-64 calling
  14147. convention for Unix-based systems uses the following six registers to
  14148. pass arguments to a function, in the given order:
  14149. \begin{lstlisting}
  14150. rdi rsi rdx rcx r8 r9
  14151. \end{lstlisting}
  14152. If there are more than six arguments, then the calling convention
  14153. mandates using space on the frame of the caller for the rest of the
  14154. arguments. However, to ease the implementation of efficient tail calls
  14155. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14156. arguments.
  14157. %
  14158. The return value of the function is stored in register \code{rax}.
  14159. Regarding frames \index{subject}{frame} and the procedure call stack,
  14160. \index{subject}{procedure call stack} recall from
  14161. section~\ref{sec:x86} that the stack grows down and each function call
  14162. uses a chunk of space on the stack called a frame. The caller sets the
  14163. stack pointer, register \code{rsp}, to the last data item in its
  14164. frame. The callee must not change anything in the caller's frame, that
  14165. is, anything that is at or above the stack pointer. The callee is free
  14166. to use locations that are below the stack pointer.
  14167. Recall that we store variables of tuple type on the root stack. So,
  14168. the prelude\index{subject}{prelude} of a function needs to move the
  14169. root stack pointer \code{r15} up according to the number of variables
  14170. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14171. move the root stack pointer back down. Also, the prelude must
  14172. initialize to \code{0} this frame's slots in the root stack to signal
  14173. to the garbage collector that those slots do not yet contain a valid
  14174. pointer. Otherwise the garbage collector will interpret the garbage
  14175. bits in those slots as memory addresses and try to traverse them,
  14176. causing serious mayhem!
  14177. Regarding the sharing of registers between different functions, recall
  14178. from section~\ref{sec:calling-conventions} that the registers are
  14179. divided into two groups, the caller-saved registers and the
  14180. callee-saved registers. The caller should assume that all the
  14181. caller-saved registers are overwritten with arbitrary values by the
  14182. callee. For that reason we recommend in
  14183. section~\ref{sec:calling-conventions} that variables that are live
  14184. during a function call should not be assigned to caller-saved
  14185. registers.
  14186. On the flip side, if the callee wants to use a callee-saved register,
  14187. the callee must save the contents of those registers on their stack
  14188. frame and then put them back prior to returning to the caller. For
  14189. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14190. the register allocator assigns a variable to a callee-saved register,
  14191. then the prelude of the \code{main} function must save that register
  14192. to the stack and the conclusion of \code{main} must restore it. This
  14193. recommendation now generalizes to all functions.
  14194. Recall that the base pointer, register \code{rbp}, is used as a
  14195. point of reference within a frame, so that each local variable can be
  14196. accessed at a fixed offset from the base pointer
  14197. (section~\ref{sec:x86}).
  14198. %
  14199. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14200. frames.
  14201. \begin{figure}[tbp]
  14202. \centering
  14203. \begin{tcolorbox}[colback=white]
  14204. \begin{tabular}{r|r|l|l} \hline
  14205. Caller View & Callee View & Contents & Frame \\ \hline
  14206. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14207. 0(\key{\%rbp}) & & old \key{rbp} \\
  14208. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14209. \ldots & & \ldots \\
  14210. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14211. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14212. \ldots & & \ldots \\
  14213. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14214. %% & & \\
  14215. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14216. %% & \ldots & \ldots \\
  14217. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14218. \hline
  14219. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14220. & 0(\key{\%rbp}) & old \key{rbp} \\
  14221. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14222. & \ldots & \ldots \\
  14223. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14224. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14225. & \ldots & \ldots \\
  14226. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14227. \end{tabular}
  14228. \end{tcolorbox}
  14229. \caption{Memory layout of caller and callee frames.}
  14230. \label{fig:call-frames}
  14231. \end{figure}
  14232. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14233. %% local variables and for storing the values of callee-saved registers
  14234. %% (we shall refer to all of these collectively as ``locals''), and that
  14235. %% at the beginning of a function we move the stack pointer \code{rsp}
  14236. %% down to make room for them.
  14237. %% We recommend storing the local variables
  14238. %% first and then the callee-saved registers, so that the local variables
  14239. %% can be accessed using \code{rbp} the same as before the addition of
  14240. %% functions.
  14241. %% To make additional room for passing arguments, we shall
  14242. %% move the stack pointer even further down. We count how many stack
  14243. %% arguments are needed for each function call that occurs inside the
  14244. %% body of the function and find their maximum. Adding this number to the
  14245. %% number of locals gives us how much the \code{rsp} should be moved at
  14246. %% the beginning of the function. In preparation for a function call, we
  14247. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14248. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14249. %% so on.
  14250. %% Upon calling the function, the stack arguments are retrieved by the
  14251. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14252. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14253. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14254. %% the layout of the caller and callee frames. Notice how important it is
  14255. %% that we correctly compute the maximum number of arguments needed for
  14256. %% function calls; if that number is too small then the arguments and
  14257. %% local variables will smash into each other!
  14258. \subsection{Efficient Tail Calls}
  14259. \label{sec:tail-call}
  14260. In general, the amount of stack space used by a program is determined
  14261. by the longest chain of nested function calls. That is, if function
  14262. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14263. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14264. large if functions are recursive. However, in some cases we can
  14265. arrange to use only a constant amount of space for a long chain of
  14266. nested function calls.
  14267. A \emph{tail call}\index{subject}{tail call} is a function call that
  14268. happens as the last action in a function body. For example, in the
  14269. following program, the recursive call to \code{tail\_sum} is a tail
  14270. call:
  14271. \begin{center}
  14272. {\if\edition\racketEd
  14273. \begin{lstlisting}
  14274. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14275. (if (eq? n 0)
  14276. r
  14277. (tail_sum (- n 1) (+ n r))))
  14278. (+ (tail_sum 3 0) 36)
  14279. \end{lstlisting}
  14280. \fi}
  14281. {\if\edition\pythonEd\pythonColor
  14282. \begin{lstlisting}
  14283. def tail_sum(n : int, r : int) -> int:
  14284. if n == 0:
  14285. return r
  14286. else:
  14287. return tail_sum(n - 1, n + r)
  14288. print(tail_sum(3, 0) + 36)
  14289. \end{lstlisting}
  14290. \fi}
  14291. \end{center}
  14292. At a tail call, the frame of the caller is no longer needed, so we can
  14293. pop the caller's frame before making the tail call. With this
  14294. approach, a recursive function that makes only tail calls ends up
  14295. using a constant amount of stack space. Functional languages like
  14296. Racket rely heavily on recursive functions, so the definition of
  14297. Racket \emph{requires} that all tail calls be optimized in this way.
  14298. \index{subject}{frame}
  14299. Some care is needed with regard to argument passing in tail calls. As
  14300. mentioned, for arguments beyond the sixth, the convention is to use
  14301. space in the caller's frame for passing arguments. However, for a
  14302. tail call we pop the caller's frame and can no longer use it. An
  14303. alternative is to use space in the callee's frame for passing
  14304. arguments. However, this option is also problematic because the caller
  14305. and callee's frames overlap in memory. As we begin to copy the
  14306. arguments from their sources in the caller's frame, the target
  14307. locations in the callee's frame might collide with the sources for
  14308. later arguments! We solve this problem by using the heap instead of
  14309. the stack for passing more than six arguments
  14310. (section~\ref{sec:limit-functions-r4}).
  14311. As mentioned, for a tail call we pop the caller's frame prior to
  14312. making the tail call. The instructions for popping a frame are the
  14313. instructions that we usually place in the conclusion of a
  14314. function. Thus, we also need to place such code immediately before
  14315. each tail call. These instructions include restoring the callee-saved
  14316. registers, so it is fortunate that the argument passing registers are
  14317. all caller-saved registers.
  14318. One note remains regarding which instruction to use to make the tail
  14319. call. When the callee is finished, it should not return to the current
  14320. function but instead return to the function that called the current
  14321. one. Thus, the return address that is already on the stack is the
  14322. right one, and we should not use \key{callq} to make the tail call
  14323. because that would overwrite the return address. Instead we simply use
  14324. the \key{jmp} instruction. As with the indirect function call, we write
  14325. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14326. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14327. jump target because the conclusion can overwrite just about everything
  14328. else.
  14329. \begin{lstlisting}
  14330. jmp *%rax
  14331. \end{lstlisting}
  14332. \section{Shrink \LangFun{}}
  14333. \label{sec:shrink-r4}
  14334. The \code{shrink} pass performs a minor modification to ease the
  14335. later passes. This pass introduces an explicit \code{main} function
  14336. that gobbles up all the top-level statements of the module.
  14337. %
  14338. \racket{It also changes the top \code{ProgramDefsExp} form to
  14339. \code{ProgramDefs}.}
  14340. {\if\edition\racketEd
  14341. \begin{lstlisting}
  14342. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14343. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14344. \end{lstlisting}
  14345. where $\itm{mainDef}$ is
  14346. \begin{lstlisting}
  14347. (Def 'main '() 'Integer '() |$\Exp'$|)
  14348. \end{lstlisting}
  14349. \fi}
  14350. {\if\edition\pythonEd\pythonColor
  14351. \begin{lstlisting}
  14352. Module(|$\Def\ldots\Stmt\ldots$|)
  14353. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14354. \end{lstlisting}
  14355. where $\itm{mainDef}$ is
  14356. \begin{lstlisting}
  14357. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14358. \end{lstlisting}
  14359. \fi}
  14360. \section{Reveal Functions and the \LangFunRef{} Language}
  14361. \label{sec:reveal-functions-r4}
  14362. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14363. in that it conflates the use of function names and local
  14364. variables. This is a problem because we need to compile the use of a
  14365. function name differently from the use of a local variable. In
  14366. particular, we use \code{leaq} to convert the function name (a label
  14367. in x86) to an address in a register. Thus, we create a new pass that
  14368. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14369. $n$ is the arity of the function.\python{\footnote{The arity is not
  14370. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14371. This pass is named \code{reveal\_functions} and the output language
  14372. is \LangFunRef{}.
  14373. %is defined in figure~\ref{fig:f1-syntax}.
  14374. %% The concrete syntax for a
  14375. %% function reference is $\CFUNREF{f}$.
  14376. %% \begin{figure}[tp]
  14377. %% \centering
  14378. %% \fbox{
  14379. %% \begin{minipage}{0.96\textwidth}
  14380. %% {\if\edition\racketEd
  14381. %% \[
  14382. %% \begin{array}{lcl}
  14383. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14384. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14385. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14386. %% \end{array}
  14387. %% \]
  14388. %% \fi}
  14389. %% {\if\edition\pythonEd\pythonColor
  14390. %% \[
  14391. %% \begin{array}{lcl}
  14392. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14393. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14394. %% \end{array}
  14395. %% \]
  14396. %% \fi}
  14397. %% \end{minipage}
  14398. %% }
  14399. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14400. %% (figure~\ref{fig:Lfun-syntax}).}
  14401. %% \label{fig:f1-syntax}
  14402. %% \end{figure}
  14403. %% Distinguishing between calls in tail position and non-tail position
  14404. %% requires the pass to have some notion of context. We recommend using
  14405. %% two mutually recursive functions, one for processing expressions in
  14406. %% tail position and another for the rest.
  14407. \racket{Placing this pass after \code{uniquify} will make sure that
  14408. there are no local variables and functions that share the same
  14409. name.}
  14410. %
  14411. The \code{reveal\_functions} pass should come before the
  14412. \code{remove\_complex\_operands} pass because function references
  14413. should be categorized as complex expressions.
  14414. \section{Limit Functions}
  14415. \label{sec:limit-functions-r4}
  14416. Recall that we wish to limit the number of function parameters to six
  14417. so that we do not need to use the stack for argument passing, which
  14418. makes it easier to implement efficient tail calls. However, because
  14419. the input language \LangFun{} supports arbitrary numbers of function
  14420. arguments, we have some work to do! The \code{limit\_functions} pass
  14421. transforms functions and function calls that involve more than six
  14422. arguments to pass the first five arguments as usual, but it packs the
  14423. rest of the arguments into a tuple and passes it as the sixth
  14424. argument.\footnote{The implementation this pass can be postponed to
  14425. last because you can test the rest of the passes on functions with
  14426. six or fewer parameters.}
  14427. Each function definition with seven or more parameters is transformed as
  14428. follows:
  14429. {\if\edition\racketEd
  14430. \begin{lstlisting}
  14431. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14432. |$\Rightarrow$|
  14433. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14434. \end{lstlisting}
  14435. \fi}
  14436. {\if\edition\pythonEd\pythonColor
  14437. \begin{lstlisting}
  14438. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14439. |$\Rightarrow$|
  14440. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14441. |$T_r$|, None, |$\itm{body}'$|, None)
  14442. \end{lstlisting}
  14443. \fi}
  14444. %
  14445. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14446. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14447. the $k$th element of the tuple, where $k = i - 6$.
  14448. %
  14449. {\if\edition\racketEd
  14450. \begin{lstlisting}
  14451. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14452. \end{lstlisting}
  14453. \fi}
  14454. {\if\edition\pythonEd\pythonColor
  14455. \begin{lstlisting}
  14456. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14457. \end{lstlisting}
  14458. \fi}
  14459. For function calls with too many arguments, the \code{limit\_functions}
  14460. pass transforms them in the following way:
  14461. \begin{tabular}{lll}
  14462. \begin{minipage}{0.3\textwidth}
  14463. {\if\edition\racketEd
  14464. \begin{lstlisting}
  14465. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14466. \end{lstlisting}
  14467. \fi}
  14468. {\if\edition\pythonEd\pythonColor
  14469. \begin{lstlisting}
  14470. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14471. \end{lstlisting}
  14472. \fi}
  14473. \end{minipage}
  14474. &
  14475. $\Rightarrow$
  14476. &
  14477. \begin{minipage}{0.5\textwidth}
  14478. {\if\edition\racketEd
  14479. \begin{lstlisting}
  14480. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14481. \end{lstlisting}
  14482. \fi}
  14483. {\if\edition\pythonEd\pythonColor
  14484. \begin{lstlisting}
  14485. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14486. \end{lstlisting}
  14487. \fi}
  14488. \end{minipage}
  14489. \end{tabular}
  14490. \section{Remove Complex Operands}
  14491. \label{sec:rco-r4}
  14492. The primary decisions to make for this pass are whether to classify
  14493. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14494. atomic or complex expressions. Recall that an atomic expression
  14495. ends up as an immediate argument of an x86 instruction. Function
  14496. application translates to a sequence of instructions, so
  14497. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14498. a complex expression. On the other hand, the arguments of
  14499. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14500. expressions.
  14501. %
  14502. Regarding \code{FunRef}, as discussed previously, the function label
  14503. needs to be converted to an address using the \code{leaq}
  14504. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14505. needs to be classified as a complex expression so that we generate an
  14506. assignment statement with a left-hand side that can serve as the
  14507. target of the \code{leaq}.
  14508. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14509. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14510. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14511. and augments programs to include a list of function definitions.
  14512. %
  14513. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14514. \newcommand{\LfunMonadASTRacket}{
  14515. \begin{array}{lcl}
  14516. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14517. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14518. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14519. \end{array}
  14520. }
  14521. \newcommand{\LfunMonadASTPython}{
  14522. \begin{array}{lcl}
  14523. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14524. \MID \key{TupleType}\LS\Type^+\RS\\
  14525. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14526. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14527. \Stmt &::=& \RETURN{\Exp} \\
  14528. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14529. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14530. \end{array}
  14531. }
  14532. \begin{figure}[tp]
  14533. \centering
  14534. \begin{tcolorbox}[colback=white]
  14535. \small
  14536. {\if\edition\racketEd
  14537. \[
  14538. \begin{array}{l}
  14539. \gray{\LvarMonadASTRacket} \\ \hline
  14540. \gray{\LifMonadASTRacket} \\ \hline
  14541. \gray{\LwhileMonadASTRacket} \\ \hline
  14542. \gray{\LtupMonadASTRacket} \\ \hline
  14543. \LfunMonadASTRacket \\
  14544. \begin{array}{rcl}
  14545. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14546. \end{array}
  14547. \end{array}
  14548. \]
  14549. \fi}
  14550. {\if\edition\pythonEd\pythonColor
  14551. \[
  14552. \begin{array}{l}
  14553. \gray{\LvarMonadASTPython} \\ \hline
  14554. \gray{\LifMonadASTPython} \\ \hline
  14555. \gray{\LwhileMonadASTPython} \\ \hline
  14556. \gray{\LtupMonadASTPython} \\ \hline
  14557. \LfunMonadASTPython \\
  14558. \begin{array}{rcl}
  14559. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14560. \end{array}
  14561. \end{array}
  14562. \]
  14563. \fi}
  14564. \end{tcolorbox}
  14565. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14566. \label{fig:Lfun-anf-syntax}
  14567. \end{figure}
  14568. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14569. %% \LangFunANF{} of this pass.
  14570. %% \begin{figure}[tp]
  14571. %% \centering
  14572. %% \fbox{
  14573. %% \begin{minipage}{0.96\textwidth}
  14574. %% \small
  14575. %% \[
  14576. %% \begin{array}{rcl}
  14577. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14578. %% \MID \VOID{} } \\
  14579. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14580. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14581. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14582. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14583. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14584. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14585. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14586. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14587. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14588. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14589. %% \end{array}
  14590. %% \]
  14591. %% \end{minipage}
  14592. %% }
  14593. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14594. %% \label{fig:Lfun-anf-syntax}
  14595. %% \end{figure}
  14596. \section{Explicate Control and the \LangCFun{} Language}
  14597. \label{sec:explicate-control-r4}
  14598. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14599. output of \code{explicate\_control}.
  14600. %
  14601. %% \racket{(The concrete syntax is given in
  14602. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14603. %
  14604. The auxiliary functions for assignment\racket{ and tail contexts} should
  14605. be updated with cases for
  14606. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14607. function for predicate context should be updated for
  14608. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14609. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14610. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14611. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14612. auxiliary function for processing function definitions. This code is
  14613. similar to the case for \code{Program} in \LangVec{}. The top-level
  14614. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14615. form of \LangFun{} can then apply this new function to all the
  14616. function definitions.
  14617. {\if\edition\pythonEd\pythonColor
  14618. The translation of \code{Return} statements requires a new auxiliary
  14619. function to handle expressions in tail context, called
  14620. \code{explicate\_tail}. The function should take an expression and the
  14621. dictionary of basic blocks and produce a list of statements in the
  14622. \LangCFun{} language. The \code{explicate\_tail} function should
  14623. include cases for \code{Begin}, \code{IfExp}, \code{Let}, and \code{Call},
  14624. and a default case for other kinds of expressions. The default case
  14625. should produce a \code{Return} statement. The case for \code{Call}
  14626. should change it into \code{TailCall}. The other cases should
  14627. recursively process their subexpressions and statements, choosing the
  14628. appropriate explicate functions for the various contexts.
  14629. \fi}
  14630. \newcommand{\CfunASTRacket}{
  14631. \begin{array}{lcl}
  14632. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14633. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14634. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14635. \end{array}
  14636. }
  14637. \newcommand{\CfunASTPython}{
  14638. \begin{array}{lcl}
  14639. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14640. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14641. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14642. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14643. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14644. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14645. \end{array}
  14646. }
  14647. \begin{figure}[tp]
  14648. \begin{tcolorbox}[colback=white]
  14649. \small
  14650. {\if\edition\racketEd
  14651. \[
  14652. \begin{array}{l}
  14653. \gray{\CvarASTRacket} \\ \hline
  14654. \gray{\CifASTRacket} \\ \hline
  14655. \gray{\CloopASTRacket} \\ \hline
  14656. \gray{\CtupASTRacket} \\ \hline
  14657. \CfunASTRacket \\
  14658. \begin{array}{lcl}
  14659. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14660. \end{array}
  14661. \end{array}
  14662. \]
  14663. \fi}
  14664. {\if\edition\pythonEd\pythonColor
  14665. \[
  14666. \begin{array}{l}
  14667. \gray{\CifASTPython} \\ \hline
  14668. \gray{\CtupASTPython} \\ \hline
  14669. \CfunASTPython \\
  14670. \begin{array}{lcl}
  14671. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14672. \end{array}
  14673. \end{array}
  14674. \]
  14675. \fi}
  14676. \end{tcolorbox}
  14677. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14678. \label{fig:c3-syntax}
  14679. \end{figure}
  14680. \clearpage
  14681. \section{Select Instructions and the \LangXIndCall{} Language}
  14682. \label{sec:select-r4}
  14683. \index{subject}{select instructions}
  14684. The output of select instructions is a program in the \LangXIndCall{}
  14685. language; the definition of its concrete syntax is shown in
  14686. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14687. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14688. directive on the labels of function definitions to make sure the
  14689. bottom three bits are zero, which we put to use in
  14690. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14691. this section. \index{subject}{x86}
  14692. \newcommand{\GrammarXIndCall}{
  14693. \begin{array}{lcl}
  14694. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14695. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14696. \Block &::= & \Instr^{+} \\
  14697. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14698. \end{array}
  14699. }
  14700. \newcommand{\ASTXIndCallRacket}{
  14701. \begin{array}{lcl}
  14702. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14703. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14704. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14705. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14706. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14707. \end{array}
  14708. }
  14709. \begin{figure}[tp]
  14710. \begin{tcolorbox}[colback=white]
  14711. \small
  14712. \[
  14713. \begin{array}{l}
  14714. \gray{\GrammarXInt} \\ \hline
  14715. \gray{\GrammarXIf} \\ \hline
  14716. \gray{\GrammarXGlobal} \\ \hline
  14717. \GrammarXIndCall \\
  14718. \begin{array}{lcl}
  14719. \LangXIndCallM{} &::= & \Def^{*}
  14720. \end{array}
  14721. \end{array}
  14722. \]
  14723. \end{tcolorbox}
  14724. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14725. \label{fig:x86-3-concrete}
  14726. \end{figure}
  14727. \begin{figure}[tp]
  14728. \begin{tcolorbox}[colback=white]
  14729. \small
  14730. {\if\edition\racketEd
  14731. \[\arraycolsep=3pt
  14732. \begin{array}{l}
  14733. \gray{\ASTXIntRacket} \\ \hline
  14734. \gray{\ASTXIfRacket} \\ \hline
  14735. \gray{\ASTXGlobalRacket} \\ \hline
  14736. \ASTXIndCallRacket \\
  14737. \begin{array}{lcl}
  14738. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14739. \end{array}
  14740. \end{array}
  14741. \]
  14742. \fi}
  14743. {\if\edition\pythonEd\pythonColor
  14744. \[
  14745. \begin{array}{lcl}
  14746. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14747. \MID \BYTEREG{\Reg} } \\
  14748. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14749. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14750. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14751. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14752. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14753. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14754. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14755. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14756. \end{array}
  14757. \]
  14758. \fi}
  14759. \end{tcolorbox}
  14760. \caption{The abstract syntax of \LangXIndCall{} (extends
  14761. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14762. \label{fig:x86-3}
  14763. \end{figure}
  14764. An assignment of a function reference to a variable becomes a
  14765. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14766. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14767. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14768. node, whose concrete syntax is instruction-pointer-relative
  14769. addressing.
  14770. \begin{center}
  14771. \begin{tabular}{lcl}
  14772. \begin{minipage}{0.35\textwidth}
  14773. {\if\edition\racketEd
  14774. \begin{lstlisting}
  14775. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14776. \end{lstlisting}
  14777. \fi}
  14778. {\if\edition\pythonEd\pythonColor
  14779. \begin{lstlisting}
  14780. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14781. \end{lstlisting}
  14782. \fi}
  14783. \end{minipage}
  14784. &
  14785. $\Rightarrow$\qquad\qquad
  14786. &
  14787. \begin{minipage}{0.3\textwidth}
  14788. \begin{lstlisting}
  14789. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14790. \end{lstlisting}
  14791. \end{minipage}
  14792. \end{tabular}
  14793. \end{center}
  14794. Regarding function definitions, we need to remove the parameters and
  14795. instead perform parameter passing using the conventions discussed in
  14796. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14797. registers. We recommend turning the parameters into local variables
  14798. and generating instructions at the beginning of the function to move
  14799. from the argument-passing registers
  14800. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14801. {\if\edition\racketEd
  14802. \begin{lstlisting}
  14803. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14804. |$\Rightarrow$|
  14805. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14806. \end{lstlisting}
  14807. \fi}
  14808. {\if\edition\pythonEd\pythonColor
  14809. \begin{lstlisting}
  14810. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14811. |$\Rightarrow$|
  14812. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14813. \end{lstlisting}
  14814. \fi}
  14815. The basic blocks $B'$ are the same as $B$ except that the
  14816. \code{start} block is modified to add the instructions for moving from
  14817. the argument registers to the parameter variables. So the \code{start}
  14818. block of $B$ shown on the left of the following is changed to the code
  14819. on the right:
  14820. \begin{center}
  14821. \begin{minipage}{0.3\textwidth}
  14822. \begin{lstlisting}
  14823. start:
  14824. |$\itm{instr}_1$|
  14825. |$\cdots$|
  14826. |$\itm{instr}_n$|
  14827. \end{lstlisting}
  14828. \end{minipage}
  14829. $\Rightarrow$
  14830. \begin{minipage}{0.3\textwidth}
  14831. \begin{lstlisting}
  14832. |$f$|start:
  14833. movq %rdi, |$x_1$|
  14834. movq %rsi, |$x_2$|
  14835. |$\cdots$|
  14836. |$\itm{instr}_1$|
  14837. |$\cdots$|
  14838. |$\itm{instr}_n$|
  14839. \end{lstlisting}
  14840. \end{minipage}
  14841. \end{center}
  14842. Recall that we use the label \code{start} for the initial block of a
  14843. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14844. the conclusion of the program with \code{conclusion}, so that
  14845. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14846. by a jump to \code{conclusion}. With the addition of function
  14847. definitions, there is a start block and conclusion for each function,
  14848. but their labels need to be unique. We recommend prepending the
  14849. function's name to \code{start} and \code{conclusion}, respectively,
  14850. to obtain unique labels.
  14851. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14852. number of parameters the function expects, but the parameters are no
  14853. longer in the syntax of function definitions. Instead, add an entry
  14854. to $\itm{info}$ that maps \code{num-params} to the number of
  14855. parameters to construct $\itm{info}'$.}
  14856. By changing the parameters to local variables, we are giving the
  14857. register allocator control over which registers or stack locations to
  14858. use for them. If you implement the move-biasing challenge
  14859. (section~\ref{sec:move-biasing}), the register allocator will try to
  14860. assign the parameter variables to the corresponding argument register,
  14861. in which case the \code{patch\_instructions} pass will remove the
  14862. \code{movq} instruction. This happens in the example translation given
  14863. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14864. the \code{add} function.
  14865. %
  14866. Also, note that the register allocator will perform liveness analysis
  14867. on this sequence of move instructions and build the interference
  14868. graph. So, for example, $x_1$ will be marked as interfering with
  14869. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14870. which is good because otherwise the first \code{movq} would overwrite
  14871. the argument in \code{rsi} that is needed for $x_2$.
  14872. Next, consider the compilation of function calls. In the mirror image
  14873. of the handling of parameters in function definitions, the arguments
  14874. are moved to the argument-passing registers. Note that the function
  14875. is not given as a label, but its address is produced by the argument
  14876. $\itm{arg}_0$. So, we translate the call into an indirect function
  14877. call. The return value from the function is stored in \code{rax}, so
  14878. it needs to be moved into the \itm{lhs}.
  14879. \begin{lstlisting}
  14880. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14881. |$\Rightarrow$|
  14882. movq |$\itm{arg}_1$|, %rdi
  14883. movq |$\itm{arg}_2$|, %rsi
  14884. |$\vdots$|
  14885. callq *|$\itm{arg}_0$|
  14886. movq %rax, |$\itm{lhs}$|
  14887. \end{lstlisting}
  14888. The \code{IndirectCallq} AST node includes an integer for the arity of
  14889. the function, that is, the number of parameters. That information is
  14890. useful in the \code{uncover\_live} pass for determining which
  14891. argument-passing registers are potentially read during the call.
  14892. For tail calls, the parameter passing is the same as non-tail calls:
  14893. generate instructions to move the arguments into the argument-passing
  14894. registers. After that we need to pop the frame from the procedure
  14895. call stack. However, we do not yet know how big the frame is; that
  14896. gets determined during register allocation. So, instead of generating
  14897. those instructions here, we invent a new instruction that means ``pop
  14898. the frame and then do an indirect jump,'' which we name
  14899. \code{TailJmp}. The abstract syntax for this instruction includes an
  14900. argument that specifies where to jump and an integer that represents
  14901. the arity of the function being called.
  14902. \section{Register Allocation}
  14903. \label{sec:register-allocation-r4}
  14904. The addition of functions requires some changes to all three aspects
  14905. of register allocation, which we discuss in the following subsections.
  14906. \subsection{Liveness Analysis}
  14907. \label{sec:liveness-analysis-r4}
  14908. \index{subject}{liveness analysis}
  14909. %% The rest of the passes need only minor modifications to handle the new
  14910. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14911. %% \code{leaq}.
  14912. The \code{IndirectCallq} instruction should be treated like
  14913. \code{Callq} regarding its written locations $W$, in that they should
  14914. include all the caller-saved registers. Recall that the reason for
  14915. that is to force variables that are live across a function call to be assigned to callee-saved
  14916. registers or to be spilled to the stack.
  14917. Regarding the set of read locations $R$, the arity fields of
  14918. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14919. argument-passing registers should be considered as read by those
  14920. instructions. Also, the target field of \code{TailJmp} and
  14921. \code{IndirectCallq} should be included in the set of read locations
  14922. $R$.
  14923. \subsection{Build Interference Graph}
  14924. \label{sec:build-interference-r4}
  14925. With the addition of function definitions, we compute a separate interference
  14926. graph for each function (not just one for the whole program).
  14927. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14928. spill tuple-typed variables that are live during a call to
  14929. \code{collect}, the garbage collector. With the addition of functions
  14930. to our language, we need to revisit this issue. Functions that perform
  14931. allocation contain calls to the collector. Thus, we should not only
  14932. spill a tuple-typed variable when it is live during a call to
  14933. \code{collect}, but we should spill the variable if it is live during
  14934. a call to any user-defined function. Thus, in the
  14935. \code{build\_interference} pass, we recommend adding interference
  14936. edges between call-live tuple-typed variables and the callee-saved
  14937. registers (in addition to creating edges between
  14938. call-live variables and the caller-saved registers).
  14939. \subsection{Allocate Registers}
  14940. The primary change to the \code{allocate\_registers} pass is adding an
  14941. auxiliary function for handling definitions (the \Def{} nonterminal
  14942. shown in figure~\ref{fig:x86-3}) with one case for function
  14943. definitions. The logic is the same as described in
  14944. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14945. allocation is performed many times, once for each function definition,
  14946. instead of just once for the whole program.
  14947. \section{Patch Instructions}
  14948. In \code{patch\_instructions}, you should deal with the x86
  14949. idiosyncrasy that the destination argument of \code{leaq} must be a
  14950. register. Additionally, you should ensure that the argument of
  14951. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14952. trample many other registers before the tail call, as explained in the
  14953. next section.
  14954. \section{Prelude and Conclusion}
  14955. Now that register allocation is complete, we can translate the
  14956. \code{TailJmp} into a sequence of instructions. A naive translation of
  14957. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14958. before the jump we need to pop the current frame to achieve efficient
  14959. tail calls. This sequence of instructions is the same as the code for
  14960. the conclusion of a function, except that the \code{retq} is replaced with
  14961. \code{jmp *$\itm{arg}$}.
  14962. Regarding function definitions, we generate a prelude and conclusion
  14963. for each one. This code is similar to the prelude and conclusion
  14964. generated for the \code{main} function presented in
  14965. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14966. carry out the following steps:
  14967. % TODO: .align the functions!
  14968. \begin{enumerate}
  14969. %% \item Start with \code{.global} and \code{.align} directives followed
  14970. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14971. %% example.)
  14972. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14973. pointer.
  14974. \item Push to the stack all the callee-saved registers that were
  14975. used for register allocation.
  14976. \item Move the stack pointer \code{rsp} down to make room for the
  14977. regular spills (aligned to 16 bytes).
  14978. \item Move the root stack pointer \code{r15} up by the size of the
  14979. root-stack frame for this function, which depends on the number of
  14980. spilled tuple-typed variables. \label{root-stack-init}
  14981. \item Initialize to zero all new entries in the root-stack frame.
  14982. \item Jump to the start block.
  14983. \end{enumerate}
  14984. The prelude of the \code{main} function has an additional task: call
  14985. the \code{initialize} function to set up the garbage collector, and
  14986. then move the value of the global \code{rootstack\_begin} in
  14987. \code{r15}. This initialization should happen before step
  14988. \ref{root-stack-init}, which depends on \code{r15}.
  14989. The conclusion of every function should do the following:
  14990. \begin{enumerate}
  14991. \item Move the stack pointer back up past the regular spills.
  14992. \item Restore the callee-saved registers by popping them from the
  14993. stack.
  14994. \item Move the root stack pointer back down by the size of the
  14995. root-stack frame for this function.
  14996. \item Restore \code{rbp} by popping it from the stack.
  14997. \item Return to the caller with the \code{retq} instruction.
  14998. \end{enumerate}
  14999. The output of this pass is \LangXIndCallFlat{}, which differs from
  15000. \LangXIndCall{} in that there is no longer an AST node for function
  15001. definitions. Instead, a program is just an association list of basic
  15002. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15003. \[
  15004. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15005. \]
  15006. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15007. compiling \LangFun{} to x86.
  15008. \begin{exercise}\normalfont\normalsize
  15009. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15010. Create eight new programs that use functions including examples that
  15011. pass functions and return functions from other functions, recursive
  15012. functions, functions that create vectors, and functions that make tail
  15013. calls. Test your compiler on these new programs and all your
  15014. previously created test programs.
  15015. \end{exercise}
  15016. \begin{figure}[tbp]
  15017. \begin{tcolorbox}[colback=white]
  15018. {\if\edition\racketEd
  15019. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15020. \node (Lfun) at (0,2) {\large \LangFun{}};
  15021. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15022. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15023. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15024. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15025. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15026. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15027. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15028. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15029. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15030. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15031. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15032. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15033. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15034. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15035. \path[->,bend left=15] (Lfun) edge [above] node
  15036. {\ttfamily\footnotesize shrink} (Lfun-1);
  15037. \path[->,bend left=15] (Lfun-1) edge [above] node
  15038. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15039. \path[->,bend left=15] (Lfun-2) edge [above] node
  15040. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15041. \path[->,bend left=15] (F1-1) edge [left] node
  15042. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15043. \path[->,bend left=15] (F1-2) edge [below] node
  15044. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15045. \path[->,bend left=15] (F1-3) edge [below] node
  15046. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15047. \path[->,bend right=15] (F1-4) edge [above] node
  15048. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15049. \path[->,bend right=15] (F1-5) edge [right] node
  15050. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15051. \path[->,bend right=15] (C3-2) edge [right] node
  15052. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15053. \path[->,bend left=15] (x86-2) edge [right] node
  15054. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15055. \path[->,bend right=15] (x86-2-1) edge [below] node
  15056. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15057. \path[->,bend right=15] (x86-2-2) edge [right] node
  15058. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15059. \path[->,bend left=15] (x86-3) edge [above] node
  15060. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15061. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15062. \end{tikzpicture}
  15063. \fi}
  15064. {\if\edition\pythonEd\pythonColor
  15065. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15066. \node (Lfun) at (0,2) {\large \LangFun{}};
  15067. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15068. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15069. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15070. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15071. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15072. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15073. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15074. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15075. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15076. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15077. \path[->,bend left=15] (Lfun) edge [above] node
  15078. {\ttfamily\footnotesize shrink} (Lfun-2);
  15079. \path[->,bend left=15] (Lfun-2) edge [above] node
  15080. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15081. \path[->,bend left=15] (F1-1) edge [above] node
  15082. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15083. \path[->,bend left=15] (F1-2) edge [right] node
  15084. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15085. \path[->,bend right=15] (F1-4) edge [above] node
  15086. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15087. \path[->,bend right=15] (F1-5) edge [right] node
  15088. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15089. \path[->,bend left=15] (C3-2) edge [right] node
  15090. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15091. \path[->,bend right=15] (x86-2) edge [below] node
  15092. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15093. \path[->,bend left=15] (x86-3) edge [above] node
  15094. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15095. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15096. \end{tikzpicture}
  15097. \fi}
  15098. \end{tcolorbox}
  15099. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15100. \label{fig:Lfun-passes}
  15101. \end{figure}
  15102. \section{An Example Translation}
  15103. \label{sec:functions-example}
  15104. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15105. function in \LangFun{} to x86. The figure includes the results of
  15106. \code{explicate\_control} and \code{select\_instructions}.
  15107. \begin{figure}[hbtp]
  15108. \begin{tcolorbox}[colback=white]
  15109. \begin{tabular}{ll}
  15110. \begin{minipage}{0.4\textwidth}
  15111. % s3_2.rkt
  15112. {\if\edition\racketEd
  15113. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15114. (define (add [x : Integer]
  15115. [y : Integer])
  15116. : Integer
  15117. (+ x y))
  15118. (add 40 2)
  15119. \end{lstlisting}
  15120. \fi}
  15121. {\if\edition\pythonEd\pythonColor
  15122. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15123. def add(x:int, y:int) -> int:
  15124. return x + y
  15125. print(add(40, 2))
  15126. \end{lstlisting}
  15127. \fi}
  15128. $\Downarrow$
  15129. {\if\edition\racketEd
  15130. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15131. (define (add86 [x87 : Integer]
  15132. [y88 : Integer])
  15133. : Integer
  15134. add86start:
  15135. return (+ x87 y88);
  15136. )
  15137. (define (main) : Integer ()
  15138. mainstart:
  15139. tmp89 = (fun-ref add86 2);
  15140. (tail-call tmp89 40 2)
  15141. )
  15142. \end{lstlisting}
  15143. \fi}
  15144. {\if\edition\pythonEd\pythonColor
  15145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15146. def add(x:int, y:int) -> int:
  15147. addstart:
  15148. return x + y
  15149. def main() -> int:
  15150. mainstart:
  15151. fun.0 = add
  15152. tmp.1 = fun.0(40, 2)
  15153. print(tmp.1)
  15154. return 0
  15155. \end{lstlisting}
  15156. \fi}
  15157. \end{minipage}
  15158. &
  15159. $\Rightarrow$
  15160. \begin{minipage}{0.5\textwidth}
  15161. {\if\edition\racketEd
  15162. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15163. (define (add86) : Integer
  15164. add86start:
  15165. movq %rdi, x87
  15166. movq %rsi, y88
  15167. movq x87, %rax
  15168. addq y88, %rax
  15169. jmp inc1389conclusion
  15170. )
  15171. (define (main) : Integer
  15172. mainstart:
  15173. leaq (fun-ref add86 2), tmp89
  15174. movq $40, %rdi
  15175. movq $2, %rsi
  15176. tail-jmp tmp89
  15177. )
  15178. \end{lstlisting}
  15179. \fi}
  15180. {\if\edition\pythonEd\pythonColor
  15181. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15182. def add() -> int:
  15183. addstart:
  15184. movq %rdi, x
  15185. movq %rsi, y
  15186. movq x, %rax
  15187. addq y, %rax
  15188. jmp addconclusion
  15189. def main() -> int:
  15190. mainstart:
  15191. leaq add, fun.0
  15192. movq $40, %rdi
  15193. movq $2, %rsi
  15194. callq *fun.0
  15195. movq %rax, tmp.1
  15196. movq tmp.1, %rdi
  15197. callq print_int
  15198. movq $0, %rax
  15199. jmp mainconclusion
  15200. \end{lstlisting}
  15201. \fi}
  15202. $\Downarrow$
  15203. \end{minipage}
  15204. \end{tabular}
  15205. \begin{tabular}{ll}
  15206. \begin{minipage}{0.3\textwidth}
  15207. {\if\edition\racketEd
  15208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15209. .globl add86
  15210. .align 8
  15211. add86:
  15212. pushq %rbp
  15213. movq %rsp, %rbp
  15214. jmp add86start
  15215. add86start:
  15216. movq %rdi, %rax
  15217. addq %rsi, %rax
  15218. jmp add86conclusion
  15219. add86conclusion:
  15220. popq %rbp
  15221. retq
  15222. \end{lstlisting}
  15223. \fi}
  15224. {\if\edition\pythonEd\pythonColor
  15225. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15226. .align 8
  15227. add:
  15228. pushq %rbp
  15229. movq %rsp, %rbp
  15230. subq $0, %rsp
  15231. jmp addstart
  15232. addstart:
  15233. movq %rdi, %rdx
  15234. movq %rsi, %rcx
  15235. movq %rdx, %rax
  15236. addq %rcx, %rax
  15237. jmp addconclusion
  15238. addconclusion:
  15239. subq $0, %r15
  15240. addq $0, %rsp
  15241. popq %rbp
  15242. retq
  15243. \end{lstlisting}
  15244. \fi}
  15245. \end{minipage}
  15246. &
  15247. \begin{minipage}{0.5\textwidth}
  15248. {\if\edition\racketEd
  15249. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15250. .globl main
  15251. .align 8
  15252. main:
  15253. pushq %rbp
  15254. movq %rsp, %rbp
  15255. movq $16384, %rdi
  15256. movq $16384, %rsi
  15257. callq initialize
  15258. movq rootstack_begin(%rip), %r15
  15259. jmp mainstart
  15260. mainstart:
  15261. leaq add86(%rip), %rcx
  15262. movq $40, %rdi
  15263. movq $2, %rsi
  15264. movq %rcx, %rax
  15265. popq %rbp
  15266. jmp *%rax
  15267. mainconclusion:
  15268. popq %rbp
  15269. retq
  15270. \end{lstlisting}
  15271. \fi}
  15272. {\if\edition\pythonEd\pythonColor
  15273. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15274. .globl main
  15275. .align 8
  15276. main:
  15277. pushq %rbp
  15278. movq %rsp, %rbp
  15279. subq $0, %rsp
  15280. movq $65536, %rdi
  15281. movq $65536, %rsi
  15282. callq initialize
  15283. movq rootstack_begin(%rip), %r15
  15284. jmp mainstart
  15285. mainstart:
  15286. leaq add(%rip), %rcx
  15287. movq $40, %rdi
  15288. movq $2, %rsi
  15289. callq *%rcx
  15290. movq %rax, %rcx
  15291. movq %rcx, %rdi
  15292. callq print_int
  15293. movq $0, %rax
  15294. jmp mainconclusion
  15295. mainconclusion:
  15296. subq $0, %r15
  15297. addq $0, %rsp
  15298. popq %rbp
  15299. retq
  15300. \end{lstlisting}
  15301. \fi}
  15302. \end{minipage}
  15303. \end{tabular}
  15304. \end{tcolorbox}
  15305. \caption{Example compilation of a simple function to x86.}
  15306. \label{fig:add-fun}
  15307. \end{figure}
  15308. % Challenge idea: inlining! (simple version)
  15309. % Further Reading
  15310. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15311. \chapter{Lexically Scoped Functions}
  15312. \label{ch:Llambda}
  15313. \setcounter{footnote}{0}
  15314. This chapter studies lexically scoped functions. Lexical
  15315. scoping\index{subject}{lexical scoping} means that a function's body
  15316. may refer to variables whose binding site is outside of the function,
  15317. in an enclosing scope.
  15318. %
  15319. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15320. in \LangLam{}, which extends \LangFun{} with the
  15321. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15322. functions. The body of the \key{lambda} refers to three variables:
  15323. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15324. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15325. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15326. function \code{f}}, and \code{x} is a parameter of function
  15327. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15328. result value. The main expression of the program includes two calls to
  15329. \code{f} with different arguments for \code{x}: first \code{5} and
  15330. then \code{3}. The functions returned from \code{f} are bound to
  15331. variables \code{g} and \code{h}. Even though these two functions were
  15332. created by the same \code{lambda}, they are really different functions
  15333. because they use different values for \code{x}. Applying \code{g} to
  15334. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15335. produces \code{22}, so the result of the program is \code{42}.
  15336. \begin{figure}[btp]
  15337. \begin{tcolorbox}[colback=white]
  15338. {\if\edition\racketEd
  15339. % lambda_test_21.rkt
  15340. \begin{lstlisting}
  15341. (define (f [x : Integer]) : (Integer -> Integer)
  15342. (let ([y 4])
  15343. (lambda: ([z : Integer]) : Integer
  15344. (+ x (+ y z)))))
  15345. (let ([g (f 5)])
  15346. (let ([h (f 3)])
  15347. (+ (g 11) (h 15))))
  15348. \end{lstlisting}
  15349. \fi}
  15350. {\if\edition\pythonEd\pythonColor
  15351. \begin{lstlisting}
  15352. def f(x : int) -> Callable[[int], int]:
  15353. y = 4
  15354. return lambda z: x + y + z
  15355. g = f(5)
  15356. h = f(3)
  15357. print(g(11) + h(15))
  15358. \end{lstlisting}
  15359. \fi}
  15360. \end{tcolorbox}
  15361. \caption{Example of a lexically scoped function.}
  15362. \label{fig:lexical-scoping}
  15363. \end{figure}
  15364. The approach that we take for implementing lexically scoped functions
  15365. is to compile them into top-level function definitions, translating
  15366. from \LangLam{} into \LangFun{}. However, the compiler must give
  15367. special treatment to variable occurrences such as \code{x} and
  15368. \code{y} in the body of the \code{lambda} shown in
  15369. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15370. may not refer to variables defined outside of it. To identify such
  15371. variable occurrences, we review the standard notion of free variable.
  15372. \begin{definition}\normalfont
  15373. A variable is \emph{free in expression} $e$ if the variable occurs
  15374. inside $e$ but does not have an enclosing definition that is also in
  15375. $e$.\index{subject}{free variable}
  15376. \end{definition}
  15377. For example, in the expression
  15378. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15379. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15380. only \code{x} and \code{y} are free in the following expression,
  15381. because \code{z} is defined by the \code{lambda}
  15382. {\if\edition\racketEd
  15383. \begin{lstlisting}
  15384. (lambda: ([z : Integer]) : Integer
  15385. (+ x (+ y z)))
  15386. \end{lstlisting}
  15387. \fi}
  15388. {\if\edition\pythonEd\pythonColor
  15389. \begin{lstlisting}
  15390. lambda z: x + y + z
  15391. \end{lstlisting}
  15392. \fi}
  15393. %
  15394. \noindent Thus the free variables of a \code{lambda} are the ones that
  15395. need special treatment. We need to transport at runtime the values
  15396. of those variables from the point where the \code{lambda} was created
  15397. to the point where the \code{lambda} is applied. An efficient solution
  15398. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15399. values of the free variables together with a function pointer into a
  15400. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15401. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15402. closure}
  15403. %
  15404. By design, we have all the ingredients to make closures:
  15405. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15406. function pointers. The function pointer resides at index $0$, and the
  15407. values for the free variables fill in the rest of the tuple.
  15408. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15409. to see how closures work. It is a three-step dance. The program calls
  15410. function \code{f}, which creates a closure for the \code{lambda}. The
  15411. closure is a tuple whose first element is a pointer to the top-level
  15412. function that we will generate for the \code{lambda}; the second
  15413. element is the value of \code{x}, which is \code{5}; and the third
  15414. element is \code{4}, the value of \code{y}. The closure does not
  15415. contain an element for \code{z} because \code{z} is not a free
  15416. variable of the \code{lambda}. Creating the closure is step 1 of the
  15417. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15418. shown in figure~\ref{fig:closures}.
  15419. %
  15420. The second call to \code{f} creates another closure, this time with
  15421. \code{3} in the second slot (for \code{x}). This closure is also
  15422. returned from \code{f} but bound to \code{h}, which is also shown in
  15423. figure~\ref{fig:closures}.
  15424. \begin{figure}[tbp]
  15425. \centering
  15426. \begin{minipage}{0.65\textwidth}
  15427. \begin{tcolorbox}[colback=white]
  15428. \includegraphics[width=\textwidth]{figs/closures}
  15429. \end{tcolorbox}
  15430. \end{minipage}
  15431. \caption{Flat closure representations for the two functions
  15432. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15433. \label{fig:closures}
  15434. \end{figure}
  15435. Continuing with the example, consider the application of \code{g} to
  15436. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15437. closure, we obtain the function pointer from the first element of the
  15438. closure and call it, passing in the closure itself and then the
  15439. regular arguments, in this case \code{11}. This technique for applying
  15440. a closure is step 2 of the dance.
  15441. %
  15442. But doesn't this \code{lambda} take only one argument, for parameter
  15443. \code{z}? The third and final step of the dance is generating a
  15444. top-level function for a \code{lambda}. We add an additional
  15445. parameter for the closure and insert an initialization at the beginning
  15446. of the function for each free variable, to bind those variables to the
  15447. appropriate elements from the closure parameter.
  15448. %
  15449. This three-step dance is known as \emph{closure
  15450. conversion}\index{subject}{closure conversion}. We discuss the
  15451. details of closure conversion in section~\ref{sec:closure-conversion}
  15452. and show the code generated from the example in
  15453. section~\ref{sec:example-lambda}. First, we define the syntax and
  15454. semantics of \LangLam{} in section~\ref{sec:r5}.
  15455. \section{The \LangLam{} Language}
  15456. \label{sec:r5}
  15457. The definitions of the concrete syntax and abstract syntax for
  15458. \LangLam{}, a language with anonymous functions and lexical scoping,
  15459. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15460. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15461. for \LangFun{}, which already has syntax for function application.
  15462. %
  15463. \python{The syntax also includes an assignment statement that includes
  15464. a type annotation for the variable on the left-hand side, which
  15465. facilitates the type checking of \code{lambda} expressions that we
  15466. discuss later in this section.}
  15467. %
  15468. \racket{The \code{procedure-arity} operation returns the number of parameters
  15469. of a given function, an operation that we need for the translation
  15470. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15471. %
  15472. \python{The \code{arity} operation returns the number of parameters of
  15473. a given function, an operation that we need for the translation
  15474. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15475. The \code{arity} operation is not in Python, but the same functionality
  15476. is available in a more complex form. We include \code{arity} in the
  15477. \LangLam{} source language to enable testing.}
  15478. \newcommand{\LlambdaGrammarRacket}{
  15479. \begin{array}{lcl}
  15480. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15481. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15482. \end{array}
  15483. }
  15484. \newcommand{\LlambdaASTRacket}{
  15485. \begin{array}{lcl}
  15486. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15487. \itm{op} &::=& \code{procedure-arity}
  15488. \end{array}
  15489. }
  15490. \newcommand{\LlambdaGrammarPython}{
  15491. \begin{array}{lcl}
  15492. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15493. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15494. \end{array}
  15495. }
  15496. \newcommand{\LlambdaASTPython}{
  15497. \begin{array}{lcl}
  15498. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15499. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15500. \end{array}
  15501. }
  15502. % include AnnAssign in ASTPython
  15503. \begin{figure}[tp]
  15504. \centering
  15505. \begin{tcolorbox}[colback=white]
  15506. \small
  15507. {\if\edition\racketEd
  15508. \[
  15509. \begin{array}{l}
  15510. \gray{\LintGrammarRacket{}} \\ \hline
  15511. \gray{\LvarGrammarRacket{}} \\ \hline
  15512. \gray{\LifGrammarRacket{}} \\ \hline
  15513. \gray{\LwhileGrammarRacket} \\ \hline
  15514. \gray{\LtupGrammarRacket} \\ \hline
  15515. \gray{\LfunGrammarRacket} \\ \hline
  15516. \LlambdaGrammarRacket \\
  15517. \begin{array}{lcl}
  15518. \LangLamM{} &::=& \Def\ldots \; \Exp
  15519. \end{array}
  15520. \end{array}
  15521. \]
  15522. \fi}
  15523. {\if\edition\pythonEd\pythonColor
  15524. \[
  15525. \begin{array}{l}
  15526. \gray{\LintGrammarPython{}} \\ \hline
  15527. \gray{\LvarGrammarPython{}} \\ \hline
  15528. \gray{\LifGrammarPython{}} \\ \hline
  15529. \gray{\LwhileGrammarPython} \\ \hline
  15530. \gray{\LtupGrammarPython} \\ \hline
  15531. \gray{\LfunGrammarPython} \\ \hline
  15532. \LlambdaGrammarPython \\
  15533. \begin{array}{lcl}
  15534. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15535. \end{array}
  15536. \end{array}
  15537. \]
  15538. \fi}
  15539. \end{tcolorbox}
  15540. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15541. with \key{lambda}.}
  15542. \label{fig:Llam-concrete-syntax}
  15543. \end{figure}
  15544. \begin{figure}[tp]
  15545. \centering
  15546. \begin{tcolorbox}[colback=white]
  15547. \small
  15548. {\if\edition\racketEd
  15549. \[\arraycolsep=3pt
  15550. \begin{array}{l}
  15551. \gray{\LintOpAST} \\ \hline
  15552. \gray{\LvarASTRacket{}} \\ \hline
  15553. \gray{\LifASTRacket{}} \\ \hline
  15554. \gray{\LwhileASTRacket{}} \\ \hline
  15555. \gray{\LtupASTRacket{}} \\ \hline
  15556. \gray{\LfunASTRacket} \\ \hline
  15557. \LlambdaASTRacket \\
  15558. \begin{array}{lcl}
  15559. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15560. \end{array}
  15561. \end{array}
  15562. \]
  15563. \fi}
  15564. {\if\edition\pythonEd\pythonColor
  15565. \[
  15566. \begin{array}{l}
  15567. \gray{\LintASTPython} \\ \hline
  15568. \gray{\LvarASTPython{}} \\ \hline
  15569. \gray{\LifASTPython{}} \\ \hline
  15570. \gray{\LwhileASTPython{}} \\ \hline
  15571. \gray{\LtupASTPython{}} \\ \hline
  15572. \gray{\LfunASTPython} \\ \hline
  15573. \LlambdaASTPython \\
  15574. \begin{array}{lcl}
  15575. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15576. \end{array}
  15577. \end{array}
  15578. \]
  15579. \fi}
  15580. \end{tcolorbox}
  15581. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15582. \label{fig:Llam-syntax}
  15583. \end{figure}
  15584. Figure~\ref{fig:interp-Llambda} shows the definitional
  15585. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15586. \key{Lambda} saves the current environment inside the returned
  15587. function value. Recall that during function application, the
  15588. environment stored in the function value, extended with the mapping of
  15589. parameters to argument values, is used to interpret the body of the
  15590. function.
  15591. \begin{figure}[tbp]
  15592. \begin{tcolorbox}[colback=white]
  15593. {\if\edition\racketEd
  15594. \begin{lstlisting}
  15595. (define interp-Llambda-class
  15596. (class interp-Lfun-class
  15597. (super-new)
  15598. (define/override (interp-op op)
  15599. (match op
  15600. ['procedure-arity
  15601. (lambda (v)
  15602. (match v
  15603. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15604. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15605. [else (super interp-op op)]))
  15606. (define/override ((interp-exp env) e)
  15607. (define recur (interp-exp env))
  15608. (match e
  15609. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15610. `(function ,xs ,body ,env)]
  15611. [else ((super interp-exp env) e)]))
  15612. ))
  15613. (define (interp-Llambda p)
  15614. (send (new interp-Llambda-class) interp-program p))
  15615. \end{lstlisting}
  15616. \fi}
  15617. {\if\edition\pythonEd\pythonColor
  15618. \begin{lstlisting}
  15619. class InterpLlambda(InterpLfun):
  15620. def arity(self, v):
  15621. match v:
  15622. case Function(name, params, body, env):
  15623. return len(params)
  15624. case _:
  15625. raise Exception('Llambda arity unexpected ' + repr(v))
  15626. def interp_exp(self, e, env):
  15627. match e:
  15628. case Call(Name('arity'), [fun]):
  15629. f = self.interp_exp(fun, env)
  15630. return self.arity(f)
  15631. case Lambda(params, body):
  15632. return Function('lambda', params, [Return(body)], env)
  15633. case _:
  15634. return super().interp_exp(e, env)
  15635. def interp_stmt(self, s, env, cont):
  15636. match s:
  15637. case AnnAssign(lhs, typ, value, simple):
  15638. env[lhs.id] = self.interp_exp(value, env)
  15639. return self.interp_stmts(cont, env)
  15640. case Pass():
  15641. return self.interp_stmts(cont, env)
  15642. case _:
  15643. return super().interp_stmt(s, env, cont)
  15644. \end{lstlisting}
  15645. \fi}
  15646. \end{tcolorbox}
  15647. \caption{Interpreter for \LangLam{}.}
  15648. \label{fig:interp-Llambda}
  15649. \end{figure}
  15650. {\if\edition\racketEd
  15651. %
  15652. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15653. \key{lambda} form. The body of the \key{lambda} is checked in an
  15654. environment that includes the current environment (because it is
  15655. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15656. require the body's type to match the declared return type.
  15657. %
  15658. \fi}
  15659. {\if\edition\pythonEd\pythonColor
  15660. %
  15661. Figures~\ref{fig:type-check-Llambda} and
  15662. \ref{fig:type-check-Llambda-part2} define the type checker for
  15663. \LangLam{}, which is more complex than one might expect. The reason
  15664. for the added complexity is that the syntax of \key{lambda} does not
  15665. include type annotations for the parameters or return type. Instead
  15666. they must be inferred. There are many approaches to type inference
  15667. from which to choose, of varying degrees of complexity. We choose one
  15668. of the simpler approaches, bidirectional type
  15669. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15670. book is compilation, not type inference.
  15671. The main idea of bidirectional type inference is to add an auxiliary
  15672. function, here named \code{check\_exp}, that takes an expected type
  15673. and checks whether the given expression is of that type. Thus, in
  15674. \code{check\_exp}, type information flows in a top-down manner with
  15675. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15676. function, where type information flows in a primarily bottom-up
  15677. manner.
  15678. %
  15679. The idea then is to use \code{check\_exp} in all the places where we
  15680. already know what the type of an expression should be, such as in the
  15681. \code{return} statement of a top-level function definition or on the
  15682. right-hand side of an annotated assignment statement.
  15683. With regard to \code{lambda}, it is straightforward to check a
  15684. \code{lambda} inside \code{check\_exp} because the expected type
  15685. provides the parameter types and the return type. On the other hand,
  15686. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15687. that we do not allow \code{lambda} in contexts in which we don't already
  15688. know its type. This restriction does not incur a loss of
  15689. expressiveness for \LangLam{} because it is straightforward to modify
  15690. a program to sidestep the restriction, for example, by using an
  15691. annotated assignment statement to assign the \code{lambda} to a
  15692. temporary variable.
  15693. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15694. checker records their type in a \code{has\_type} field. This type
  15695. information is used further on in this chapter.
  15696. %
  15697. \fi}
  15698. \begin{figure}[tbp]
  15699. \begin{tcolorbox}[colback=white]
  15700. {\if\edition\racketEd
  15701. \begin{lstlisting}
  15702. (define (type-check-Llambda env)
  15703. (lambda (e)
  15704. (match e
  15705. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15706. (define-values (new-body bodyT)
  15707. ((type-check-exp (append (map cons xs Ts) env)) body))
  15708. (define ty `(,@Ts -> ,rT))
  15709. (cond
  15710. [(equal? rT bodyT)
  15711. (values (HasType (Lambda params rT new-body) ty) ty)]
  15712. [else
  15713. (error "mismatch in return type" bodyT rT)])]
  15714. ...
  15715. )))
  15716. \end{lstlisting}
  15717. \fi}
  15718. {\if\edition\pythonEd\pythonColor
  15719. \begin{lstlisting}
  15720. class TypeCheckLlambda(TypeCheckLfun):
  15721. def type_check_exp(self, e, env):
  15722. match e:
  15723. case Name(id):
  15724. e.has_type = env[id]
  15725. return env[id]
  15726. case Lambda(params, body):
  15727. raise Exception('cannot synthesize a type for a lambda')
  15728. case Call(Name('arity'), [func]):
  15729. func_t = self.type_check_exp(func, env)
  15730. match func_t:
  15731. case FunctionType(params_t, return_t):
  15732. return IntType()
  15733. case _:
  15734. raise Exception('in arity, unexpected ' + repr(func_t))
  15735. case _:
  15736. return super().type_check_exp(e, env)
  15737. def check_exp(self, e, ty, env):
  15738. match e:
  15739. case Lambda(params, body):
  15740. e.has_type = ty
  15741. match ty:
  15742. case FunctionType(params_t, return_t):
  15743. new_env = env.copy().update(zip(params, params_t))
  15744. self.check_exp(body, return_t, new_env)
  15745. case _:
  15746. raise Exception('lambda does not have type ' + str(ty))
  15747. case Call(func, args):
  15748. func_t = self.type_check_exp(func, env)
  15749. match func_t:
  15750. case FunctionType(params_t, return_t):
  15751. for (arg, param_t) in zip(args, params_t):
  15752. self.check_exp(arg, param_t, env)
  15753. self.check_type_equal(return_t, ty, e)
  15754. case _:
  15755. raise Exception('type_check_exp: in call, unexpected ' + \
  15756. repr(func_t))
  15757. case _:
  15758. t = self.type_check_exp(e, env)
  15759. self.check_type_equal(t, ty, e)
  15760. \end{lstlisting}
  15761. \fi}
  15762. \end{tcolorbox}
  15763. \caption{Type checking \LangLam{}\python{, part 1}.}
  15764. \label{fig:type-check-Llambda}
  15765. \end{figure}
  15766. {\if\edition\pythonEd\pythonColor
  15767. \begin{figure}[tbp]
  15768. \begin{tcolorbox}[colback=white]
  15769. \begin{lstlisting}
  15770. def check_stmts(self, ss, return_ty, env):
  15771. if len(ss) == 0:
  15772. return
  15773. match ss[0]:
  15774. case FunctionDef(name, params, body, dl, returns, comment):
  15775. new_env = env.copy().update(params)
  15776. rt = self.check_stmts(body, returns, new_env)
  15777. self.check_stmts(ss[1:], return_ty, env)
  15778. case Return(value):
  15779. self.check_exp(value, return_ty, env)
  15780. case Assign([Name(id)], value):
  15781. if id in env:
  15782. self.check_exp(value, env[id], env)
  15783. else:
  15784. env[id] = self.type_check_exp(value, env)
  15785. self.check_stmts(ss[1:], return_ty, env)
  15786. case Assign([Subscript(tup, Constant(index), Store())], value):
  15787. tup_t = self.type_check_exp(tup, env)
  15788. match tup_t:
  15789. case TupleType(ts):
  15790. self.check_exp(value, ts[index], env)
  15791. case _:
  15792. raise Exception('expected a tuple, not ' + repr(tup_t))
  15793. self.check_stmts(ss[1:], return_ty, env)
  15794. case AnnAssign(Name(id), ty_annot, value, simple):
  15795. ss[0].annotation = ty_annot
  15796. if id in env:
  15797. self.check_type_equal(env[id], ty_annot)
  15798. else:
  15799. env[id] = ty_annot
  15800. self.check_exp(value, ty_annot, env)
  15801. self.check_stmts(ss[1:], return_ty, env)
  15802. case _:
  15803. self.type_check_stmts(ss, env)
  15804. def type_check(self, p):
  15805. match p:
  15806. case Module(body):
  15807. env = {}
  15808. for s in body:
  15809. match s:
  15810. case FunctionDef(name, params, bod, dl, returns, comment):
  15811. params_t = [t for (x,t) in params]
  15812. env[name] = FunctionType(params_t, returns)
  15813. self.check_stmts(body, int, env)
  15814. \end{lstlisting}
  15815. \end{tcolorbox}
  15816. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15817. \label{fig:type-check-Llambda-part2}
  15818. \end{figure}
  15819. \fi}
  15820. \clearpage
  15821. \section{Assignment and Lexically Scoped Functions}
  15822. \label{sec:assignment-scoping}
  15823. The combination of lexically scoped functions and assignment to
  15824. variables raises a challenge with the flat-closure approach to
  15825. implementing lexically scoped functions. Consider the following
  15826. example in which function \code{f} has a free variable \code{x} that
  15827. is changed after \code{f} is created but before the call to \code{f}.
  15828. % loop_test_11.rkt
  15829. {\if\edition\racketEd
  15830. \begin{lstlisting}
  15831. (let ([x 0])
  15832. (let ([y 0])
  15833. (let ([z 20])
  15834. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15835. (begin
  15836. (set! x 10)
  15837. (set! y 12)
  15838. (f y))))))
  15839. \end{lstlisting}
  15840. \fi}
  15841. {\if\edition\pythonEd\pythonColor
  15842. % box_free_assign.py
  15843. \begin{lstlisting}
  15844. def g(z : int) -> int:
  15845. x = 0
  15846. y = 0
  15847. f : Callable[[int],int] = lambda a: a + x + z
  15848. x = 10
  15849. y = 12
  15850. return f(y)
  15851. print(g(20))
  15852. \end{lstlisting}
  15853. \fi} The correct output for this example is \code{42} because the call
  15854. to \code{f} is required to use the current value of \code{x} (which is
  15855. \code{10}). Unfortunately, the closure conversion pass
  15856. (section~\ref{sec:closure-conversion}) generates code for the
  15857. \code{lambda} that copies the old value of \code{x} into a
  15858. closure. Thus, if we naively applied closure conversion, the output of
  15859. this program would be \code{32}.
  15860. A first attempt at solving this problem would be to save a pointer to
  15861. \code{x} in the closure and change the occurrences of \code{x} inside
  15862. the lambda to dereference the pointer. Of course, this would require
  15863. assigning \code{x} to the stack and not to a register. However, the
  15864. problem goes a bit deeper.
  15865. Consider the following example that returns a function that refers to
  15866. a local variable of the enclosing function:
  15867. \begin{center}
  15868. \begin{minipage}{\textwidth}
  15869. {\if\edition\racketEd
  15870. \begin{lstlisting}
  15871. (define (f) : ( -> Integer)
  15872. (let ([x 0])
  15873. (let ([g (lambda: () : Integer x)])
  15874. (begin
  15875. (set! x 42)
  15876. g))))
  15877. ((f))
  15878. \end{lstlisting}
  15879. \fi}
  15880. {\if\edition\pythonEd\pythonColor
  15881. % counter.py
  15882. \begin{lstlisting}
  15883. def f():
  15884. x = 0
  15885. g = lambda: x
  15886. x = 42
  15887. return g
  15888. print(f()())
  15889. \end{lstlisting}
  15890. \fi}
  15891. \end{minipage}
  15892. \end{center}
  15893. In this example, the lifetime of \code{x} extends beyond the lifetime
  15894. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15895. stack frame for the call to \code{f}, it would be gone by the time we
  15896. called \code{g}, leaving us with dangling pointers for
  15897. \code{x}. This example demonstrates that when a variable occurs free
  15898. inside a function, its lifetime becomes indefinite. Thus, the value of
  15899. the variable needs to live on the heap. The verb
  15900. \emph{box}\index{subject}{box} is often used for allocating a single
  15901. value on the heap, producing a pointer, and
  15902. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15903. %
  15904. We introduce a new pass named \code{convert\_assignments} to address
  15905. this challenge.
  15906. %
  15907. \python{But before diving into that, we have one more
  15908. problem to discuss.}
  15909. {\if\edition\pythonEd\pythonColor
  15910. \section{Uniquify Variables}
  15911. \label{sec:uniquify-lambda}
  15912. With the addition of \code{lambda} we have a complication to deal
  15913. with: name shadowing. Consider the following program with a function
  15914. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15915. \code{lambda} expressions. The first \code{lambda} has a parameter
  15916. that is also named \code{x}.
  15917. \begin{lstlisting}
  15918. def f(x:int, y:int) -> Callable[[int], int]:
  15919. g : Callable[[int],int] = (lambda x: x + y)
  15920. h : Callable[[int],int] = (lambda y: x + y)
  15921. x = input_int()
  15922. return g
  15923. print(f(0, 10)(32))
  15924. \end{lstlisting}
  15925. Many of our compiler passes rely on being able to connect variable
  15926. uses with their definitions using just the name of the
  15927. variable. However, in the example above the name of the variable does
  15928. not uniquely determine its definition. To solve this problem we
  15929. recommend implementing a pass named \code{uniquify} that renames every
  15930. variable in the program to make sure that they are all unique.
  15931. The following shows the result of \code{uniquify} for the example
  15932. above. The \code{x} parameter of function \code{f} is renamed to
  15933. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15934. renamed to \code{x\_4}.
  15935. \begin{lstlisting}
  15936. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15937. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15938. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15939. x_0 = input_int()
  15940. return g_2
  15941. def main() -> int :
  15942. print(f(0, 10)(32))
  15943. return 0
  15944. \end{lstlisting}
  15945. \fi} % pythonEd
  15946. %% \section{Reveal Functions}
  15947. %% \label{sec:reveal-functions-r5}
  15948. %% \racket{To support the \code{procedure-arity} operator we need to
  15949. %% communicate the arity of a function to the point of closure
  15950. %% creation.}
  15951. %% %
  15952. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15953. %% function at runtime. Thus, we need to communicate the arity of a
  15954. %% function to the point of closure creation.}
  15955. %% %
  15956. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15957. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15958. %% \[
  15959. %% \begin{array}{lcl}
  15960. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15961. %% \end{array}
  15962. %% \]
  15963. \section{Assignment Conversion}
  15964. \label{sec:convert-assignments}
  15965. The purpose of the \code{convert\_assignments} pass is to address the
  15966. challenge regarding the interaction between variable assignments and
  15967. closure conversion. First we identify which variables need to be
  15968. boxed, and then we transform the program to box those variables. In
  15969. general, boxing introduces runtime overhead that we would like to
  15970. avoid, so we should box as few variables as possible. We recommend
  15971. boxing the variables in the intersection of the following two sets of
  15972. variables:
  15973. \begin{enumerate}
  15974. \item The variables that are free in a \code{lambda}.
  15975. \item The variables that appear on the left-hand side of an
  15976. assignment.
  15977. \end{enumerate}
  15978. The first condition is a must but the second condition is
  15979. conservative. It is possible to develop a more liberal condition using
  15980. static program analysis.
  15981. Consider again the first example from
  15982. section~\ref{sec:assignment-scoping}:
  15983. %
  15984. {\if\edition\racketEd
  15985. \begin{lstlisting}
  15986. (let ([x 0])
  15987. (let ([y 0])
  15988. (let ([z 20])
  15989. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15990. (begin
  15991. (set! x 10)
  15992. (set! y 12)
  15993. (f y))))))
  15994. \end{lstlisting}
  15995. \fi}
  15996. {\if\edition\pythonEd\pythonColor
  15997. \begin{lstlisting}
  15998. def g(z : int) -> int:
  15999. x = 0
  16000. y = 0
  16001. f : Callable[[int],int] = lambda a: a + x + z
  16002. x = 10
  16003. y = 12
  16004. return f(y)
  16005. print(g(20))
  16006. \end{lstlisting}
  16007. \fi}
  16008. %
  16009. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16010. side of assignments. The variables \code{x} and \code{z} occur free
  16011. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16012. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16013. three transformations: initialize \code{x} with a tuple whose elements
  16014. are uninitialized, replace reads from \code{x} with tuple reads, and
  16015. replace each assignment to \code{x} with a tuple write. The output of
  16016. \code{convert\_assignments} for this example is as follows:
  16017. %
  16018. {\if\edition\racketEd
  16019. \begin{lstlisting}
  16020. (define (main) : Integer
  16021. (let ([x0 (vector 0)])
  16022. (let ([y1 0])
  16023. (let ([z2 20])
  16024. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16025. (+ a3 (+ (vector-ref x0 0) z2)))])
  16026. (begin
  16027. (vector-set! x0 0 10)
  16028. (set! y1 12)
  16029. (f4 y1)))))))
  16030. \end{lstlisting}
  16031. \fi}
  16032. %
  16033. {\if\edition\pythonEd\pythonColor
  16034. \begin{lstlisting}
  16035. def g(z : int)-> int:
  16036. x = (uninitialized(int),)
  16037. x[0] = 0
  16038. y = 0
  16039. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16040. x[0] = 10
  16041. y = 12
  16042. return f(y)
  16043. def main() -> int:
  16044. print(g(20))
  16045. return 0
  16046. \end{lstlisting}
  16047. \fi}
  16048. To compute the free variables of all the \code{lambda} expressions, we
  16049. recommend defining the following two auxiliary functions:
  16050. \begin{enumerate}
  16051. \item \code{free\_variables} computes the free variables of an expression, and
  16052. \item \code{free\_in\_lambda} collects all the variables that are
  16053. free in any of the \code{lambda} expressions, using
  16054. \code{free\_variables} in the case for each \code{lambda}.
  16055. \end{enumerate}
  16056. {\if\edition\racketEd
  16057. %
  16058. To compute the variables that are assigned to, we recommend updating
  16059. the \code{collect-set!} function that we introduced in
  16060. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16061. as \code{Lambda}.
  16062. %
  16063. \fi}
  16064. {\if\edition\pythonEd\pythonColor
  16065. %
  16066. To compute the variables that are assigned to, we recommend defining
  16067. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16068. the set of variables that occur in the left-hand side of an assignment
  16069. statement and otherwise returns the empty set.
  16070. %
  16071. \fi}
  16072. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16073. free in a \code{lambda} and that are assigned to in the enclosing
  16074. function definition.
  16075. Next we discuss the \code{convert\_assignments} pass. In the case for
  16076. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16077. $\VAR{x}$ to a tuple read.
  16078. %
  16079. {\if\edition\racketEd
  16080. \begin{lstlisting}
  16081. (Var |$x$|)
  16082. |$\Rightarrow$|
  16083. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16084. \end{lstlisting}
  16085. \fi}
  16086. %
  16087. {\if\edition\pythonEd\pythonColor
  16088. \begin{lstlisting}
  16089. Name(|$x$|)
  16090. |$\Rightarrow$|
  16091. Subscript(Name(|$x$|), Constant(0), Load())
  16092. \end{lstlisting}
  16093. \fi}
  16094. %
  16095. \noindent In the case for assignment, recursively process the
  16096. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16097. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16098. as follows:
  16099. %
  16100. {\if\edition\racketEd
  16101. \begin{lstlisting}
  16102. (SetBang |$x$| |$\itm{rhs}$|)
  16103. |$\Rightarrow$|
  16104. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16105. \end{lstlisting}
  16106. \fi}
  16107. {\if\edition\pythonEd\pythonColor
  16108. \begin{lstlisting}
  16109. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16110. |$\Rightarrow$|
  16111. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16112. \end{lstlisting}
  16113. \fi}
  16114. %
  16115. {\if\edition\racketEd
  16116. The case for \code{Lambda} is nontrivial, but it is similar to the
  16117. case for function definitions, which we discuss next.
  16118. \fi}
  16119. %
  16120. To translate a function definition, we first compute $\mathit{AF}$,
  16121. the intersection of the variables that are free in a \code{lambda} and
  16122. that are assigned to. We then apply assignment conversion to the body
  16123. of the function definition. Finally, we box the parameters of this
  16124. function definition that are in $\mathit{AF}$. For example,
  16125. the parameter \code{x} of the following function \code{g}
  16126. needs to be boxed:
  16127. {\if\edition\racketEd
  16128. \begin{lstlisting}
  16129. (define (g [x : Integer]) : Integer
  16130. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16131. (begin
  16132. (set! x 10)
  16133. (f 32))))
  16134. \end{lstlisting}
  16135. \fi}
  16136. %
  16137. {\if\edition\pythonEd\pythonColor
  16138. \begin{lstlisting}
  16139. def g(x : int) -> int:
  16140. f : Callable[[int],int] = lambda a: a + x
  16141. x = 10
  16142. return f(32)
  16143. \end{lstlisting}
  16144. \fi}
  16145. %
  16146. \noindent We box parameter \code{x} by creating a local variable named
  16147. \code{x} that is initialized to a tuple whose contents is the value of
  16148. the parameter, which has been renamed to \code{x\_0}.
  16149. %
  16150. {\if\edition\racketEd
  16151. \begin{lstlisting}
  16152. (define (g [x_0 : Integer]) : Integer
  16153. (let ([x (vector x_0)])
  16154. (let ([f (lambda: ([a : Integer]) : Integer
  16155. (+ a (vector-ref x 0)))])
  16156. (begin
  16157. (vector-set! x 0 10)
  16158. (f 32)))))
  16159. \end{lstlisting}
  16160. \fi}
  16161. %
  16162. {\if\edition\pythonEd\pythonColor
  16163. \begin{lstlisting}
  16164. def g(x_0 : int)-> int:
  16165. x = (x_0,)
  16166. f : Callable[[int], int] = (lambda a: a + x[0])
  16167. x[0] = 10
  16168. return f(32)
  16169. \end{lstlisting}
  16170. \fi}
  16171. \section{Closure Conversion}
  16172. \label{sec:closure-conversion}
  16173. \index{subject}{closure conversion}
  16174. The compiling of lexically scoped functions into top-level function
  16175. definitions and flat closures is accomplished in the pass
  16176. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16177. and before \code{limit\_functions}.
  16178. As usual, we implement the pass as a recursive function over the
  16179. AST. The interesting cases are for \key{lambda} and function
  16180. application. We transform a \key{lambda} expression into an expression
  16181. that creates a closure, that is, a tuple for which the first element
  16182. is a function pointer and the rest of the elements are the values of
  16183. the free variables of the \key{lambda}.
  16184. %
  16185. However, we use the \code{Closure} AST node instead of using a tuple
  16186. so that we can record the arity.
  16187. %
  16188. In the generated code that follows, \itm{fvs} is the free variables of
  16189. the lambda and \itm{name} is a unique symbol generated to identify the
  16190. lambda.
  16191. %
  16192. \racket{The \itm{arity} is the number of parameters (the length of
  16193. \itm{ps}).}
  16194. %
  16195. {\if\edition\racketEd
  16196. \begin{lstlisting}
  16197. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16198. |$\Rightarrow$|
  16199. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16200. \end{lstlisting}
  16201. \fi}
  16202. %
  16203. {\if\edition\pythonEd\pythonColor
  16204. \begin{lstlisting}
  16205. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16206. |$\Rightarrow$|
  16207. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  16208. \end{lstlisting}
  16209. \fi}
  16210. %
  16211. In addition to transforming each \key{Lambda} AST node into a
  16212. tuple, we create a top-level function definition for each
  16213. \key{Lambda}, as shown next.\\
  16214. \begin{minipage}{0.8\textwidth}
  16215. {\if\edition\racketEd
  16216. \begin{lstlisting}
  16217. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16218. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16219. ...
  16220. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16221. |\itm{body'}|)...))
  16222. \end{lstlisting}
  16223. \fi}
  16224. {\if\edition\pythonEd\pythonColor
  16225. \begin{lstlisting}
  16226. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  16227. |$\itm{fvs}_1$| = clos[1]
  16228. |$\ldots$|
  16229. |$\itm{fvs}_n$| = clos[|$n$|]
  16230. |\itm{body'}|
  16231. \end{lstlisting}
  16232. \fi}
  16233. \end{minipage}\\
  16234. The \code{clos} parameter refers to the closure. Translate the type
  16235. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16236. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  16237. \itm{closTy} is a tuple type for which the first element type is
  16238. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  16239. the element types are the types of the free variables in the
  16240. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16241. is nontrivial to give a type to the function in the closure's type.%
  16242. %
  16243. \footnote{To give an accurate type to a closure, we would need to add
  16244. existential types to the type checker~\citep{Minamide:1996ys}.}
  16245. %
  16246. %% The dummy type is considered to be equal to any other type during type
  16247. %% checking.
  16248. The free variables become local variables that are initialized with
  16249. their values in the closure.
  16250. Closure conversion turns every function into a tuple, so the type
  16251. annotations in the program must also be translated. We recommend
  16252. defining an auxiliary recursive function for this purpose. Function
  16253. types should be translated as follows:
  16254. %
  16255. {\if\edition\racketEd
  16256. \begin{lstlisting}
  16257. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16258. |$\Rightarrow$|
  16259. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16260. \end{lstlisting}
  16261. \fi}
  16262. {\if\edition\pythonEd\pythonColor
  16263. \begin{lstlisting}
  16264. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16265. |$\Rightarrow$|
  16266. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16267. \end{lstlisting}
  16268. \fi}
  16269. %
  16270. This type indicates that the first thing in the tuple is a
  16271. function. The first parameter of the function is a tuple (a closure)
  16272. and the rest of the parameters are the ones from the original
  16273. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16274. omits the types of the free variables because (1) those types are not
  16275. available in this context, and (2) we do not need them in the code that
  16276. is generated for function application. So this type describes only the
  16277. first component of the closure tuple. At runtime the tuple may have
  16278. more components, but we ignore them at this point.
  16279. We transform function application into code that retrieves the
  16280. function from the closure and then calls the function, passing the
  16281. closure as the first argument. We place $e'$ in a temporary variable
  16282. to avoid code duplication.
  16283. \begin{center}
  16284. \begin{minipage}{\textwidth}
  16285. {\if\edition\racketEd
  16286. \begin{lstlisting}
  16287. (Apply |$e$| |$\itm{es}$|)
  16288. |$\Rightarrow$|
  16289. (Let |$\itm{tmp}$| |$e'$|
  16290. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16291. \end{lstlisting}
  16292. \fi}
  16293. %
  16294. {\if\edition\pythonEd\pythonColor
  16295. \begin{lstlisting}
  16296. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16297. |$\Rightarrow$|
  16298. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16299. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16300. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16301. \end{lstlisting}
  16302. \fi}
  16303. \end{minipage}
  16304. \end{center}
  16305. There is also the question of what to do with references to top-level
  16306. function definitions. To maintain a uniform translation of function
  16307. application, we turn function references into closures.
  16308. \begin{tabular}{lll}
  16309. \begin{minipage}{0.2\textwidth}
  16310. {\if\edition\racketEd
  16311. \begin{lstlisting}
  16312. (FunRef |$f$| |$n$|)
  16313. \end{lstlisting}
  16314. \fi}
  16315. {\if\edition\pythonEd\pythonColor
  16316. \begin{lstlisting}
  16317. FunRef(|$f$|, |$n$|)
  16318. \end{lstlisting}
  16319. \fi}
  16320. \end{minipage}
  16321. &
  16322. $\Rightarrow\qquad$
  16323. &
  16324. \begin{minipage}{0.5\textwidth}
  16325. {\if\edition\racketEd
  16326. \begin{lstlisting}
  16327. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16328. \end{lstlisting}
  16329. \fi}
  16330. {\if\edition\pythonEd\pythonColor
  16331. \begin{lstlisting}
  16332. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16333. \end{lstlisting}
  16334. \fi}
  16335. \end{minipage}
  16336. \end{tabular} \\
  16337. We no longer need the annotated assignment statement \code{AnnAssign}
  16338. to support the type checking of \code{lambda} expressions, so we
  16339. translate it to a regular \code{Assign} statement.
  16340. The top-level function definitions need to be updated to take an extra
  16341. closure parameter, but that parameter is ignored in the body of those
  16342. functions.
  16343. \section{An Example Translation}
  16344. \label{sec:example-lambda}
  16345. Figure~\ref{fig:lexical-functions-example} shows the result of
  16346. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16347. program demonstrating lexical scoping that we discussed at the
  16348. beginning of this chapter.
  16349. \begin{figure}[tbp]
  16350. \begin{tcolorbox}[colback=white]
  16351. \begin{minipage}{0.8\textwidth}
  16352. {\if\edition\racketEd
  16353. % tests/lambda_test_6.rkt
  16354. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16355. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16356. (let ([y8 4])
  16357. (lambda: ([z9 : Integer]) : Integer
  16358. (+ x7 (+ y8 z9)))))
  16359. (define (main) : Integer
  16360. (let ([g0 ((fun-ref f6 1) 5)])
  16361. (let ([h1 ((fun-ref f6 1) 3)])
  16362. (+ (g0 11) (h1 15)))))
  16363. \end{lstlisting}
  16364. $\Rightarrow$
  16365. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16366. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16367. (let ([y8 4])
  16368. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16369. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16370. (let ([x7 (vector-ref fvs3 1)])
  16371. (let ([y8 (vector-ref fvs3 2)])
  16372. (+ x7 (+ y8 z9)))))
  16373. (define (main) : Integer
  16374. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16375. ((vector-ref clos5 0) clos5 5))])
  16376. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16377. ((vector-ref clos6 0) clos6 3))])
  16378. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16379. \end{lstlisting}
  16380. \fi}
  16381. %
  16382. {\if\edition\pythonEd\pythonColor
  16383. % free_var.py
  16384. \begin{lstlisting}
  16385. def f(x: int) -> Callable[[int],int]:
  16386. y = 4
  16387. return lambda z: x + y + z
  16388. g = f(5)
  16389. h = f(3)
  16390. print(g(11) + h(15))
  16391. \end{lstlisting}
  16392. $\Rightarrow$
  16393. \begin{lstlisting}
  16394. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16395. x = fvs_1[1]
  16396. y = fvs_1[2]
  16397. return (x + y[0] + z)
  16398. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16399. y = (uninitialized(int),)
  16400. y[0] = 4
  16401. return closure{1}({lambda_0}, x, y)
  16402. def main() -> int:
  16403. g = (begin: clos_3 = closure{1}({f})
  16404. clos_3[0](clos_3, 5))
  16405. h = (begin: clos_4 = closure{1}({f})
  16406. clos_4[0](clos_4, 3))
  16407. print((begin: clos_5 = g
  16408. clos_5[0](clos_5, 11))
  16409. + (begin: clos_6 = h
  16410. clos_6[0](clos_6, 15)))
  16411. return 0
  16412. \end{lstlisting}
  16413. \fi}
  16414. \end{minipage}
  16415. \end{tcolorbox}
  16416. \caption{Example of closure conversion.}
  16417. \label{fig:lexical-functions-example}
  16418. \end{figure}
  16419. \begin{exercise}\normalfont\normalsize
  16420. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16421. Create five new programs that use \key{lambda} functions and make use of
  16422. lexical scoping. Test your compiler on these new programs and all
  16423. your previously created test programs.
  16424. \end{exercise}
  16425. \section{Expose Allocation}
  16426. \label{sec:expose-allocation-r5}
  16427. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16428. that allocates and initializes a tuple, similar to the translation of
  16429. the tuple creation in section~\ref{sec:expose-allocation}.
  16430. The only difference is replacing the use of
  16431. \ALLOC{\itm{len}}{\itm{type}} with
  16432. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16433. \section{Explicate Control and \LangCLam{}}
  16434. \label{sec:explicate-r5}
  16435. The output language of \code{explicate\_control} is \LangCLam{}; the
  16436. definition of its abstract syntax is shown in
  16437. figure~\ref{fig:Clam-syntax}.
  16438. %
  16439. \racket{The only differences with respect to \LangCFun{} are the
  16440. addition of the \code{AllocateClosure} form to the grammar for
  16441. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16442. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16443. similar to the handling of other expressions such as primitive
  16444. operators.}
  16445. %
  16446. \python{The differences with respect to \LangCFun{} are the
  16447. additions of \code{Uninitialized}, \code{AllocateClosure},
  16448. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16449. \code{explicate\_control} pass is similar to the handling of other
  16450. expressions such as primitive operators.}
  16451. \newcommand{\ClambdaASTRacket}{
  16452. \begin{array}{lcl}
  16453. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16454. \itm{op} &::= & \code{procedure-arity}
  16455. \end{array}
  16456. }
  16457. \newcommand{\ClambdaASTPython}{
  16458. \begin{array}{lcl}
  16459. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16460. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16461. &\MID& \ARITY{\Atm}
  16462. \end{array}
  16463. }
  16464. \begin{figure}[tp]
  16465. \begin{tcolorbox}[colback=white]
  16466. \small
  16467. {\if\edition\racketEd
  16468. \[
  16469. \begin{array}{l}
  16470. \gray{\CvarASTRacket} \\ \hline
  16471. \gray{\CifASTRacket} \\ \hline
  16472. \gray{\CloopASTRacket} \\ \hline
  16473. \gray{\CtupASTRacket} \\ \hline
  16474. \gray{\CfunASTRacket} \\ \hline
  16475. \ClambdaASTRacket \\
  16476. \begin{array}{lcl}
  16477. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16478. \end{array}
  16479. \end{array}
  16480. \]
  16481. \fi}
  16482. {\if\edition\pythonEd\pythonColor
  16483. \[
  16484. \begin{array}{l}
  16485. \gray{\CifASTPython} \\ \hline
  16486. \gray{\CtupASTPython} \\ \hline
  16487. \gray{\CfunASTPython} \\ \hline
  16488. \ClambdaASTPython \\
  16489. \begin{array}{lcl}
  16490. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16491. \end{array}
  16492. \end{array}
  16493. \]
  16494. \fi}
  16495. \end{tcolorbox}
  16496. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16497. \label{fig:Clam-syntax}
  16498. \end{figure}
  16499. \section{Select Instructions}
  16500. \label{sec:select-instructions-Llambda}
  16501. \index{subject}{select instructions}
  16502. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16503. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16504. (section~\ref{sec:select-instructions-gc}). The only difference is
  16505. that you should place the \itm{arity} in the tag that is stored at
  16506. position $0$ of the tuple. Recall that in
  16507. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16508. was not used. We store the arity in the $5$ bits starting at position
  16509. $58$.
  16510. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16511. instructions that access the tag from position $0$ of the vector and
  16512. extract the $5$ bits starting at position $58$ from the tag.}
  16513. %
  16514. \python{Compile a call to the \code{arity} operator to a sequence of
  16515. instructions that access the tag from position $0$ of the tuple
  16516. (representing a closure) and extract the $5$ bits starting at position
  16517. $58$ from the tag.}
  16518. \begin{figure}[p]
  16519. \begin{tcolorbox}[colback=white]
  16520. {\if\edition\racketEd
  16521. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16522. \node (Lfun) at (0,2) {\large \LangLam{}};
  16523. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16524. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16525. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16526. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16527. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16528. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16529. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16530. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16531. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16532. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16533. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16534. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16535. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16536. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16537. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16538. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16539. \path[->,bend left=15] (Lfun) edge [above] node
  16540. {\ttfamily\footnotesize shrink} (Lfun-2);
  16541. \path[->,bend left=15] (Lfun-2) edge [above] node
  16542. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16543. \path[->,bend left=15] (Lfun-3) edge [above] node
  16544. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16545. \path[->,bend left=15] (F1-0) edge [left] node
  16546. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16547. \path[->,bend left=15] (F1-1) edge [below] node
  16548. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16549. \path[->,bend right=15] (F1-2) edge [above] node
  16550. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16551. \path[->,bend right=15] (F1-3) edge [above] node
  16552. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16553. \path[->,bend left=15] (F1-4) edge [right] node
  16554. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16555. \path[->,bend right=15] (F1-5) edge [below] node
  16556. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16557. \path[->,bend left=15] (F1-6) edge [above] node
  16558. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16559. \path[->] (C3-2) edge [right] node
  16560. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16561. \path[->,bend right=15] (x86-2) edge [right] node
  16562. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16563. \path[->,bend right=15] (x86-2-1) edge [below] node
  16564. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16565. \path[->,bend right=15] (x86-2-2) edge [right] node
  16566. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16567. \path[->,bend left=15] (x86-3) edge [above] node
  16568. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16569. \path[->,bend left=15] (x86-4) edge [right] node
  16570. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16571. \end{tikzpicture}
  16572. \fi}
  16573. {\if\edition\pythonEd\pythonColor
  16574. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16575. \node (Lfun) at (0,2) {\large \LangLam{}};
  16576. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16577. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16578. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16579. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16580. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16581. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16582. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16583. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16584. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16585. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16586. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16587. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16588. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16589. \path[->,bend left=15] (Lfun) edge [above] node
  16590. {\ttfamily\footnotesize shrink} (Lfun-2);
  16591. \path[->,bend left=15] (Lfun-2) edge [above] node
  16592. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16593. \path[->,bend left=15] (Lfun-3) edge [above] node
  16594. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16595. \path[->,bend left=15] (F1-0) edge [left] node
  16596. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16597. \path[->,bend left=15] (F1-1) edge [below] node
  16598. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16599. \path[->,bend left=15] (F1-2) edge [below] node
  16600. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16601. \path[->,bend right=15] (F1-3) edge [above] node
  16602. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16603. \path[->,bend right=15] (F1-5) edge [right] node
  16604. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16605. \path[->,bend left=15] (F1-6) edge [right] node
  16606. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16607. \path[->,bend right=15] (C3-2) edge [right] node
  16608. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16609. \path[->,bend right=15] (x86-2) edge [below] node
  16610. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16611. \path[->,bend right=15] (x86-3) edge [below] node
  16612. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16613. \path[->,bend left=15] (x86-4) edge [above] node
  16614. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16615. \end{tikzpicture}
  16616. \fi}
  16617. \end{tcolorbox}
  16618. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16619. functions.}
  16620. \label{fig:Llambda-passes}
  16621. \end{figure}
  16622. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16623. needed for the compilation of \LangLam{}.
  16624. \clearpage
  16625. \section{Challenge: Optimize Closures}
  16626. \label{sec:optimize-closures}
  16627. In this chapter we compile lexically scoped functions into a
  16628. relatively efficient representation: flat closures. However, even this
  16629. representation comes with some overhead. For example, consider the
  16630. following program with a function \code{tail\_sum} that does not have
  16631. any free variables and where all the uses of \code{tail\_sum} are in
  16632. applications in which we know that only \code{tail\_sum} is being applied
  16633. (and not any other functions):
  16634. \begin{center}
  16635. \begin{minipage}{0.95\textwidth}
  16636. {\if\edition\racketEd
  16637. \begin{lstlisting}
  16638. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16639. (if (eq? n 0)
  16640. s
  16641. (tail_sum (- n 1) (+ n s))))
  16642. (+ (tail_sum 3 0) 36)
  16643. \end{lstlisting}
  16644. \fi}
  16645. {\if\edition\pythonEd\pythonColor
  16646. \begin{lstlisting}
  16647. def tail_sum(n : int, s : int) -> int:
  16648. if n == 0:
  16649. return s
  16650. else:
  16651. return tail_sum(n - 1, n + s)
  16652. print(tail_sum(3, 0) + 36)
  16653. \end{lstlisting}
  16654. \fi}
  16655. \end{minipage}
  16656. \end{center}
  16657. As described in this chapter, we uniformly apply closure conversion to
  16658. all functions, obtaining the following output for this program:
  16659. \begin{center}
  16660. \begin{minipage}{0.95\textwidth}
  16661. {\if\edition\racketEd
  16662. \begin{lstlisting}
  16663. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16664. (if (eq? n2 0)
  16665. s3
  16666. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16667. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16668. (define (main) : Integer
  16669. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16670. ((vector-ref clos6 0) clos6 3 0)) 27))
  16671. \end{lstlisting}
  16672. \fi}
  16673. {\if\edition\pythonEd\pythonColor
  16674. \begin{lstlisting}
  16675. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16676. if n_0 == 0:
  16677. return s_1
  16678. else:
  16679. return (let clos_2 = (tail_sum,)
  16680. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16681. def main() -> int :
  16682. print((let clos_4 = (tail_sum,)
  16683. in clos_4[0](clos_4, 3, 0)) + 36)
  16684. return 0
  16685. \end{lstlisting}
  16686. \fi}
  16687. \end{minipage}
  16688. \end{center}
  16689. If this program were compiled according to the previous chapter, there
  16690. would be no allocation and the calls to \code{tail\_sum} would be
  16691. direct calls. In contrast, the program presented here allocates memory
  16692. for each closure and the calls to \code{tail\_sum} are indirect. These
  16693. two differences incur considerable overhead in a program such as this,
  16694. in which the allocations and indirect calls occur inside a tight loop.
  16695. One might think that this problem is trivial to solve: can't we just
  16696. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16697. and compile them to direct calls instead of treating it like a call to
  16698. a closure? We would also drop the new \code{fvs} parameter of
  16699. \code{tail\_sum}.
  16700. %
  16701. However, this problem is not so trivial, because a global function may
  16702. \emph{escape} and become involved in applications that also involve
  16703. closures. Consider the following example in which the application
  16704. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16705. application because the \code{lambda} may flow into \code{f}, but the
  16706. \code{inc} function might also flow into \code{f}:
  16707. \begin{center}
  16708. \begin{minipage}{\textwidth}
  16709. % lambda_test_30.rkt
  16710. {\if\edition\racketEd
  16711. \begin{lstlisting}
  16712. (define (inc [x : Integer]) : Integer
  16713. (+ x 1))
  16714. (let ([y (read)])
  16715. (let ([f (if (eq? (read) 0)
  16716. inc
  16717. (lambda: ([x : Integer]) : Integer (- x y)))])
  16718. (f 41)))
  16719. \end{lstlisting}
  16720. \fi}
  16721. {\if\edition\pythonEd\pythonColor
  16722. \begin{lstlisting}
  16723. def add1(x : int) -> int:
  16724. return x + 1
  16725. y = input_int()
  16726. g : Callable[[int], int] = lambda x: x - y
  16727. f = add1 if input_int() == 0 else g
  16728. print(f(41))
  16729. \end{lstlisting}
  16730. \fi}
  16731. \end{minipage}
  16732. \end{center}
  16733. If a global function name is used in any way other than as the
  16734. operator in a direct call, then we say that the function
  16735. \emph{escapes}. If a global function does not escape, then we do not
  16736. need to perform closure conversion on the function.
  16737. \begin{exercise}\normalfont\normalsize
  16738. Implement an auxiliary function for detecting which global
  16739. functions escape. Using that function, implement an improved version
  16740. of closure conversion that does not apply closure conversion to
  16741. global functions that do not escape but instead compiles them as
  16742. regular functions. Create several new test cases that check whether
  16743. your compiler properly detects whether global functions escape or not.
  16744. \end{exercise}
  16745. So far we have reduced the overhead of calling global functions, but
  16746. it would also be nice to reduce the overhead of calling a
  16747. \code{lambda} when we can determine at compile time which
  16748. \code{lambda} will be called. We refer to such calls as \emph{known
  16749. calls}. Consider the following example in which a \code{lambda} is
  16750. bound to \code{f} and then applied.
  16751. {\if\edition\racketEd
  16752. % lambda_test_9.rkt
  16753. \begin{lstlisting}
  16754. (let ([y (read)])
  16755. (let ([f (lambda: ([x : Integer]) : Integer
  16756. (+ x y))])
  16757. (f 21)))
  16758. \end{lstlisting}
  16759. \fi}
  16760. {\if\edition\pythonEd\pythonColor
  16761. \begin{lstlisting}
  16762. y = input_int()
  16763. f : Callable[[int],int] = lambda x: x + y
  16764. print(f(21))
  16765. \end{lstlisting}
  16766. \fi}
  16767. %
  16768. \noindent Closure conversion compiles the application
  16769. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16770. %
  16771. {\if\edition\racketEd
  16772. \begin{lstlisting}
  16773. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16774. (let ([y2 (vector-ref fvs6 1)])
  16775. (+ x3 y2)))
  16776. (define (main) : Integer
  16777. (let ([y2 (read)])
  16778. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16779. ((vector-ref f4 0) f4 21))))
  16780. \end{lstlisting}
  16781. \fi}
  16782. {\if\edition\pythonEd\pythonColor
  16783. \begin{lstlisting}
  16784. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16785. y_1 = fvs_4[1]
  16786. return x_2 + y_1[0]
  16787. def main() -> int:
  16788. y_1 = (777,)
  16789. y_1[0] = input_int()
  16790. f_0 = (lambda_3, y_1)
  16791. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16792. return 0
  16793. \end{lstlisting}
  16794. \fi}
  16795. %
  16796. \noindent However, we can instead compile the application
  16797. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16798. %
  16799. {\if\edition\racketEd
  16800. \begin{lstlisting}
  16801. (define (main) : Integer
  16802. (let ([y2 (read)])
  16803. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16804. ((fun-ref lambda5 1) f4 21))))
  16805. \end{lstlisting}
  16806. \fi}
  16807. {\if\edition\pythonEd\pythonColor
  16808. \begin{lstlisting}
  16809. def main() -> int:
  16810. y_1 = (777,)
  16811. y_1[0] = input_int()
  16812. f_0 = (lambda_3, y_1)
  16813. print(lambda_3(f_0, 21))
  16814. return 0
  16815. \end{lstlisting}
  16816. \fi}
  16817. The problem of determining which \code{lambda} will be called from a
  16818. particular application is quite challenging in general and the topic
  16819. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16820. following exercise we recommend that you compile an application to a
  16821. direct call when the operator is a variable and \racket{the variable
  16822. is \code{let}-bound to a closure}\python{the previous assignment to
  16823. the variable is a closure}. This can be accomplished by maintaining
  16824. an environment that maps variables to function names. Extend the
  16825. environment whenever you encounter a closure on the right-hand side of
  16826. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16827. name of the global function for the closure. This pass should come
  16828. after closure conversion.
  16829. \begin{exercise}\normalfont\normalsize
  16830. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16831. compiles known calls into direct calls. Verify that your compiler is
  16832. successful in this regard on several example programs.
  16833. \end{exercise}
  16834. These exercises only scratch the surface of closure optimization. A
  16835. good next step for the interested reader is to look at the work of
  16836. \citet{Keep:2012ab}.
  16837. \section{Further Reading}
  16838. The notion of lexically scoped functions predates modern computers by
  16839. about a decade. They were invented by \citet{Church:1932aa}, who
  16840. proposed the lambda calculus as a foundation for logic. Anonymous
  16841. functions were included in the LISP~\citep{McCarthy:1960dz}
  16842. programming language but were initially dynamically scoped. The Scheme
  16843. dialect of LISP adopted lexical scoping, and
  16844. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16845. Scheme programs. However, environments were represented as linked
  16846. lists, so variable look-up was linear in the size of the
  16847. environment. \citet{Appel91} gives a detailed description of several
  16848. closure representations. In this chapter we represent environments
  16849. using flat closures, which were invented by
  16850. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16851. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16852. closures, variable look-up is constant time but the time to create a
  16853. closure is proportional to the number of its free variables. Flat
  16854. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16855. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16856. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16857. % compilers)
  16858. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16859. \chapter{Dynamic Typing}
  16860. \label{ch:Ldyn}
  16861. \index{subject}{dynamic typing}
  16862. \setcounter{footnote}{0}
  16863. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16864. typed language that is a subset of \racket{Racket}\python{Python}. The
  16865. focus on dynamic typing is in contrast to the previous chapters, which
  16866. have studied the compilation of statically typed languages. In
  16867. dynamically typed languages such as \LangDyn{}, a particular
  16868. expression may produce a value of a different type each time it is
  16869. executed. Consider the following example with a conditional \code{if}
  16870. expression that may return a Boolean or an integer depending on the
  16871. input to the program:
  16872. % part of dynamic_test_25.rkt
  16873. {\if\edition\racketEd
  16874. \begin{lstlisting}
  16875. (not (if (eq? (read) 1) #f 0))
  16876. \end{lstlisting}
  16877. \fi}
  16878. {\if\edition\pythonEd\pythonColor
  16879. \begin{lstlisting}
  16880. not (False if input_int() == 1 else 0)
  16881. \end{lstlisting}
  16882. \fi}
  16883. Languages that allow expressions to produce different kinds of values
  16884. are called \emph{polymorphic}, a word composed of the Greek roots
  16885. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16886. There are several kinds of polymorphism in programming languages, such as
  16887. subtype polymorphism\index{subject}{subtype polymorphism} and
  16888. parametric polymorphism\index{subject}{parametric polymorphism}
  16889. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16890. study in this chapter does not have a special name; it is the kind
  16891. that arises in dynamically typed languages.
  16892. Another characteristic of dynamically typed languages is that
  16893. their primitive operations, such as \code{not}, are often defined to operate
  16894. on many different types of values. In fact, in
  16895. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16896. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16897. given anything else it returns \FALSE{}.
  16898. Furthermore, even when primitive operations restrict their inputs to
  16899. values of a certain type, this restriction is enforced at runtime
  16900. instead of during compilation. For example, the tuple read
  16901. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16902. results in a runtime error because the first argument must
  16903. be a tuple, not a Boolean.
  16904. \section{The \LangDyn{} Language}
  16905. \newcommand{\LdynGrammarRacket}{
  16906. \begin{array}{rcl}
  16907. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16908. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16909. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16910. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16911. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16912. \end{array}
  16913. }
  16914. \newcommand{\LdynASTRacket}{
  16915. \begin{array}{lcl}
  16916. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16917. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16918. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16919. \end{array}
  16920. }
  16921. \begin{figure}[tp]
  16922. \centering
  16923. \begin{tcolorbox}[colback=white]
  16924. \small
  16925. {\if\edition\racketEd
  16926. \[
  16927. \begin{array}{l}
  16928. \gray{\LintGrammarRacket{}} \\ \hline
  16929. \gray{\LvarGrammarRacket{}} \\ \hline
  16930. \gray{\LifGrammarRacket{}} \\ \hline
  16931. \gray{\LwhileGrammarRacket} \\ \hline
  16932. \gray{\LtupGrammarRacket} \\ \hline
  16933. \LdynGrammarRacket \\
  16934. \begin{array}{rcl}
  16935. \LangDynM{} &::=& \Def\ldots\; \Exp
  16936. \end{array}
  16937. \end{array}
  16938. \]
  16939. \fi}
  16940. {\if\edition\pythonEd\pythonColor
  16941. \[
  16942. \begin{array}{rcl}
  16943. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16944. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16945. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16946. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16947. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16948. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16949. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16950. \MID \CLEN{\Exp} \\
  16951. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16952. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16953. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16954. \MID \Var\mathop{\key{=}}\Exp \\
  16955. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16956. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16957. &\MID& \CRETURN{\Exp} \\
  16958. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16959. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16960. \end{array}
  16961. \]
  16962. \fi}
  16963. \end{tcolorbox}
  16964. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16965. \label{fig:r7-concrete-syntax}
  16966. \end{figure}
  16967. \begin{figure}[tp]
  16968. \centering
  16969. \begin{tcolorbox}[colback=white]
  16970. \small
  16971. {\if\edition\racketEd
  16972. \[
  16973. \begin{array}{l}
  16974. \gray{\LintASTRacket{}} \\ \hline
  16975. \gray{\LvarASTRacket{}} \\ \hline
  16976. \gray{\LifASTRacket{}} \\ \hline
  16977. \gray{\LwhileASTRacket} \\ \hline
  16978. \gray{\LtupASTRacket} \\ \hline
  16979. \LdynASTRacket \\
  16980. \begin{array}{lcl}
  16981. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16982. \end{array}
  16983. \end{array}
  16984. \]
  16985. \fi}
  16986. {\if\edition\pythonEd\pythonColor
  16987. \[
  16988. \begin{array}{rcl}
  16989. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16990. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16991. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16992. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16993. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16994. &\MID & \code{Is()} \\
  16995. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16996. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16997. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16998. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16999. \MID \VAR{\Var{}} \\
  17000. &\MID& \BOOL{\itm{bool}}
  17001. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17002. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17003. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17004. &\MID& \LEN{\Exp} \\
  17005. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17006. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17007. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17008. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17009. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17010. &\MID& \RETURN{\Exp} \\
  17011. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17012. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17013. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17014. \end{array}
  17015. \]
  17016. \fi}
  17017. \end{tcolorbox}
  17018. \caption{The abstract syntax of \LangDyn{}.}
  17019. \label{fig:r7-syntax}
  17020. \end{figure}
  17021. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17022. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17023. %
  17024. There is no type checker for \LangDyn{} because it checks types only
  17025. at runtime.
  17026. The definitional interpreter for \LangDyn{} is presented in
  17027. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17028. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17029. \INT{n}. Instead of simply returning the integer \code{n} (as
  17030. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17031. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17032. value} that combines an underlying value with a tag that identifies
  17033. what kind of value it is. We define the following \racket{struct}\python{class}
  17034. to represent tagged values:
  17035. %
  17036. {\if\edition\racketEd
  17037. \begin{lstlisting}
  17038. (struct Tagged (value tag) #:transparent)
  17039. \end{lstlisting}
  17040. \fi}
  17041. {\if\edition\pythonEd\pythonColor
  17042. \begin{minipage}{\textwidth}
  17043. \begin{lstlisting}
  17044. @dataclass(eq=True)
  17045. class Tagged(Value):
  17046. value : Value
  17047. tag : str
  17048. def __str__(self):
  17049. return str(self.value)
  17050. \end{lstlisting}
  17051. \end{minipage}
  17052. \fi}
  17053. %
  17054. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17055. \code{Vector}, and \code{Procedure}.}
  17056. %
  17057. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17058. \skey{tuple}, and \skey{function}.}
  17059. %
  17060. Tags are closely related to types but do not always capture all the
  17061. information that a type does.
  17062. %
  17063. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17064. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17065. Any)} is tagged with \code{Procedure}.}
  17066. %
  17067. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17068. is tagged with \skey{tuple} and a function of type
  17069. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17070. is tagged with \skey{function}.}
  17071. Next consider the match case for accessing the element of a tuple.
  17072. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17073. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17074. argument is a tuple and the second is an integer.
  17075. \racket{
  17076. If they are not, a \code{trapped-error} is raised. Recall from
  17077. section~\ref{sec:interp_Lint} that when a definition interpreter
  17078. raises a \code{trapped-error} error, the compiled code must also
  17079. signal an error by exiting with return code \code{255}. A
  17080. \code{trapped-error} is also raised if the index is not less than the
  17081. length of the vector.
  17082. }
  17083. %
  17084. \python{If they are not, an exception is raised. The compiled code
  17085. must also signal an error by exiting with return code \code{255}. A
  17086. exception is also raised if the index is not less than the length of the
  17087. tuple or if it is negative.}
  17088. \begin{figure}[tbp]
  17089. \begin{tcolorbox}[colback=white]
  17090. {\if\edition\racketEd
  17091. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17092. (define ((interp-Ldyn-exp env) ast)
  17093. (define recur (interp-Ldyn-exp env))
  17094. (match ast
  17095. [(Var x) (dict-ref env x)]
  17096. [(Int n) (Tagged n 'Integer)]
  17097. [(Bool b) (Tagged b 'Boolean)]
  17098. [(Lambda xs rt body)
  17099. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17100. [(Prim 'vector es)
  17101. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17102. [(Prim 'vector-ref (list e1 e2))
  17103. (define vec (recur e1)) (define i (recur e2))
  17104. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17105. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17106. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17107. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17108. [(Prim 'vector-set! (list e1 e2 e3))
  17109. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17110. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17111. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17112. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17113. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17114. (Tagged (void) 'Void)]
  17115. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17116. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17117. [(Prim 'or (list e1 e2))
  17118. (define v1 (recur e1))
  17119. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17120. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17121. [(Prim op (list e1))
  17122. #:when (set-member? type-predicates op)
  17123. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17124. [(Prim op es)
  17125. (define args (map recur es))
  17126. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17127. (unless (for/or ([expected-tags (op-tags op)])
  17128. (equal? expected-tags tags))
  17129. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17130. (tag-value
  17131. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17132. [(If q t f)
  17133. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17134. [(Apply f es)
  17135. (define new-f (recur f)) (define args (map recur es))
  17136. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17137. (match f-val
  17138. [`(function ,xs ,body ,lam-env)
  17139. (unless (eq? (length xs) (length args))
  17140. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17141. (define new-env (append (map cons xs args) lam-env))
  17142. ((interp-Ldyn-exp new-env) body)]
  17143. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17144. \end{lstlisting}
  17145. \fi}
  17146. {\if\edition\pythonEd\pythonColor
  17147. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17148. class InterpLdyn(InterpLlambda):
  17149. def interp_exp(self, e, env):
  17150. match e:
  17151. case Constant(n):
  17152. return self.tag(super().interp_exp(e, env))
  17153. case Tuple(es, Load()):
  17154. return self.tag(super().interp_exp(e, env))
  17155. case Lambda(params, body):
  17156. return self.tag(super().interp_exp(e, env))
  17157. case Call(Name('input_int'), []):
  17158. return self.tag(super().interp_exp(e, env))
  17159. case BinOp(left, Add(), right):
  17160. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17161. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17162. case BinOp(left, Sub(), right):
  17163. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17164. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17165. case UnaryOp(USub(), e1):
  17166. v = self.interp_exp(e1, env)
  17167. return self.tag(- self.untag(v, 'int', e))
  17168. case IfExp(test, body, orelse):
  17169. v = self.interp_exp(test, env)
  17170. if self.untag(v, 'bool', e):
  17171. return self.interp_exp(body, env)
  17172. else:
  17173. return self.interp_exp(orelse, env)
  17174. case UnaryOp(Not(), e1):
  17175. v = self.interp_exp(e1, env)
  17176. return self.tag(not self.untag(v, 'bool', e))
  17177. case BoolOp(And(), values):
  17178. left = values[0]; right = values[1]
  17179. l = self.interp_exp(left, env)
  17180. if self.untag(l, 'bool', e):
  17181. return self.interp_exp(right, env)
  17182. else:
  17183. return self.tag(False)
  17184. case BoolOp(Or(), values):
  17185. left = values[0]; right = values[1]
  17186. l = self.interp_exp(left, env)
  17187. if self.untag(l, 'bool', e):
  17188. return self.tag(True)
  17189. else:
  17190. return self.interp_exp(right, env)
  17191. case Compare(left, [cmp], [right]):
  17192. l = self.interp_exp(left, env)
  17193. r = self.interp_exp(right, env)
  17194. if l.tag == r.tag:
  17195. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17196. else:
  17197. raise Exception('interp Compare unexpected '
  17198. + repr(l) + ' ' + repr(r))
  17199. case Subscript(tup, index, Load()):
  17200. t = self.interp_exp(tup, env)
  17201. n = self.interp_exp(index, env)
  17202. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17203. case Call(Name('len'), [tup]):
  17204. t = self.interp_exp(tup, env)
  17205. return self.tag(len(self.untag(t, 'tuple', e)))
  17206. case _:
  17207. return self.tag(super().interp_exp(e, env))
  17208. \end{lstlisting}
  17209. \fi}
  17210. \end{tcolorbox}
  17211. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17212. \label{fig:interp-Ldyn}
  17213. \end{figure}
  17214. {\if\edition\pythonEd\pythonColor
  17215. \begin{figure}[tbp]
  17216. \begin{tcolorbox}[colback=white]
  17217. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17218. class InterpLdyn(InterpLlambda):
  17219. def interp_stmt(self, s, env, cont):
  17220. match s:
  17221. case If(test, body, orelse):
  17222. v = self.interp_exp(test, env)
  17223. match self.untag(v, 'bool', s):
  17224. case True:
  17225. return self.interp_stmts(body + cont, env)
  17226. case False:
  17227. return self.interp_stmts(orelse + cont, env)
  17228. case While(test, body, []):
  17229. v = self.interp_exp(test, env)
  17230. if self.untag(v, 'bool', test):
  17231. self.interp_stmts(body + [s] + cont, env)
  17232. else:
  17233. return self.interp_stmts(cont, env)
  17234. case Assign([Subscript(tup, index)], value):
  17235. tup = self.interp_exp(tup, env)
  17236. index = self.interp_exp(index, env)
  17237. tup_v = self.untag(tup, 'tuple', s)
  17238. index_v = self.untag(index, 'int', s)
  17239. tup_v[index_v] = self.interp_exp(value, env)
  17240. return self.interp_stmts(cont, env)
  17241. case FunctionDef(name, params, bod, dl, returns, comment):
  17242. if isinstance(params, ast.arguments):
  17243. ps = [p.arg for p in params.args]
  17244. else:
  17245. ps = [x for (x,t) in params]
  17246. env[name] = self.tag(Function(name, ps, bod, env))
  17247. return self.interp_stmts(cont, env)
  17248. case _:
  17249. return super().interp_stmt(s, env, cont)
  17250. \end{lstlisting}
  17251. \end{tcolorbox}
  17252. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17253. \label{fig:interp-Ldyn-2}
  17254. \end{figure}
  17255. \fi}
  17256. \begin{figure}[tbp]
  17257. \begin{tcolorbox}[colback=white]
  17258. {\if\edition\racketEd
  17259. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17260. (define (interp-op op)
  17261. (match op
  17262. ['+ fx+]
  17263. ['- fx-]
  17264. ['read read-fixnum]
  17265. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17266. ['< (lambda (v1 v2)
  17267. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17268. ['<= (lambda (v1 v2)
  17269. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17270. ['> (lambda (v1 v2)
  17271. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17272. ['>= (lambda (v1 v2)
  17273. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17274. ['boolean? boolean?]
  17275. ['integer? fixnum?]
  17276. ['void? void?]
  17277. ['vector? vector?]
  17278. ['vector-length vector-length]
  17279. ['procedure? (match-lambda
  17280. [`(functions ,xs ,body ,env) #t] [else #f])]
  17281. [else (error 'interp-op "unknown operator" op)]))
  17282. (define (op-tags op)
  17283. (match op
  17284. ['+ '((Integer Integer))]
  17285. ['- '((Integer Integer) (Integer))]
  17286. ['read '(())]
  17287. ['not '((Boolean))]
  17288. ['< '((Integer Integer))]
  17289. ['<= '((Integer Integer))]
  17290. ['> '((Integer Integer))]
  17291. ['>= '((Integer Integer))]
  17292. ['vector-length '((Vector))]))
  17293. (define type-predicates
  17294. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17295. (define (tag-value v)
  17296. (cond [(boolean? v) (Tagged v 'Boolean)]
  17297. [(fixnum? v) (Tagged v 'Integer)]
  17298. [(procedure? v) (Tagged v 'Procedure)]
  17299. [(vector? v) (Tagged v 'Vector)]
  17300. [(void? v) (Tagged v 'Void)]
  17301. [else (error 'tag-value "unidentified value ~a" v)]))
  17302. (define (check-tag val expected ast)
  17303. (define tag (Tagged-tag val))
  17304. (unless (eq? tag expected)
  17305. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17306. \end{lstlisting}
  17307. \fi}
  17308. {\if\edition\pythonEd\pythonColor
  17309. \begin{lstlisting}
  17310. class InterpLdyn(InterpLlambda):
  17311. def tag(self, v):
  17312. if v is True or v is False:
  17313. return Tagged(v, 'bool')
  17314. elif isinstance(v, int):
  17315. return Tagged(v, 'int')
  17316. elif isinstance(v, Function):
  17317. return Tagged(v, 'function')
  17318. elif isinstance(v, tuple):
  17319. return Tagged(v, 'tuple')
  17320. elif isinstance(v, type(None)):
  17321. return Tagged(v, 'none')
  17322. else:
  17323. raise Exception('tag: unexpected ' + repr(v))
  17324. def untag(self, v, expected_tag, ast):
  17325. match v:
  17326. case Tagged(val, tag) if tag == expected_tag:
  17327. return val
  17328. case _:
  17329. raise TrappedError('expected Tagged value with '
  17330. + expected_tag + ', not ' + ' ' + repr(v))
  17331. def apply_fun(self, fun, args, e):
  17332. f = self.untag(fun, 'function', e)
  17333. return super().apply_fun(f, args, e)
  17334. \end{lstlisting}
  17335. \fi}
  17336. \end{tcolorbox}
  17337. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17338. \label{fig:interp-Ldyn-aux}
  17339. \end{figure}
  17340. \clearpage
  17341. \section{Representation of Tagged Values}
  17342. The interpreter for \LangDyn{} introduced a new kind of value: the
  17343. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17344. represent tagged values at the bit level. Because almost every
  17345. operation in \LangDyn{} involves manipulating tagged values, the
  17346. representation must be efficient. Recall that all our values are 64
  17347. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17348. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17349. $011$ for procedures, and $101$ for the void value\python{,
  17350. \key{None}}. We define the following auxiliary function for mapping
  17351. types to tag codes:
  17352. %
  17353. {\if\edition\racketEd
  17354. \begin{align*}
  17355. \itm{tagof}(\key{Integer}) &= 001 \\
  17356. \itm{tagof}(\key{Boolean}) &= 100 \\
  17357. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17358. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17359. \itm{tagof}(\key{Void}) &= 101
  17360. \end{align*}
  17361. \fi}
  17362. {\if\edition\pythonEd\pythonColor
  17363. \begin{align*}
  17364. \itm{tagof}(\key{IntType()}) &= 001 \\
  17365. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17366. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17367. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17368. \itm{tagof}(\key{type(None)}) &= 101
  17369. \end{align*}
  17370. \fi}
  17371. %
  17372. This stealing of 3 bits comes at some price: integers are now restricted
  17373. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17374. affect tuples and procedures because those values are addresses, and
  17375. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17376. they are always $000$. Thus, we do not lose information by overwriting
  17377. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17378. to recover the original address.
  17379. To make tagged values into first-class entities, we can give them a
  17380. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17381. operations such as \code{Inject} and \code{Project} for creating and
  17382. using them, yielding the statically typed \LangAny{} intermediate
  17383. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17384. section~\ref{sec:compile-r7}; in the next section we describe the
  17385. \LangAny{} language in greater detail.
  17386. \section{The \LangAny{} Language}
  17387. \label{sec:Rany-lang}
  17388. \newcommand{\LanyASTRacket}{
  17389. \begin{array}{lcl}
  17390. \Type &::= & \ANYTY \\
  17391. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17392. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17393. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17394. \itm{op} &::= & \code{any-vector-length}
  17395. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17396. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17397. \MID \code{procedure?} \MID \code{void?} \\
  17398. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17399. \end{array}
  17400. }
  17401. \newcommand{\LanyASTPython}{
  17402. \begin{array}{lcl}
  17403. \Type &::= & \key{AnyType()} \\
  17404. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17405. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17406. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17407. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17408. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17409. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17410. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17411. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17412. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17413. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17414. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17415. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17416. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17417. \end{array}
  17418. }
  17419. \begin{figure}[tp]
  17420. \centering
  17421. \begin{tcolorbox}[colback=white]
  17422. \small
  17423. {\if\edition\racketEd
  17424. \[
  17425. \begin{array}{l}
  17426. \gray{\LintOpAST} \\ \hline
  17427. \gray{\LvarASTRacket{}} \\ \hline
  17428. \gray{\LifASTRacket{}} \\ \hline
  17429. \gray{\LwhileASTRacket{}} \\ \hline
  17430. \gray{\LtupASTRacket{}} \\ \hline
  17431. \gray{\LfunASTRacket} \\ \hline
  17432. \gray{\LlambdaASTRacket} \\ \hline
  17433. \LanyASTRacket \\
  17434. \begin{array}{lcl}
  17435. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17436. \end{array}
  17437. \end{array}
  17438. \]
  17439. \fi}
  17440. {\if\edition\pythonEd\pythonColor
  17441. \[
  17442. \begin{array}{l}
  17443. \gray{\LintASTPython} \\ \hline
  17444. \gray{\LvarASTPython{}} \\ \hline
  17445. \gray{\LifASTPython{}} \\ \hline
  17446. \gray{\LwhileASTPython{}} \\ \hline
  17447. \gray{\LtupASTPython{}} \\ \hline
  17448. \gray{\LfunASTPython} \\ \hline
  17449. \gray{\LlambdaASTPython} \\ \hline
  17450. \LanyASTPython \\
  17451. \begin{array}{lcl}
  17452. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17453. \end{array}
  17454. \end{array}
  17455. \]
  17456. \fi}
  17457. \end{tcolorbox}
  17458. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17459. \label{fig:Lany-syntax}
  17460. \end{figure}
  17461. The definition of the abstract syntax of \LangAny{} is given in
  17462. figure~\ref{fig:Lany-syntax}.
  17463. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17464. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17465. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17466. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17467. converts the tagged value produced by expression $e$ into a value of
  17468. type $T$ or halts the program if the type tag does not match $T$.
  17469. %
  17470. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17471. restricted to be a flat type (the nonterminal $\FType$) which
  17472. simplifies the implementation and complies with the needs for
  17473. compiling \LangDyn{}.
  17474. The \racket{\code{any-vector}} operators
  17475. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17476. operations so that they can be applied to a value of type
  17477. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17478. tuple operations in that the index is not restricted to a literal
  17479. integer in the grammar but is allowed to be any expression.
  17480. \racket{The type predicates such as
  17481. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17482. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17483. the predicate and return {\FALSE} otherwise.}
  17484. The type checker for \LangAny{} is shown in
  17485. figure~\ref{fig:type-check-Lany}
  17486. %
  17487. \racket{ and uses the auxiliary functions presented in
  17488. figure~\ref{fig:type-check-Lany-aux}}.
  17489. %
  17490. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17491. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17492. \begin{figure}[btp]
  17493. \begin{tcolorbox}[colback=white]
  17494. {\if\edition\racketEd
  17495. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17496. (define type-check-Lany-class
  17497. (class type-check-Llambda-class
  17498. (super-new)
  17499. (inherit check-type-equal?)
  17500. (define/override (type-check-exp env)
  17501. (lambda (e)
  17502. (define recur (type-check-exp env))
  17503. (match e
  17504. [(Inject e1 ty)
  17505. (unless (flat-ty? ty)
  17506. (error 'type-check "may only inject from flat type, not ~a" ty))
  17507. (define-values (new-e1 e-ty) (recur e1))
  17508. (check-type-equal? e-ty ty e)
  17509. (values (Inject new-e1 ty) 'Any)]
  17510. [(Project e1 ty)
  17511. (unless (flat-ty? ty)
  17512. (error 'type-check "may only project to flat type, not ~a" ty))
  17513. (define-values (new-e1 e-ty) (recur e1))
  17514. (check-type-equal? e-ty 'Any e)
  17515. (values (Project new-e1 ty) ty)]
  17516. [(Prim 'any-vector-length (list e1))
  17517. (define-values (e1^ t1) (recur e1))
  17518. (check-type-equal? t1 'Any e)
  17519. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17520. [(Prim 'any-vector-ref (list e1 e2))
  17521. (define-values (e1^ t1) (recur e1))
  17522. (define-values (e2^ t2) (recur e2))
  17523. (check-type-equal? t1 'Any e)
  17524. (check-type-equal? t2 'Integer e)
  17525. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17526. [(Prim 'any-vector-set! (list e1 e2 e3))
  17527. (define-values (e1^ t1) (recur e1))
  17528. (define-values (e2^ t2) (recur e2))
  17529. (define-values (e3^ t3) (recur e3))
  17530. (check-type-equal? t1 'Any e)
  17531. (check-type-equal? t2 'Integer e)
  17532. (check-type-equal? t3 'Any e)
  17533. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17534. [(Prim pred (list e1))
  17535. #:when (set-member? (type-predicates) pred)
  17536. (define-values (new-e1 e-ty) (recur e1))
  17537. (check-type-equal? e-ty 'Any e)
  17538. (values (Prim pred (list new-e1)) 'Boolean)]
  17539. [(Prim 'eq? (list arg1 arg2))
  17540. (define-values (e1 t1) (recur arg1))
  17541. (define-values (e2 t2) (recur arg2))
  17542. (match* (t1 t2)
  17543. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17544. [(other wise) (check-type-equal? t1 t2 e)])
  17545. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17546. [else ((super type-check-exp env) e)])))
  17547. ))
  17548. \end{lstlisting}
  17549. \fi}
  17550. {\if\edition\pythonEd\pythonColor
  17551. \begin{lstlisting}
  17552. class TypeCheckLany(TypeCheckLlambda):
  17553. def type_check_exp(self, e, env):
  17554. match e:
  17555. case Inject(value, typ):
  17556. self.check_exp(value, typ, env)
  17557. return AnyType()
  17558. case Project(value, typ):
  17559. self.check_exp(value, AnyType(), env)
  17560. return typ
  17561. case Call(Name('any_tuple_load'), [tup, index]):
  17562. self.check_exp(tup, AnyType(), env)
  17563. self.check_exp(index, IntType(), env)
  17564. return AnyType()
  17565. case Call(Name('any_len'), [tup]):
  17566. self.check_exp(tup, AnyType(), env)
  17567. return IntType()
  17568. case Call(Name('arity'), [fun]):
  17569. ty = self.type_check_exp(fun, env)
  17570. match ty:
  17571. case FunctionType(ps, rt):
  17572. return IntType()
  17573. case TupleType([FunctionType(ps,rs)]):
  17574. return IntType()
  17575. case _:
  17576. raise Exception('type check arity unexpected ' + repr(ty))
  17577. case Call(Name('make_any'), [value, tag]):
  17578. self.type_check_exp(value, env)
  17579. self.check_exp(tag, IntType(), env)
  17580. return AnyType()
  17581. case AnnLambda(params, returns, body):
  17582. new_env = {x:t for (x,t) in env.items()}
  17583. for (x,t) in params:
  17584. new_env[x] = t
  17585. return_t = self.type_check_exp(body, new_env)
  17586. self.check_type_equal(returns, return_t, e)
  17587. return FunctionType([t for (x,t) in params], return_t)
  17588. case _:
  17589. return super().type_check_exp(e, env)
  17590. \end{lstlisting}
  17591. \fi}
  17592. \end{tcolorbox}
  17593. \caption{Type checker for the \LangAny{} language.}
  17594. \label{fig:type-check-Lany}
  17595. \end{figure}
  17596. {\if\edition\racketEd
  17597. \begin{figure}[tbp]
  17598. \begin{tcolorbox}[colback=white]
  17599. \begin{lstlisting}
  17600. (define/override (operator-types)
  17601. (append
  17602. '((integer? . ((Any) . Boolean))
  17603. (vector? . ((Any) . Boolean))
  17604. (procedure? . ((Any) . Boolean))
  17605. (void? . ((Any) . Boolean)))
  17606. (super operator-types)))
  17607. (define/public (type-predicates)
  17608. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17609. (define/public (flat-ty? ty)
  17610. (match ty
  17611. [(or `Integer `Boolean `Void) #t]
  17612. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17613. [`(,ts ... -> ,rt)
  17614. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17615. [else #f]))
  17616. \end{lstlisting}
  17617. \end{tcolorbox}
  17618. \caption{Auxiliary methods for type checking \LangAny{}.}
  17619. \label{fig:type-check-Lany-aux}
  17620. \end{figure}
  17621. \fi}
  17622. \begin{figure}[btp]
  17623. \begin{tcolorbox}[colback=white]
  17624. {\if\edition\racketEd
  17625. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17626. (define interp-Lany-class
  17627. (class interp-Llambda-class
  17628. (super-new)
  17629. (define/override (interp-op op)
  17630. (match op
  17631. ['boolean? (match-lambda
  17632. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17633. [else #f])]
  17634. ['integer? (match-lambda
  17635. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17636. [else #f])]
  17637. ['vector? (match-lambda
  17638. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17639. [else #f])]
  17640. ['procedure? (match-lambda
  17641. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17642. [else #f])]
  17643. ['eq? (match-lambda*
  17644. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17645. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17646. [ls (apply (super interp-op op) ls)])]
  17647. ['any-vector-ref (lambda (v i)
  17648. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17649. ['any-vector-set! (lambda (v i a)
  17650. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17651. ['any-vector-length (lambda (v)
  17652. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17653. [else (super interp-op op)]))
  17654. (define/override ((interp-exp env) e)
  17655. (define recur (interp-exp env))
  17656. (match e
  17657. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17658. [(Project e ty2) (apply-project (recur e) ty2)]
  17659. [else ((super interp-exp env) e)]))
  17660. ))
  17661. (define (interp-Lany p)
  17662. (send (new interp-Lany-class) interp-program p))
  17663. \end{lstlisting}
  17664. \fi}
  17665. {\if\edition\pythonEd\pythonColor
  17666. \begin{lstlisting}
  17667. class InterpLany(InterpLlambda):
  17668. def interp_exp(self, e, env):
  17669. match e:
  17670. case Inject(value, typ):
  17671. v = self.interp_exp(value, env)
  17672. return Tagged(v, self.type_to_tag(typ))
  17673. case Project(value, typ):
  17674. v = self.interp_exp(value, env)
  17675. match v:
  17676. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17677. return val
  17678. case _:
  17679. raise Exception('interp project to ' + repr(typ)
  17680. + ' unexpected ' + repr(v))
  17681. case Call(Name('any_tuple_load'), [tup, index]):
  17682. tv = self.interp_exp(tup, env)
  17683. n = self.interp_exp(index, env)
  17684. match tv:
  17685. case Tagged(v, tag):
  17686. return v[n]
  17687. case _:
  17688. raise Exception('in any_tuple_load unexpected ' + repr(tv))
  17689. case Call(Name('any_len'), [value]):
  17690. v = self.interp_exp(value, env)
  17691. match v:
  17692. case Tagged(value, tag):
  17693. return len(value)
  17694. case _:
  17695. raise Exception('interp any_len unexpected ' + repr(v))
  17696. case Call(Name('arity'), [fun]):
  17697. f = self.interp_exp(fun, env)
  17698. return self.arity(f)
  17699. case _:
  17700. return super().interp_exp(e, env)
  17701. \end{lstlisting}
  17702. \fi}
  17703. \end{tcolorbox}
  17704. \caption{Interpreter for \LangAny{}.}
  17705. \label{fig:interp-Lany}
  17706. \end{figure}
  17707. \begin{figure}[tbp]
  17708. \begin{tcolorbox}[colback=white]
  17709. {\if\edition\racketEd
  17710. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17711. (define/public (apply-inject v tg) (Tagged v tg))
  17712. (define/public (apply-project v ty2)
  17713. (define tag2 (any-tag ty2))
  17714. (match v
  17715. [(Tagged v1 tag1)
  17716. (cond
  17717. [(eq? tag1 tag2)
  17718. (match ty2
  17719. [`(Vector ,ts ...)
  17720. (define l1 ((interp-op 'vector-length) v1))
  17721. (cond
  17722. [(eq? l1 (length ts)) v1]
  17723. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17724. l1 (length ts))])]
  17725. [`(,ts ... -> ,rt)
  17726. (match v1
  17727. [`(function ,xs ,body ,env)
  17728. (cond [(eq? (length xs) (length ts)) v1]
  17729. [else
  17730. (error 'apply-project "arity mismatch ~a != ~a"
  17731. (length xs) (length ts))])]
  17732. [else (error 'apply-project "expected function not ~a" v1)])]
  17733. [else v1])]
  17734. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17735. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17736. \end{lstlisting}
  17737. \fi}
  17738. {\if\edition\pythonEd\pythonColor
  17739. \begin{lstlisting}
  17740. class InterpLany(InterpLlambda):
  17741. def type_to_tag(self, typ):
  17742. match typ:
  17743. case FunctionType(params, rt):
  17744. return 'function'
  17745. case TupleType(fields):
  17746. return 'tuple'
  17747. case t if t == int:
  17748. return 'int'
  17749. case t if t == bool:
  17750. return 'bool'
  17751. case IntType():
  17752. return 'int'
  17753. case BoolType():
  17754. return 'int'
  17755. case _:
  17756. raise Exception('type_to_tag unexpected ' + repr(typ))
  17757. def arity(self, v):
  17758. match v:
  17759. case Function(name, params, body, env):
  17760. return len(params)
  17761. case ClosureTuple(args, arity):
  17762. return arity
  17763. case _:
  17764. raise Exception('Lany arity unexpected ' + repr(v))
  17765. \end{lstlisting}
  17766. \fi}
  17767. \end{tcolorbox}
  17768. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17769. \label{fig:interp-Lany-aux}
  17770. \end{figure}
  17771. \clearpage
  17772. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17773. \label{sec:compile-r7}
  17774. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17775. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17776. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17777. is that given any subexpression $e$ in the \LangDyn{} program, the
  17778. pass will produce an expression $e'$ in \LangAny{} that has type
  17779. \ANYTY{}. For example, the first row in
  17780. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17781. \TRUE{}, which must be injected to produce an expression of type
  17782. \ANYTY{}.
  17783. %
  17784. The compilation of addition is shown in the second row of
  17785. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17786. representative of many primitive operations: the arguments have type
  17787. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17788. be performed.
  17789. The compilation of \key{lambda} (third row of
  17790. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17791. produce type annotations: we simply use \ANYTY{}.
  17792. %
  17793. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17794. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17795. this pass has to account for some differences in behavior between
  17796. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17797. permissive than \LangAny{} regarding what kind of values can be used
  17798. in various places. For example, the condition of an \key{if} does
  17799. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17800. of the same type (in that case the result is \code{\#f}).}
  17801. \begin{figure}[btp]
  17802. \centering
  17803. \begin{tcolorbox}[colback=white]
  17804. {\if\edition\racketEd
  17805. \begin{tabular}{lll}
  17806. \begin{minipage}{0.27\textwidth}
  17807. \begin{lstlisting}
  17808. #t
  17809. \end{lstlisting}
  17810. \end{minipage}
  17811. &
  17812. $\Rightarrow$
  17813. &
  17814. \begin{minipage}{0.65\textwidth}
  17815. \begin{lstlisting}
  17816. (inject #t Boolean)
  17817. \end{lstlisting}
  17818. \end{minipage}
  17819. \\[2ex]\hline
  17820. \begin{minipage}{0.27\textwidth}
  17821. \begin{lstlisting}
  17822. (+ |$e_1$| |$e_2$|)
  17823. \end{lstlisting}
  17824. \end{minipage}
  17825. &
  17826. $\Rightarrow$
  17827. &
  17828. \begin{minipage}{0.65\textwidth}
  17829. \begin{lstlisting}
  17830. (inject
  17831. (+ (project |$e'_1$| Integer)
  17832. (project |$e'_2$| Integer))
  17833. Integer)
  17834. \end{lstlisting}
  17835. \end{minipage}
  17836. \\[2ex]\hline
  17837. \begin{minipage}{0.27\textwidth}
  17838. \begin{lstlisting}
  17839. (lambda (|$x_1 \ldots$|) |$e$|)
  17840. \end{lstlisting}
  17841. \end{minipage}
  17842. &
  17843. $\Rightarrow$
  17844. &
  17845. \begin{minipage}{0.65\textwidth}
  17846. \begin{lstlisting}
  17847. (inject
  17848. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17849. (Any|$\ldots$|Any -> Any))
  17850. \end{lstlisting}
  17851. \end{minipage}
  17852. \\[2ex]\hline
  17853. \begin{minipage}{0.27\textwidth}
  17854. \begin{lstlisting}
  17855. (|$e_0$| |$e_1 \ldots e_n$|)
  17856. \end{lstlisting}
  17857. \end{minipage}
  17858. &
  17859. $\Rightarrow$
  17860. &
  17861. \begin{minipage}{0.65\textwidth}
  17862. \begin{lstlisting}
  17863. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17864. \end{lstlisting}
  17865. \end{minipage}
  17866. \\[2ex]\hline
  17867. \begin{minipage}{0.27\textwidth}
  17868. \begin{lstlisting}
  17869. (vector-ref |$e_1$| |$e_2$|)
  17870. \end{lstlisting}
  17871. \end{minipage}
  17872. &
  17873. $\Rightarrow$
  17874. &
  17875. \begin{minipage}{0.65\textwidth}
  17876. \begin{lstlisting}
  17877. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17878. \end{lstlisting}
  17879. \end{minipage}
  17880. \\[2ex]\hline
  17881. \begin{minipage}{0.27\textwidth}
  17882. \begin{lstlisting}
  17883. (if |$e_1$| |$e_2$| |$e_3$|)
  17884. \end{lstlisting}
  17885. \end{minipage}
  17886. &
  17887. $\Rightarrow$
  17888. &
  17889. \begin{minipage}{0.65\textwidth}
  17890. \begin{lstlisting}
  17891. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17892. \end{lstlisting}
  17893. \end{minipage}
  17894. \\[2ex]\hline
  17895. \begin{minipage}{0.27\textwidth}
  17896. \begin{lstlisting}
  17897. (eq? |$e_1$| |$e_2$|)
  17898. \end{lstlisting}
  17899. \end{minipage}
  17900. &
  17901. $\Rightarrow$
  17902. &
  17903. \begin{minipage}{0.65\textwidth}
  17904. \begin{lstlisting}
  17905. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17906. \end{lstlisting}
  17907. \end{minipage}
  17908. \\[2ex]\hline
  17909. \begin{minipage}{0.27\textwidth}
  17910. \begin{lstlisting}
  17911. (not |$e_1$|)
  17912. \end{lstlisting}
  17913. \end{minipage}
  17914. &
  17915. $\Rightarrow$
  17916. &
  17917. \begin{minipage}{0.65\textwidth}
  17918. \begin{lstlisting}
  17919. (if (eq? |$e'_1$| (inject #f Boolean))
  17920. (inject #t Boolean) (inject #f Boolean))
  17921. \end{lstlisting}
  17922. \end{minipage}
  17923. \end{tabular}
  17924. \fi}
  17925. {\if\edition\pythonEd\pythonColor
  17926. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17927. \begin{minipage}{0.23\textwidth}
  17928. \begin{lstlisting}
  17929. True
  17930. \end{lstlisting}
  17931. \end{minipage}
  17932. &
  17933. $\Rightarrow$
  17934. &
  17935. \begin{minipage}{0.7\textwidth}
  17936. \begin{lstlisting}
  17937. Inject(True, BoolType())
  17938. \end{lstlisting}
  17939. \end{minipage}
  17940. \\[2ex]\hline
  17941. \begin{minipage}{0.23\textwidth}
  17942. \begin{lstlisting}
  17943. |$e_1$| + |$e_2$|
  17944. \end{lstlisting}
  17945. \end{minipage}
  17946. &
  17947. $\Rightarrow$
  17948. &
  17949. \begin{minipage}{0.7\textwidth}
  17950. \begin{lstlisting}
  17951. Inject(Project(|$e'_1$|, IntType())
  17952. + Project(|$e'_2$|, IntType()),
  17953. IntType())
  17954. \end{lstlisting}
  17955. \end{minipage}
  17956. \\[2ex]\hline
  17957. \begin{minipage}{0.23\textwidth}
  17958. \begin{lstlisting}
  17959. lambda |$x_1 \ldots$|: |$e$|
  17960. \end{lstlisting}
  17961. \end{minipage}
  17962. &
  17963. $\Rightarrow$
  17964. &
  17965. \begin{minipage}{0.7\textwidth}
  17966. \begin{lstlisting}
  17967. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17968. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17969. \end{lstlisting}
  17970. \end{minipage}
  17971. \\[2ex]\hline
  17972. \begin{minipage}{0.23\textwidth}
  17973. \begin{lstlisting}
  17974. |$e_0$|(|$e_1 \ldots e_n$|)
  17975. \end{lstlisting}
  17976. \end{minipage}
  17977. &
  17978. $\Rightarrow$
  17979. &
  17980. \begin{minipage}{0.7\textwidth}
  17981. \begin{lstlisting}
  17982. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17983. AnyType())), |$e'_1, \ldots, e'_n$|)
  17984. \end{lstlisting}
  17985. \end{minipage}
  17986. \\[2ex]\hline
  17987. \begin{minipage}{0.23\textwidth}
  17988. \begin{lstlisting}
  17989. |$e_1$|[|$e_2$|]
  17990. \end{lstlisting}
  17991. \end{minipage}
  17992. &
  17993. $\Rightarrow$
  17994. &
  17995. \begin{minipage}{0.7\textwidth}
  17996. \begin{lstlisting}
  17997. Call(Name('any_tuple_load'),
  17998. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17999. \end{lstlisting}
  18000. \end{minipage}
  18001. %% \begin{minipage}{0.23\textwidth}
  18002. %% \begin{lstlisting}
  18003. %% |$e_2$| if |$e_1$| else |$e_3$|
  18004. %% \end{lstlisting}
  18005. %% \end{minipage}
  18006. %% &
  18007. %% $\Rightarrow$
  18008. %% &
  18009. %% \begin{minipage}{0.7\textwidth}
  18010. %% \begin{lstlisting}
  18011. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18012. %% \end{lstlisting}
  18013. %% \end{minipage}
  18014. %% \\[2ex]\hline
  18015. %% \begin{minipage}{0.23\textwidth}
  18016. %% \begin{lstlisting}
  18017. %% (eq? |$e_1$| |$e_2$|)
  18018. %% \end{lstlisting}
  18019. %% \end{minipage}
  18020. %% &
  18021. %% $\Rightarrow$
  18022. %% &
  18023. %% \begin{minipage}{0.7\textwidth}
  18024. %% \begin{lstlisting}
  18025. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18026. %% \end{lstlisting}
  18027. %% \end{minipage}
  18028. %% \\[2ex]\hline
  18029. %% \begin{minipage}{0.23\textwidth}
  18030. %% \begin{lstlisting}
  18031. %% (not |$e_1$|)
  18032. %% \end{lstlisting}
  18033. %% \end{minipage}
  18034. %% &
  18035. %% $\Rightarrow$
  18036. %% &
  18037. %% \begin{minipage}{0.7\textwidth}
  18038. %% \begin{lstlisting}
  18039. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18040. %% (inject #t Boolean) (inject #f Boolean))
  18041. %% \end{lstlisting}
  18042. %% \end{minipage}
  18043. %% \\[2ex]\hline
  18044. \\\hline
  18045. \end{tabular}
  18046. \fi}
  18047. \end{tcolorbox}
  18048. \caption{Cast insertion.}
  18049. \label{fig:compile-r7-Lany}
  18050. \end{figure}
  18051. \section{Reveal Casts}
  18052. \label{sec:reveal-casts-Lany}
  18053. % TODO: define R'_6
  18054. In the \code{reveal\_casts} pass, we recommend compiling
  18055. \code{Project} into a conditional expression that checks whether the
  18056. value's tag matches the target type; if it does, the value is
  18057. converted to a value of the target type by removing the tag; if it
  18058. does not, the program exits.
  18059. %
  18060. {\if\edition\racketEd
  18061. %
  18062. To perform these actions we need a new primitive operation,
  18063. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18064. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18065. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18066. underlying value from a tagged value. The \code{ValueOf} form
  18067. includes the type for the underlying value that is used by the type
  18068. checker.
  18069. %
  18070. \fi}
  18071. %
  18072. {\if\edition\pythonEd\pythonColor
  18073. %
  18074. To perform these actions we need two new AST classes: \code{TagOf} and
  18075. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18076. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18077. the underlying value from a tagged value. The \code{ValueOf}
  18078. operation includes the type for the underlying value that is used by
  18079. the type checker.
  18080. %
  18081. \fi}
  18082. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18083. \code{Project} can be translated as follows:
  18084. \begin{center}
  18085. \begin{minipage}{1.0\textwidth}
  18086. {\if\edition\racketEd
  18087. \begin{lstlisting}
  18088. (Project |$e$| |$\FType$|)
  18089. |$\Rightarrow$|
  18090. (Let |$\itm{tmp}$| |$e'$|
  18091. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18092. (Int |$\itm{tagof}(\FType)$|)))
  18093. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18094. (Exit)))
  18095. \end{lstlisting}
  18096. \fi}
  18097. {\if\edition\pythonEd\pythonColor
  18098. \begin{lstlisting}
  18099. Project(|$e$|, |$\FType$|)
  18100. |$\Rightarrow$|
  18101. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18102. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18103. [Constant(|$\itm{tagof}(\FType)$|)]),
  18104. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18105. Call(Name('exit'), [])))
  18106. \end{lstlisting}
  18107. \fi}
  18108. \end{minipage}
  18109. \end{center}
  18110. If the target type of the projection is a tuple or function type, then
  18111. there is a bit more work to do. For tuples, check that the length of
  18112. the tuple type matches the length of the tuple. For functions, check
  18113. that the number of parameters in the function type matches the
  18114. function's arity.
  18115. Regarding \code{Inject}, we recommend compiling it to a slightly
  18116. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18117. takes a tag instead of a type.
  18118. \begin{center}
  18119. \begin{minipage}{1.0\textwidth}
  18120. {\if\edition\racketEd
  18121. \begin{lstlisting}
  18122. (Inject |$e$| |$\FType$|)
  18123. |$\Rightarrow$|
  18124. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18125. \end{lstlisting}
  18126. \fi}
  18127. {\if\edition\pythonEd\pythonColor
  18128. \begin{lstlisting}
  18129. Inject(|$e$|, |$\FType$|)
  18130. |$\Rightarrow$|
  18131. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18132. \end{lstlisting}
  18133. \fi}
  18134. \end{minipage}
  18135. \end{center}
  18136. {\if\edition\pythonEd\pythonColor
  18137. %
  18138. The introduction of \code{make\_any} makes it difficult to use
  18139. bidirectional type checking because we no longer have an expected type
  18140. to use for type checking the expression $e'$. Thus, we run into
  18141. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18142. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18143. annotated lambda), that contains its return type and the types of its
  18144. parameters.
  18145. %
  18146. \fi}
  18147. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18148. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18149. translation of \code{Project}.}
  18150. {\if\edition\racketEd
  18151. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18152. combine the projection action with the vector operation. Also, the
  18153. read and write operations allow arbitrary expressions for the index, so
  18154. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18155. cannot guarantee that the index is within bounds. Thus, we insert code
  18156. to perform bounds checking at runtime. The translation for
  18157. \code{any-vector-ref} is as follows, and the other two operations are
  18158. translated in a similar way:
  18159. \begin{center}
  18160. \begin{minipage}{0.95\textwidth}
  18161. \begin{lstlisting}
  18162. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18163. |$\Rightarrow$|
  18164. (Let |$v$| |$e'_1$|
  18165. (Let |$i$| |$e'_2$|
  18166. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18167. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18168. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18169. (Exit))
  18170. (Exit))))
  18171. \end{lstlisting}
  18172. \end{minipage}
  18173. \end{center}
  18174. \fi}
  18175. %
  18176. {\if\edition\pythonEd\pythonColor
  18177. %
  18178. The \code{any\_tuple\_load} operation combines the projection action
  18179. with the load operation. Also, the load operation allows arbitrary
  18180. expressions for the index so the type checker for \LangAny{}
  18181. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index, is
  18182. within bounds. Thus, we insert code to perform bounds checking at
  18183. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18184. \begin{lstlisting}
  18185. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18186. |$\Rightarrow$|
  18187. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18188. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18189. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18190. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18191. Call(Name('exit'), [])),
  18192. Call(Name('exit'), [])))
  18193. \end{lstlisting}
  18194. \fi}
  18195. {\if\edition\pythonEd\pythonColor
  18196. \section{Assignment Conversion}
  18197. \label{sec:convert-assignments-Lany}
  18198. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18199. \code{AnnLambda} AST classes.
  18200. \section{Closure Conversion}
  18201. \label{sec:closure-conversion-Lany}
  18202. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18203. \code{AnnLambda} AST classes.
  18204. \fi}
  18205. \section{Remove Complex Operands}
  18206. \label{sec:rco-Lany}
  18207. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18208. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18209. %
  18210. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18211. complex expressions. Their subexpressions must be atomic.}
  18212. \section{Explicate Control and \LangCAny{}}
  18213. \label{sec:explicate-Lany}
  18214. The output of \code{explicate\_control} is the \LangCAny{} language,
  18215. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18216. %
  18217. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18218. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18219. note that the index argument of \code{vector-ref} and
  18220. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18221. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18222. %
  18223. \python{Update the auxiliary functions \code{explicate\_tail},
  18224. \code{explicate\_effect}, and \code{explicate\_pred} as
  18225. appropriate to handle the new expressions in \LangCAny{}. }
  18226. \newcommand{\CanyASTPython}{
  18227. \begin{array}{lcl}
  18228. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18229. &\MID& \key{TagOf}\LP \Atm \RP
  18230. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18231. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18232. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18233. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18234. \end{array}
  18235. }
  18236. \newcommand{\CanyASTRacket}{
  18237. \begin{array}{lcl}
  18238. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18239. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18240. &\MID& \VALUEOF{\Atm}{\FType} \\
  18241. \Tail &::= & \LP\key{Exit}\RP
  18242. \end{array}
  18243. }
  18244. \begin{figure}[tp]
  18245. \begin{tcolorbox}[colback=white]
  18246. \small
  18247. {\if\edition\racketEd
  18248. \[
  18249. \begin{array}{l}
  18250. \gray{\CvarASTRacket} \\ \hline
  18251. \gray{\CifASTRacket} \\ \hline
  18252. \gray{\CloopASTRacket} \\ \hline
  18253. \gray{\CtupASTRacket} \\ \hline
  18254. \gray{\CfunASTRacket} \\ \hline
  18255. \gray{\ClambdaASTRacket} \\ \hline
  18256. \CanyASTRacket \\
  18257. \begin{array}{lcl}
  18258. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18259. \end{array}
  18260. \end{array}
  18261. \]
  18262. \fi}
  18263. {\if\edition\pythonEd\pythonColor
  18264. \[
  18265. \begin{array}{l}
  18266. \gray{\CifASTPython} \\ \hline
  18267. \gray{\CtupASTPython} \\ \hline
  18268. \gray{\CfunASTPython} \\ \hline
  18269. \gray{\ClambdaASTPython} \\ \hline
  18270. \CanyASTPython \\
  18271. \begin{array}{lcl}
  18272. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18273. \end{array}
  18274. \end{array}
  18275. \]
  18276. \fi}
  18277. \end{tcolorbox}
  18278. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18279. \label{fig:c5-syntax}
  18280. \end{figure}
  18281. \section{Select Instructions}
  18282. \label{sec:select-Lany}
  18283. \index{subject}{select instructions}
  18284. In the \code{select\_instructions} pass, we translate the primitive
  18285. operations on the \ANYTY{} type to x86 instructions that manipulate
  18286. the three tag bits of the tagged value. In the following descriptions,
  18287. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18288. of translating $e$ into an x86 argument:
  18289. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18290. We recommend compiling the
  18291. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18292. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18293. shifts the destination to the left by the number of bits specified by its
  18294. source argument (in this case three, the length of the tag), and it
  18295. preserves the sign of the integer. We use the \key{orq} instruction to
  18296. combine the tag and the value to form the tagged value.
  18297. {\if\edition\racketEd
  18298. \begin{lstlisting}
  18299. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18300. |$\Rightarrow$|
  18301. movq |$e'$|, |\itm{lhs'}|
  18302. salq $3, |\itm{lhs'}|
  18303. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18304. \end{lstlisting}
  18305. \fi}
  18306. %
  18307. {\if\edition\pythonEd\pythonColor
  18308. \begin{lstlisting}
  18309. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18310. |$\Rightarrow$|
  18311. movq |$e'$|, |\itm{lhs'}|
  18312. salq $3, |\itm{lhs'}|
  18313. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18314. \end{lstlisting}
  18315. \fi}
  18316. %
  18317. The instruction selection\index{subject}{instruction selection} for
  18318. tuples and procedures is different because there is no need to shift
  18319. them to the left. The rightmost 3 bits are already zeros, so we simply
  18320. combine the value and the tag using \key{orq}. \\
  18321. %
  18322. {\if\edition\racketEd
  18323. \begin{center}
  18324. \begin{minipage}{\textwidth}
  18325. \begin{lstlisting}
  18326. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18327. |$\Rightarrow$|
  18328. movq |$e'$|, |\itm{lhs'}|
  18329. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18330. \end{lstlisting}
  18331. \end{minipage}
  18332. \end{center}
  18333. \fi}
  18334. %
  18335. {\if\edition\pythonEd\pythonColor
  18336. \begin{lstlisting}
  18337. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18338. |$\Rightarrow$|
  18339. movq |$e'$|, |\itm{lhs'}|
  18340. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18341. \end{lstlisting}
  18342. \fi}
  18343. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18344. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18345. operation extracts the type tag from a value of type \ANYTY{}. The
  18346. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18347. bitwise-and of the value with $111$ ($7$ decimal).
  18348. %
  18349. {\if\edition\racketEd
  18350. \begin{lstlisting}
  18351. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18352. |$\Rightarrow$|
  18353. movq |$e'$|, |\itm{lhs'}|
  18354. andq $7, |\itm{lhs'}|
  18355. \end{lstlisting}
  18356. \fi}
  18357. %
  18358. {\if\edition\pythonEd\pythonColor
  18359. \begin{lstlisting}
  18360. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18361. |$\Rightarrow$|
  18362. movq |$e'$|, |\itm{lhs'}|
  18363. andq $7, |\itm{lhs'}|
  18364. \end{lstlisting}
  18365. \fi}
  18366. \paragraph{\code{ValueOf}}
  18367. The instructions for \key{ValueOf} also differ, depending on whether
  18368. the type $T$ is a pointer (tuple or function) or not (integer or
  18369. Boolean). The following shows the instruction
  18370. selection for integers and
  18371. Booleans, in which we produce an untagged value by shifting it to the
  18372. right by 3 bits:
  18373. %
  18374. {\if\edition\racketEd
  18375. \begin{lstlisting}
  18376. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18377. |$\Rightarrow$|
  18378. movq |$e'$|, |\itm{lhs'}|
  18379. sarq $3, |\itm{lhs'}|
  18380. \end{lstlisting}
  18381. \fi}
  18382. %
  18383. {\if\edition\pythonEd\pythonColor
  18384. \begin{lstlisting}
  18385. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18386. |$\Rightarrow$|
  18387. movq |$e'$|, |\itm{lhs'}|
  18388. sarq $3, |\itm{lhs'}|
  18389. \end{lstlisting}
  18390. \fi}
  18391. %
  18392. In the case for tuples and procedures, we zero out the rightmost 3
  18393. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18394. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18395. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18396. Finally, we apply \code{andq} with the tagged value to get the desired
  18397. result.
  18398. %
  18399. {\if\edition\racketEd
  18400. \begin{lstlisting}
  18401. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18402. |$\Rightarrow$|
  18403. movq $|$-8$|, |\itm{lhs'}|
  18404. andq |$e'$|, |\itm{lhs'}|
  18405. \end{lstlisting}
  18406. \fi}
  18407. %
  18408. {\if\edition\pythonEd\pythonColor
  18409. \begin{lstlisting}
  18410. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18411. |$\Rightarrow$|
  18412. movq $|$-8$|, |\itm{lhs'}|
  18413. andq |$e'$|, |\itm{lhs'}|
  18414. \end{lstlisting}
  18415. \fi}
  18416. %% \paragraph{Type Predicates} We leave it to the reader to
  18417. %% devise a sequence of instructions to implement the type predicates
  18418. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18419. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18420. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18421. operation combines the effect of \code{ValueOf} with accessing the
  18422. length of a tuple from the tag stored at the zero index of the tuple.
  18423. {\if\edition\racketEd
  18424. \begin{lstlisting}
  18425. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18426. |$\Longrightarrow$|
  18427. movq $|$-8$|, %r11
  18428. andq |$e_1'$|, %r11
  18429. movq 0(%r11), %r11
  18430. andq $126, %r11
  18431. sarq $1, %r11
  18432. movq %r11, |$\itm{lhs'}$|
  18433. \end{lstlisting}
  18434. \fi}
  18435. {\if\edition\pythonEd\pythonColor
  18436. \begin{lstlisting}
  18437. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18438. |$\Longrightarrow$|
  18439. movq $|$-8$|, %r11
  18440. andq |$e_1'$|, %r11
  18441. movq 0(%r11), %r11
  18442. andq $126, %r11
  18443. sarq $1, %r11
  18444. movq %r11, |$\itm{lhs'}$|
  18445. \end{lstlisting}
  18446. \fi}
  18447. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18448. This operation combines the effect of \code{ValueOf} with reading an
  18449. element of the tuple (see
  18450. section~\ref{sec:select-instructions-gc}). However, the index may be
  18451. an arbitrary atom, so instead of computing the offset at compile time,
  18452. we must generate instructions to compute the offset at runtime as
  18453. follows. Note the use of the new instruction \code{imulq}.
  18454. \begin{center}
  18455. \begin{minipage}{0.96\textwidth}
  18456. {\if\edition\racketEd
  18457. \begin{lstlisting}
  18458. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18459. |$\Longrightarrow$|
  18460. movq |$\neg 111$|, %r11
  18461. andq |$e_1'$|, %r11
  18462. movq |$e_2'$|, %rax
  18463. addq $1, %rax
  18464. imulq $8, %rax
  18465. addq %rax, %r11
  18466. movq 0(%r11) |$\itm{lhs'}$|
  18467. \end{lstlisting}
  18468. \fi}
  18469. %
  18470. {\if\edition\pythonEd\pythonColor
  18471. \begin{lstlisting}
  18472. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18473. |$\Longrightarrow$|
  18474. movq $|$-8$|, %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. \end{minipage}
  18484. \end{center}
  18485. % $ pacify font lock
  18486. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18487. %% The code generation for
  18488. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18489. %% analogous to the above translation for reading from a tuple.
  18490. \section{Register Allocation for \LangAny{}}
  18491. \label{sec:register-allocation-Lany}
  18492. \index{subject}{register allocation}
  18493. There is an interesting interaction between tagged values and garbage
  18494. collection that has an impact on register allocation. A variable of
  18495. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18496. that needs to be inspected and copied during garbage collection. Thus,
  18497. we need to treat variables of type \ANYTY{} in a similar way to
  18498. variables of tuple type for purposes of register allocation,
  18499. with particular attention to the following:
  18500. \begin{itemize}
  18501. \item If a variable of type \ANYTY{} is live during a function call,
  18502. then it must be spilled. This can be accomplished by changing
  18503. \code{build\_interference} to mark all variables of type \ANYTY{}
  18504. that are live after a \code{callq} to be interfering with all the
  18505. registers.
  18506. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18507. the root stack instead of the normal procedure call stack.
  18508. \end{itemize}
  18509. Another concern regarding the root stack is that the garbage collector
  18510. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18511. tagged value that points to a tuple, and (3) a tagged value that is
  18512. not a tuple. We enable this differentiation by choosing not to use the
  18513. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18514. reserved for identifying plain old pointers to tuples. That way, if
  18515. one of the first three bits is set, then we have a tagged value and
  18516. inspecting the tag can differentiate between tuples ($010$) and the
  18517. other kinds of values.
  18518. %% \begin{exercise}\normalfont
  18519. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18520. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18521. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18522. %% compiler on these new programs and all of your previously created test
  18523. %% programs.
  18524. %% \end{exercise}
  18525. \begin{exercise}\normalfont\normalsize
  18526. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18527. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18528. by removing type annotations. Add five more test programs that
  18529. specifically rely on the language being dynamically typed. That is,
  18530. they should not be legal programs in a statically typed language, but
  18531. nevertheless they should be valid \LangDyn{} programs that run to
  18532. completion without error.
  18533. \end{exercise}
  18534. \begin{figure}[p]
  18535. \begin{tcolorbox}[colback=white]
  18536. {\if\edition\racketEd
  18537. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18538. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18539. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18540. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18541. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18542. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18543. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18544. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18545. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18546. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18547. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18548. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18549. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18550. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18551. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18552. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18553. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18554. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18555. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18556. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18557. \path[->,bend left=15] (Lfun) edge [above] node
  18558. {\ttfamily\footnotesize shrink} (Lfun-2);
  18559. \path[->,bend left=15] (Lfun-2) edge [above] node
  18560. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18561. \path[->,bend left=15] (Lfun-3) edge [above] node
  18562. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18563. \path[->,bend left=15] (Lfun-4) edge [left] node
  18564. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18565. \path[->,bend left=15] (Lfun-5) edge [below] node
  18566. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18567. \path[->,bend left=15] (Lfun-6) edge [below] node
  18568. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18569. \path[->,bend right=15] (Lfun-7) edge [above] node
  18570. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18571. \path[->,bend right=15] (F1-2) edge [right] node
  18572. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18573. \path[->,bend right=15] (F1-3) edge [below] node
  18574. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18575. \path[->,bend right=15] (F1-4) edge [below] node
  18576. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18577. \path[->,bend left=15] (F1-5) edge [above] node
  18578. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18579. \path[->,bend left=10] (F1-6) edge [below] node
  18580. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18581. \path[->,bend left=15] (C3-2) edge [right] node
  18582. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18583. \path[->,bend right=15] (x86-2) edge [right] node
  18584. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18585. \path[->,bend right=15] (x86-2-1) edge [below] node
  18586. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18587. \path[->,bend right=15] (x86-2-2) edge [right] node
  18588. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18589. \path[->,bend left=15] (x86-3) edge [above] node
  18590. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18591. \path[->,bend left=15] (x86-4) edge [right] node
  18592. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18593. \end{tikzpicture}
  18594. \fi}
  18595. {\if\edition\pythonEd\pythonColor
  18596. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18597. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18598. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18599. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18600. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18601. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18602. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18603. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18604. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18605. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18606. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18607. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18608. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18609. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18610. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18611. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18612. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18613. \path[->,bend left=15] (Lfun) edge [above] node
  18614. {\ttfamily\footnotesize shrink} (Lfun-2);
  18615. \path[->,bend left=15] (Lfun-2) edge [above] node
  18616. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18617. \path[->,bend left=15] (Lfun-3) edge [above] node
  18618. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18619. \path[->,bend left=15] (Lfun-4) edge [left] node
  18620. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18621. \path[->,bend left=15] (Lfun-5) edge [below] node
  18622. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18623. \path[->,bend right=15] (Lfun-6) edge [above] node
  18624. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18625. \path[->,bend right=15] (Lfun-7) edge [above] node
  18626. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18627. \path[->,bend right=15] (F1-2) edge [right] node
  18628. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18629. \path[->,bend right=15] (F1-3) edge [below] node
  18630. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18631. \path[->,bend left=15] (F1-5) edge [above] node
  18632. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18633. \path[->,bend left=10] (F1-6) edge [below] node
  18634. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18635. \path[->,bend right=15] (C3-2) edge [right] node
  18636. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18637. \path[->,bend right=15] (x86-2) edge [below] node
  18638. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18639. \path[->,bend right=15] (x86-3) edge [below] node
  18640. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18641. \path[->,bend left=15] (x86-4) edge [above] node
  18642. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18643. \end{tikzpicture}
  18644. \fi}
  18645. \end{tcolorbox}
  18646. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18647. \label{fig:Ldyn-passes}
  18648. \end{figure}
  18649. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18650. for the compilation of \LangDyn{}.
  18651. % Further Reading
  18652. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18653. %% {\if\edition\pythonEd\pythonColor
  18654. %% \chapter{Objects}
  18655. %% \label{ch:Lobject}
  18656. %% \index{subject}{objects}
  18657. %% \index{subject}{classes}
  18658. %% \setcounter{footnote}{0}
  18659. %% \fi}
  18660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18661. \chapter{Gradual Typing}
  18662. \label{ch:Lgrad}
  18663. \index{subject}{gradual typing}
  18664. \setcounter{footnote}{0}
  18665. This chapter studies the language \LangGrad{}, in which the programmer
  18666. can choose between static and dynamic type checking in different parts
  18667. of a program, thereby mixing the statically typed \LangLam{} language
  18668. with the dynamically typed \LangDyn{}. There are several approaches to
  18669. mixing static and dynamic typing, including multilanguage
  18670. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18671. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18672. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18673. programmer controls the amount of static versus dynamic checking by
  18674. adding or removing type annotations on parameters and
  18675. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18676. The definition of the concrete syntax of \LangGrad{} is shown in
  18677. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18678. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18679. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18680. annotations are optional, which is specified in the grammar using the
  18681. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18682. annotations are not optional, but we use the \CANYTY{} type when a type
  18683. annotation is absent.
  18684. %
  18685. Both the type checker and the interpreter for \LangGrad{} require some
  18686. interesting changes to enable gradual typing, which we discuss in the
  18687. next two sections.
  18688. \newcommand{\LgradGrammarRacket}{
  18689. \begin{array}{lcl}
  18690. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18691. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18692. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18693. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18694. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18695. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18696. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18697. \end{array}
  18698. }
  18699. \newcommand{\LgradASTRacket}{
  18700. \begin{array}{lcl}
  18701. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18702. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18703. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18704. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18705. \itm{op} &::=& \code{procedure-arity} \\
  18706. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18707. \end{array}
  18708. }
  18709. \newcommand{\LgradGrammarPython}{
  18710. \begin{array}{lcl}
  18711. \Type &::=& \key{Any}
  18712. \MID \key{int}
  18713. \MID \key{bool}
  18714. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18715. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18716. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18717. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18718. \MID \CARITY{\Exp} \\
  18719. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18720. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18721. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18722. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18723. \end{array}
  18724. }
  18725. \newcommand{\LgradASTPython}{
  18726. \begin{array}{lcl}
  18727. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18728. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18729. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18730. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18731. &\MID& \ARITY{\Exp} \\
  18732. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18733. \MID \RETURN{\Exp} \\
  18734. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18735. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18736. \end{array}
  18737. }
  18738. \begin{figure}[tp]
  18739. \centering
  18740. \begin{tcolorbox}[colback=white]
  18741. \small
  18742. {\if\edition\racketEd
  18743. \[
  18744. \begin{array}{l}
  18745. \gray{\LintGrammarRacket{}} \\ \hline
  18746. \gray{\LvarGrammarRacket{}} \\ \hline
  18747. \gray{\LifGrammarRacket{}} \\ \hline
  18748. \gray{\LwhileGrammarRacket} \\ \hline
  18749. \gray{\LtupGrammarRacket} \\ \hline
  18750. \LgradGrammarRacket \\
  18751. \begin{array}{lcl}
  18752. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18753. \end{array}
  18754. \end{array}
  18755. \]
  18756. \fi}
  18757. {\if\edition\pythonEd\pythonColor
  18758. \[
  18759. \begin{array}{l}
  18760. \gray{\LintGrammarPython{}} \\ \hline
  18761. \gray{\LvarGrammarPython{}} \\ \hline
  18762. \gray{\LifGrammarPython{}} \\ \hline
  18763. \gray{\LwhileGrammarPython} \\ \hline
  18764. \gray{\LtupGrammarPython} \\ \hline
  18765. \LgradGrammarPython \\
  18766. \begin{array}{lcl}
  18767. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18768. \end{array}
  18769. \end{array}
  18770. \]
  18771. \fi}
  18772. \end{tcolorbox}
  18773. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18774. \label{fig:Lgrad-concrete-syntax}
  18775. \end{figure}
  18776. \begin{figure}[tp]
  18777. \centering
  18778. \begin{tcolorbox}[colback=white]
  18779. \small
  18780. {\if\edition\racketEd
  18781. \[
  18782. \begin{array}{l}
  18783. \gray{\LintOpAST} \\ \hline
  18784. \gray{\LvarASTRacket{}} \\ \hline
  18785. \gray{\LifASTRacket{}} \\ \hline
  18786. \gray{\LwhileASTRacket{}} \\ \hline
  18787. \gray{\LtupASTRacket{}} \\ \hline
  18788. \LgradASTRacket \\
  18789. \begin{array}{lcl}
  18790. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18791. \end{array}
  18792. \end{array}
  18793. \]
  18794. \fi}
  18795. {\if\edition\pythonEd\pythonColor
  18796. \[
  18797. \begin{array}{l}
  18798. \gray{\LintASTPython{}} \\ \hline
  18799. \gray{\LvarASTPython{}} \\ \hline
  18800. \gray{\LifASTPython{}} \\ \hline
  18801. \gray{\LwhileASTPython} \\ \hline
  18802. \gray{\LtupASTPython} \\ \hline
  18803. \LgradASTPython \\
  18804. \begin{array}{lcl}
  18805. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18806. \end{array}
  18807. \end{array}
  18808. \]
  18809. \fi}
  18810. \end{tcolorbox}
  18811. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18812. \label{fig:Lgrad-syntax}
  18813. \end{figure}
  18814. % TODO: more road map -Jeremy
  18815. %\clearpage
  18816. \section{Type Checking \LangGrad{}}
  18817. \label{sec:gradual-type-check}
  18818. We begin by discussing the type checking of a partially typed variant
  18819. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18820. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18821. statically typed, so there is nothing special happening there with
  18822. respect to type checking. On the other hand, the \code{inc} function
  18823. does not have type annotations, so the type checker assigns the type
  18824. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18825. \code{+} operator inside \code{inc}. It expects both arguments to have
  18826. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18827. a gradually typed language, such differences are allowed so long as
  18828. the types are \emph{consistent}; that is, they are equal except in
  18829. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18830. is consistent with every other type. Figure~\ref{fig:consistent}
  18831. shows the definition of the
  18832. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18833. %
  18834. So the type checker allows the \code{+} operator to be applied
  18835. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18836. %
  18837. Next consider the call to the \code{map} function shown in
  18838. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18839. tuple. The \code{inc} function has type
  18840. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18841. but parameter \code{f} of \code{map} has type
  18842. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18843. The type checker for \LangGrad{} accepts this call because the two types are
  18844. consistent.
  18845. \begin{figure}[btp]
  18846. % gradual_test_9.rkt
  18847. \begin{tcolorbox}[colback=white]
  18848. {\if\edition\racketEd
  18849. \begin{lstlisting}
  18850. (define (map [f : (Integer -> Integer)]
  18851. [v : (Vector Integer Integer)])
  18852. : (Vector Integer Integer)
  18853. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18854. (define (inc x) (+ x 1))
  18855. (vector-ref (map inc (vector 0 41)) 1)
  18856. \end{lstlisting}
  18857. \fi}
  18858. {\if\edition\pythonEd\pythonColor
  18859. \begin{lstlisting}
  18860. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18861. return f(v[0]), f(v[1])
  18862. def inc(x):
  18863. return x + 1
  18864. t = map(inc, (0, 41))
  18865. print(t[1])
  18866. \end{lstlisting}
  18867. \fi}
  18868. \end{tcolorbox}
  18869. \caption{A partially typed version of the \code{map} example.}
  18870. \label{fig:gradual-map}
  18871. \end{figure}
  18872. \begin{figure}[tbp]
  18873. \begin{tcolorbox}[colback=white]
  18874. {\if\edition\racketEd
  18875. \begin{lstlisting}
  18876. (define/public (consistent? t1 t2)
  18877. (match* (t1 t2)
  18878. [('Integer 'Integer) #t]
  18879. [('Boolean 'Boolean) #t]
  18880. [('Void 'Void) #t]
  18881. [('Any t2) #t]
  18882. [(t1 'Any) #t]
  18883. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18884. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18885. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18886. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18887. (consistent? rt1 rt2))]
  18888. [(other wise) #f]))
  18889. \end{lstlisting}
  18890. \fi}
  18891. {\if\edition\pythonEd\pythonColor
  18892. \begin{lstlisting}
  18893. def consistent(self, t1, t2):
  18894. match (t1, t2):
  18895. case (AnyType(), _):
  18896. return True
  18897. case (_, AnyType()):
  18898. return True
  18899. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18900. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18901. case (TupleType(ts1), TupleType(ts2)):
  18902. return all(map(self.consistent, ts1, ts2))
  18903. case (_, _):
  18904. return t1 == t2
  18905. \end{lstlisting}
  18906. \fi}
  18907. \end{tcolorbox}
  18908. \caption{The consistency method on types.}
  18909. \label{fig:consistent}
  18910. \end{figure}
  18911. It is also helpful to consider how gradual typing handles programs with an
  18912. error, such as applying \code{map} to a function that sometimes
  18913. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18914. type checker for \LangGrad{} accepts this program because the type of
  18915. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18916. \code{map}; that is,
  18917. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18918. is consistent with
  18919. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18920. One might say that a gradual type checker is optimistic in that it
  18921. accepts programs that might execute without a runtime type error.
  18922. %
  18923. The definition of the type checker for \LangGrad{} is shown in
  18924. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18925. and \ref{fig:type-check-Lgradual-3}.
  18926. %% \begin{figure}[tp]
  18927. %% \centering
  18928. %% \fbox{
  18929. %% \begin{minipage}{0.96\textwidth}
  18930. %% \small
  18931. %% \[
  18932. %% \begin{array}{lcl}
  18933. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18934. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18935. %% \end{array}
  18936. %% \]
  18937. %% \end{minipage}
  18938. %% }
  18939. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18940. %% \label{fig:Lgrad-prime-syntax}
  18941. %% \end{figure}
  18942. \begin{figure}[tbp]
  18943. \begin{tcolorbox}[colback=white]
  18944. {\if\edition\racketEd
  18945. \begin{lstlisting}
  18946. (define (map [f : (Integer -> Integer)]
  18947. [v : (Vector Integer Integer)])
  18948. : (Vector Integer Integer)
  18949. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18950. (define (inc x) (+ x 1))
  18951. (define (true) #t)
  18952. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18953. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18954. \end{lstlisting}
  18955. \fi}
  18956. {\if\edition\pythonEd\pythonColor
  18957. \begin{lstlisting}
  18958. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18959. return f(v[0]), f(v[1])
  18960. def inc(x):
  18961. return x + 1
  18962. def true():
  18963. return True
  18964. def maybe_inc(x):
  18965. return inc(x) if input_int() == 0 else true()
  18966. t = map(maybe_inc, (0, 41))
  18967. print(t[1])
  18968. \end{lstlisting}
  18969. \fi}
  18970. \end{tcolorbox}
  18971. \caption{A variant of the \code{map} example with an error.}
  18972. \label{fig:map-maybe_inc}
  18973. \end{figure}
  18974. Running this program with input \code{1} triggers an
  18975. error when the \code{maybe\_inc} function returns
  18976. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18977. performs checking at runtime to ensure the integrity of the static
  18978. types, such as the
  18979. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18980. annotation on
  18981. parameter \code{f} of \code{map}.
  18982. Here we give a preview of how the runtime checking is accomplished;
  18983. the following sections provide the details.
  18984. The runtime checking is carried out by a new \code{Cast} AST node that
  18985. is generated in a new pass named \code{cast\_insert}. The output of
  18986. \code{cast\_insert} is a program in the \LangCast{} language, which
  18987. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18988. %
  18989. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18990. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18991. inserted every time the type checker encounters two types that are
  18992. consistent but not equal. In the \code{inc} function, \code{x} is
  18993. cast to \INTTY{} and the result of the \code{+} is cast to
  18994. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18995. is cast from
  18996. \racket{\code{(Any -> Any)}}
  18997. \python{\code{Callable[[Any], Any]}}
  18998. to
  18999. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19000. %
  19001. In the next section we see how to interpret the \code{Cast} node.
  19002. \begin{figure}[btp]
  19003. \begin{tcolorbox}[colback=white]
  19004. {\if\edition\racketEd
  19005. \begin{lstlisting}
  19006. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19007. : (Vector Integer Integer)
  19008. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19009. (define (inc [x : Any]) : Any
  19010. (cast (+ (cast x Any Integer) 1) Integer Any))
  19011. (define (true) : Any (cast #t Boolean Any))
  19012. (define (maybe_inc [x : Any]) : Any
  19013. (if (eq? 0 (read)) (inc x) (true)))
  19014. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19015. (vector 0 41)) 0)
  19016. \end{lstlisting}
  19017. \fi}
  19018. {\if\edition\pythonEd\pythonColor
  19019. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19020. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19021. return f(v[0]), f(v[1])
  19022. def inc(x : Any) -> Any:
  19023. return Cast(Cast(x, Any, int) + 1, int, Any)
  19024. def true() -> Any:
  19025. return Cast(True, bool, Any)
  19026. def maybe_inc(x : Any) -> Any:
  19027. return inc(x) if input_int() == 0 else true()
  19028. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19029. (0, 41))
  19030. print(t[1])
  19031. \end{lstlisting}
  19032. \fi}
  19033. \end{tcolorbox}
  19034. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19035. and \code{maybe\_inc} example.}
  19036. \label{fig:map-cast}
  19037. \end{figure}
  19038. {\if\edition\pythonEd\pythonColor
  19039. \begin{figure}[tbp]
  19040. \begin{tcolorbox}[colback=white]
  19041. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19042. class TypeCheckLgrad(TypeCheckLlambda):
  19043. def type_check_exp(self, e, env) -> Type:
  19044. match e:
  19045. case Name(id):
  19046. return env[id]
  19047. case Constant(value) if isinstance(value, bool):
  19048. return BoolType()
  19049. case Constant(value) if isinstance(value, int):
  19050. return IntType()
  19051. case Call(Name('input_int'), []):
  19052. return IntType()
  19053. case BinOp(left, op, right):
  19054. left_type = self.type_check_exp(left, env)
  19055. self.check_consistent(left_type, IntType(), left)
  19056. right_type = self.type_check_exp(right, env)
  19057. self.check_consistent(right_type, IntType(), right)
  19058. return IntType()
  19059. case IfExp(test, body, orelse):
  19060. test_t = self.type_check_exp(test, env)
  19061. self.check_consistent(test_t, BoolType(), test)
  19062. body_t = self.type_check_exp(body, env)
  19063. orelse_t = self.type_check_exp(orelse, env)
  19064. self.check_consistent(body_t, orelse_t, e)
  19065. return self.join_types(body_t, orelse_t)
  19066. case Call(func, args):
  19067. func_t = self.type_check_exp(func, env)
  19068. args_t = [self.type_check_exp(arg, env) for arg in args]
  19069. match func_t:
  19070. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  19071. for (arg_t, param_t) in zip(args_t, params_t):
  19072. self.check_consistent(param_t, arg_t, e)
  19073. return return_t
  19074. case AnyType():
  19075. return AnyType()
  19076. case _:
  19077. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  19078. ...
  19079. case _:
  19080. raise Exception('type_check_exp: unexpected ' + repr(e))
  19081. \end{lstlisting}
  19082. \end{tcolorbox}
  19083. \caption{Type checking expressions in the \LangGrad{} language.}
  19084. \label{fig:type-check-Lgradual-1}
  19085. \end{figure}
  19086. \begin{figure}[tbp]
  19087. \begin{tcolorbox}[colback=white]
  19088. \begin{lstlisting}
  19089. def check_exp(self, e, expected_ty, env):
  19090. match e:
  19091. case Lambda(params, body):
  19092. match expected_ty:
  19093. case FunctionType(params_t, return_t):
  19094. new_env = env.copy().update(zip(params, params_t))
  19095. e.has_type = expected_ty
  19096. body_ty = self.type_check_exp(body, new_env)
  19097. self.check_consistent(body_ty, return_t)
  19098. case AnyType():
  19099. new_env = env.copy().update((p, AnyType()) for p in params)
  19100. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19101. body_ty = self.type_check_exp(body, new_env)
  19102. case _:
  19103. raise Exception('lambda is not of type ' + str(expected_ty))
  19104. case _:
  19105. e_ty = self.type_check_exp(e, env)
  19106. self.check_consistent(e_ty, expected_ty, e)
  19107. \end{lstlisting}
  19108. \end{tcolorbox}
  19109. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19110. \label{fig:type-check-Lgradual-2}
  19111. \end{figure}
  19112. \begin{figure}[tbp]
  19113. \begin{tcolorbox}[colback=white]
  19114. \begin{lstlisting}
  19115. def type_check_stmt(self, s, env, return_type):
  19116. match s:
  19117. case Assign([Name(id)], value):
  19118. value_ty = self.type_check_exp(value, env)
  19119. if id in env:
  19120. self.check_consistent(env[id], value_ty, value)
  19121. else:
  19122. env[id] = value_ty
  19123. ...
  19124. case _:
  19125. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19126. def type_check_stmts(self, ss, env, return_type):
  19127. for s in ss:
  19128. self.type_check_stmt(s, env, return_type)
  19129. \end{lstlisting}
  19130. \end{tcolorbox}
  19131. \caption{Type checking statements in the \LangGrad{} language.}
  19132. \label{fig:type-check-Lgradual-3}
  19133. \end{figure}
  19134. \begin{figure}[tbp]
  19135. \begin{tcolorbox}[colback=white]
  19136. \begin{lstlisting}
  19137. def join_types(self, t1, t2):
  19138. match (t1, t2):
  19139. case (AnyType(), _):
  19140. return t2
  19141. case (_, AnyType()):
  19142. return t1
  19143. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19144. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19145. self.join_types(rt1,rt2))
  19146. case (TupleType(ts1), TupleType(ts2)):
  19147. return TupleType(list(map(self.join_types, ts1, ts2)))
  19148. case (_, _):
  19149. return t1
  19150. def check_consistent(self, t1, t2, e):
  19151. if not self.consistent(t1, t2):
  19152. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19153. + repr(t2) + ' in ' + repr(e))
  19154. \end{lstlisting}
  19155. \end{tcolorbox}
  19156. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19157. \label{fig:type-check-Lgradual-aux}
  19158. \end{figure}
  19159. \fi}
  19160. {\if\edition\racketEd
  19161. \begin{figure}[tbp]
  19162. \begin{tcolorbox}[colback=white]
  19163. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19164. (define/override (type-check-exp env)
  19165. (lambda (e)
  19166. (define recur (type-check-exp env))
  19167. (match e
  19168. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19169. (define-values (new-es ts)
  19170. (for/lists (exprs types) ([e es])
  19171. (recur e)))
  19172. (define t-ret (type-check-op op ts e))
  19173. (values (Prim op new-es) t-ret)]
  19174. [(Prim 'eq? (list e1 e2))
  19175. (define-values (e1^ t1) (recur e1))
  19176. (define-values (e2^ t2) (recur e2))
  19177. (check-consistent? t1 t2 e)
  19178. (define T (meet t1 t2))
  19179. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19180. [(Prim 'and (list e1 e2))
  19181. (recur (If e1 e2 (Bool #f)))]
  19182. [(Prim 'or (list e1 e2))
  19183. (define tmp (gensym 'tmp))
  19184. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19185. [(If e1 e2 e3)
  19186. (define-values (e1^ T1) (recur e1))
  19187. (define-values (e2^ T2) (recur e2))
  19188. (define-values (e3^ T3) (recur e3))
  19189. (check-consistent? T1 'Boolean e)
  19190. (check-consistent? T2 T3 e)
  19191. (define Tif (meet T2 T3))
  19192. (values (If e1^ e2^ e3^) Tif)]
  19193. [(SetBang x e1)
  19194. (define-values (e1^ T1) (recur e1))
  19195. (define varT (dict-ref env x))
  19196. (check-consistent? T1 varT e)
  19197. (values (SetBang x e1^) 'Void)]
  19198. [(WhileLoop e1 e2)
  19199. (define-values (e1^ T1) (recur e1))
  19200. (check-consistent? T1 'Boolean e)
  19201. (define-values (e2^ T2) ((type-check-exp env) e2))
  19202. (values (WhileLoop e1^ e2^) 'Void)]
  19203. [(Prim 'vector-length (list e1))
  19204. (define-values (e1^ t) (recur e1))
  19205. (match t
  19206. [`(Vector ,ts ...)
  19207. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19208. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19209. \end{lstlisting}
  19210. \end{tcolorbox}
  19211. \caption{Type checker for the \LangGrad{} language, part 1.}
  19212. \label{fig:type-check-Lgradual-1}
  19213. \end{figure}
  19214. \begin{figure}[tbp]
  19215. \begin{tcolorbox}[colback=white]
  19216. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19217. [(Prim 'vector-ref (list e1 e2))
  19218. (define-values (e1^ t1) (recur e1))
  19219. (define-values (e2^ t2) (recur e2))
  19220. (check-consistent? t2 'Integer e)
  19221. (match t1
  19222. [`(Vector ,ts ...)
  19223. (match e2^
  19224. [(Int i)
  19225. (unless (and (0 . <= . i) (i . < . (length ts)))
  19226. (error 'type-check "invalid index ~a in ~a" i e))
  19227. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19228. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19229. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19230. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19231. [(Prim 'vector-set! (list e1 e2 e3) )
  19232. (define-values (e1^ t1) (recur e1))
  19233. (define-values (e2^ t2) (recur e2))
  19234. (define-values (e3^ t3) (recur e3))
  19235. (check-consistent? t2 'Integer e)
  19236. (match t1
  19237. [`(Vector ,ts ...)
  19238. (match e2^
  19239. [(Int i)
  19240. (unless (and (0 . <= . i) (i . < . (length ts)))
  19241. (error 'type-check "invalid index ~a in ~a" i e))
  19242. (check-consistent? (list-ref ts i) t3 e)
  19243. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19244. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19245. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19246. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19247. [(Apply e1 e2s)
  19248. (define-values (e1^ T1) (recur e1))
  19249. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19250. (match T1
  19251. [`(,T1ps ... -> ,T1rt)
  19252. (for ([T2 T2s] [Tp T1ps])
  19253. (check-consistent? T2 Tp e))
  19254. (values (Apply e1^ e2s^) T1rt)]
  19255. [`Any (values (Apply e1^ e2s^) 'Any)]
  19256. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19257. [(Lambda params Tr e1)
  19258. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19259. (match p
  19260. [`[,x : ,T] (values x T)]
  19261. [(? symbol? x) (values x 'Any)])))
  19262. (define-values (e1^ T1)
  19263. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19264. (check-consistent? Tr T1 e)
  19265. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19266. `(,@Ts -> ,Tr))]
  19267. [else ((super type-check-exp env) e)]
  19268. )))
  19269. \end{lstlisting}
  19270. \end{tcolorbox}
  19271. \caption{Type checker for the \LangGrad{} language, part 2.}
  19272. \label{fig:type-check-Lgradual-2}
  19273. \end{figure}
  19274. \begin{figure}[tbp]
  19275. \begin{tcolorbox}[colback=white]
  19276. \begin{lstlisting}
  19277. (define/override (type-check-def env)
  19278. (lambda (e)
  19279. (match e
  19280. [(Def f params rt info body)
  19281. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19282. (match p
  19283. [`[,x : ,T] (values x T)]
  19284. [(? symbol? x) (values x 'Any)])))
  19285. (define new-env (append (map cons xs ps) env))
  19286. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19287. (check-consistent? ty^ rt e)
  19288. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19289. [else (error 'type-check "ill-formed function definition ~a" e)]
  19290. )))
  19291. (define/override (type-check-program e)
  19292. (match e
  19293. [(Program info body)
  19294. (define-values (body^ ty) ((type-check-exp '()) body))
  19295. (check-consistent? ty 'Integer e)
  19296. (ProgramDefsExp info '() body^)]
  19297. [(ProgramDefsExp info ds body)
  19298. (define new-env (for/list ([d ds])
  19299. (cons (Def-name d) (fun-def-type d))))
  19300. (define ds^ (for/list ([d ds])
  19301. ((type-check-def new-env) d)))
  19302. (define-values (body^ ty) ((type-check-exp new-env) body))
  19303. (check-consistent? ty 'Integer e)
  19304. (ProgramDefsExp info ds^ body^)]
  19305. [else (super type-check-program e)]))
  19306. \end{lstlisting}
  19307. \end{tcolorbox}
  19308. \caption{Type checker for the \LangGrad{} language, part 3.}
  19309. \label{fig:type-check-Lgradual-3}
  19310. \end{figure}
  19311. \begin{figure}[tbp]
  19312. \begin{tcolorbox}[colback=white]
  19313. \begin{lstlisting}
  19314. (define/public (join t1 t2)
  19315. (match* (t1 t2)
  19316. [('Integer 'Integer) 'Integer]
  19317. [('Boolean 'Boolean) 'Boolean]
  19318. [('Void 'Void) 'Void]
  19319. [('Any t2) t2]
  19320. [(t1 'Any) t1]
  19321. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19322. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19323. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19324. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19325. -> ,(join rt1 rt2))]))
  19326. (define/public (meet t1 t2)
  19327. (match* (t1 t2)
  19328. [('Integer 'Integer) 'Integer]
  19329. [('Boolean 'Boolean) 'Boolean]
  19330. [('Void 'Void) 'Void]
  19331. [('Any t2) 'Any]
  19332. [(t1 'Any) 'Any]
  19333. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19334. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19335. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19336. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19337. -> ,(meet rt1 rt2))]))
  19338. (define/public (check-consistent? t1 t2 e)
  19339. (unless (consistent? t1 t2)
  19340. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19341. (define explicit-prim-ops
  19342. (set-union
  19343. (type-predicates)
  19344. (set 'procedure-arity 'eq? 'not 'and 'or
  19345. 'vector 'vector-length 'vector-ref 'vector-set!
  19346. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19347. (define/override (fun-def-type d)
  19348. (match d
  19349. [(Def f params rt info body)
  19350. (define ps
  19351. (for/list ([p params])
  19352. (match p
  19353. [`[,x : ,T] T]
  19354. [(? symbol?) 'Any]
  19355. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19356. `(,@ps -> ,rt)]
  19357. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19358. \end{lstlisting}
  19359. \end{tcolorbox}
  19360. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19361. \label{fig:type-check-Lgradual-aux}
  19362. \end{figure}
  19363. \fi}
  19364. \clearpage
  19365. \section{Interpreting \LangCast{}}
  19366. \label{sec:interp-casts}
  19367. The runtime behavior of casts involving simple types such as
  19368. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19369. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19370. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19371. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19372. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19373. operator, by checking the value's tag and either retrieving
  19374. the underlying integer or signaling an error if the tag is not the
  19375. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19376. %
  19377. Things get more interesting with casts involving
  19378. \racket{function and tuple types}\python{function, tuple, and array types}.
  19379. Consider the cast of the function \code{maybe\_inc} from
  19380. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19381. to
  19382. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19383. shown in figure~\ref{fig:map-maybe_inc}.
  19384. When the \code{maybe\_inc} function flows through
  19385. this cast at runtime, we don't know whether it will return
  19386. an integer, because that depends on the input from the user.
  19387. The \LangCast{} interpreter therefore delays the checking
  19388. of the cast until the function is applied. To do so it
  19389. wraps \code{maybe\_inc} in a new function that casts its parameter
  19390. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19391. casts the return value from \CANYTY{} to \INTTY{}.
  19392. {\if\edition\pythonEd\pythonColor
  19393. %
  19394. There are further complications regarding casts on mutable data,
  19395. such as the \code{list} type introduced in
  19396. the challenge assignment of section~\ref{sec:arrays}.
  19397. %
  19398. \fi}
  19399. %
  19400. Consider the example presented in figure~\ref{fig:map-bang} that
  19401. defines a partially typed version of \code{map} whose parameter
  19402. \code{v} has type
  19403. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19404. and that updates \code{v} in place
  19405. instead of returning a new tuple. We name this function
  19406. \code{map\_inplace}. We apply \code{map\_inplace} to
  19407. \racket{a tuple}\python{an array} of integers, so the type checker
  19408. inserts a cast from
  19409. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19410. to
  19411. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19412. A naive way for the \LangCast{} interpreter to cast between
  19413. \racket{tuple}\python{array} types would be to build a new
  19414. \racket{tuple}\python{array} whose elements are the result
  19415. of casting each of the original elements to the appropriate target
  19416. type. However, this approach is not valid for mutable data structures.
  19417. In the example of figure~\ref{fig:map-bang},
  19418. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19419. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19420. the original one.
  19421. \begin{figure}[tbp]
  19422. \begin{tcolorbox}[colback=white]
  19423. % gradual_test_11.rkt
  19424. {\if\edition\racketEd
  19425. \begin{lstlisting}
  19426. (define (map_inplace [f : (Any -> Any)]
  19427. [v : (Vector Any Any)]) : Void
  19428. (begin
  19429. (vector-set! v 0 (f (vector-ref v 0)))
  19430. (vector-set! v 1 (f (vector-ref v 1)))))
  19431. (define (inc x) (+ x 1))
  19432. (let ([v (vector 0 41)])
  19433. (begin (map_inplace inc v) (vector-ref v 1)))
  19434. \end{lstlisting}
  19435. \fi}
  19436. {\if\edition\pythonEd\pythonColor
  19437. \begin{lstlisting}
  19438. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19439. i = 0
  19440. while i != len(v):
  19441. v[i] = f(v[i])
  19442. i = i + 1
  19443. def inc(x : int) -> int:
  19444. return x + 1
  19445. v = [0, 41]
  19446. map_inplace(inc, v)
  19447. print(v[1])
  19448. \end{lstlisting}
  19449. \fi}
  19450. \end{tcolorbox}
  19451. \caption{An example involving casts on arrays.}
  19452. \label{fig:map-bang}
  19453. \end{figure}
  19454. Instead the interpreter needs to create a new kind of value, a
  19455. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19456. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19457. and then applies a
  19458. cast to the resulting value. On a write, the proxy casts the argument
  19459. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19460. \racket{
  19461. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19462. \code{0} from \INTTY{} to \CANYTY{}.
  19463. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19464. from \CANYTY{} to \INTTY{}.
  19465. }
  19466. \python{
  19467. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19468. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19469. For the subscript on the left of the assignment,
  19470. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19471. }
  19472. Finally we consider casts between the \CANYTY{} type and higher-order types
  19473. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19474. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19475. have a type annotation, so it is given type \CANYTY{}. In the call to
  19476. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19477. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19478. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19479. \code{Inject}, but that doesn't work because
  19480. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19481. a flat type. Instead, we must first cast to
  19482. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19483. and then inject to \CANYTY{}.
  19484. \begin{figure}[tbp]
  19485. \begin{tcolorbox}[colback=white]
  19486. {\if\edition\racketEd
  19487. \begin{lstlisting}
  19488. (define (map_inplace [f : (Any -> Any)] v) : Void
  19489. (begin
  19490. (vector-set! v 0 (f (vector-ref v 0)))
  19491. (vector-set! v 1 (f (vector-ref v 1)))))
  19492. (define (inc x) (+ x 1))
  19493. (let ([v (vector 0 41)])
  19494. (begin (map_inplace inc v) (vector-ref v 1)))
  19495. \end{lstlisting}
  19496. \fi}
  19497. {\if\edition\pythonEd\pythonColor
  19498. \begin{lstlisting}
  19499. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19500. i = 0
  19501. while i != len(v):
  19502. v[i] = f(v[i])
  19503. i = i + 1
  19504. def inc(x):
  19505. return x + 1
  19506. v = [0, 41]
  19507. map_inplace(inc, v)
  19508. print(v[1])
  19509. \end{lstlisting}
  19510. \fi}
  19511. \end{tcolorbox}
  19512. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19513. \label{fig:map-any}
  19514. \end{figure}
  19515. \begin{figure}[tbp]
  19516. \begin{tcolorbox}[colback=white]
  19517. {\if\edition\racketEd
  19518. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19519. (define/public (apply_cast v s t)
  19520. (match* (s t)
  19521. [(t1 t2) #:when (equal? t1 t2) v]
  19522. [('Any t2)
  19523. (match t2
  19524. [`(,ts ... -> ,rt)
  19525. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19526. (define v^ (apply-project v any->any))
  19527. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19528. [`(Vector ,ts ...)
  19529. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19530. (define v^ (apply-project v vec-any))
  19531. (apply_cast v^ vec-any `(Vector ,@ts))]
  19532. [else (apply-project v t2)])]
  19533. [(t1 'Any)
  19534. (match t1
  19535. [`(,ts ... -> ,rt)
  19536. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19537. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19538. (apply-inject v^ (any-tag any->any))]
  19539. [`(Vector ,ts ...)
  19540. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19541. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19542. (apply-inject v^ (any-tag vec-any))]
  19543. [else (apply-inject v (any-tag t1))])]
  19544. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19545. (define x (gensym 'x))
  19546. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19547. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19548. (define cast-writes
  19549. (for/list ([t1 ts1] [t2 ts2])
  19550. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19551. `(vector-proxy ,(vector v (apply vector cast-reads)
  19552. (apply vector cast-writes)))]
  19553. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19554. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19555. `(function ,xs ,(Cast
  19556. (Apply (Value v)
  19557. (for/list ([x xs][t1 ts1][t2 ts2])
  19558. (Cast (Var x) t2 t1)))
  19559. rt1 rt2) ())]
  19560. ))
  19561. \end{lstlisting}
  19562. \fi}
  19563. {\if\edition\pythonEd\pythonColor
  19564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19565. def apply_cast(self, value, src, tgt):
  19566. match (src, tgt):
  19567. case (AnyType(), FunctionType(ps2, rt2)):
  19568. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19569. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19570. case (AnyType(), TupleType(ts2)):
  19571. anytup = TupleType([AnyType() for t1 in ts2])
  19572. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19573. case (AnyType(), ListType(t2)):
  19574. anylist = ListType([AnyType() for t1 in ts2])
  19575. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19576. case (AnyType(), AnyType()):
  19577. return value
  19578. case (AnyType(), _):
  19579. return self.apply_project(value, tgt)
  19580. case (FunctionType(ps1,rt1), AnyType()):
  19581. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19582. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19583. case (TupleType(ts1), AnyType()):
  19584. anytup = TupleType([AnyType() for t1 in ts1])
  19585. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19586. case (ListType(t1), AnyType()):
  19587. anylist = ListType(AnyType())
  19588. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19589. case (_, AnyType()):
  19590. return self.apply_inject(value, src)
  19591. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19592. params = [generate_name('x') for p in ps2]
  19593. args = [Cast(Name(x), t2, t1)
  19594. for (x,t1,t2) in zip(params, ps1, ps2)]
  19595. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19596. return Function('cast', params, [Return(body)], {})
  19597. case (TupleType(ts1), TupleType(ts2)):
  19598. x = generate_name('x')
  19599. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19600. for (t1,t2) in zip(ts1,ts2)]
  19601. return ProxiedTuple(value, reads)
  19602. case (ListType(t1), ListType(t2)):
  19603. x = generate_name('x')
  19604. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19605. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19606. return ProxiedList(value, read, write)
  19607. case (t1, t2) if t1 == t2:
  19608. return value
  19609. case (t1, t2):
  19610. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19611. def apply_inject(self, value, src):
  19612. return Tagged(value, self.type_to_tag(src))
  19613. def apply_project(self, value, tgt):
  19614. match value:
  19615. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19616. return val
  19617. case _:
  19618. raise Exception('apply_project, unexpected ' + repr(value))
  19619. \end{lstlisting}
  19620. \fi}
  19621. \end{tcolorbox}
  19622. \caption{The \code{apply\_cast} auxiliary method.}
  19623. \label{fig:apply_cast}
  19624. \end{figure}
  19625. The \LangCast{} interpreter uses an auxiliary function named
  19626. \code{apply\_cast} to cast a value from a source type to a target type,
  19627. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19628. the kinds of casts that we've discussed in this section.
  19629. %
  19630. The definition of the interpreter for \LangCast{} is shown in
  19631. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19632. dispatching to \code{apply\_cast}.
  19633. \racket{To handle the addition of tuple
  19634. proxies, we update the tuple primitives in \code{interp-op} using the
  19635. functions given in figure~\ref{fig:guarded-tuple}.}
  19636. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19637. \begin{figure}[tbp]
  19638. \begin{tcolorbox}[colback=white]
  19639. {\if\edition\racketEd
  19640. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19641. (define interp-Lcast-class
  19642. (class interp-Llambda-class
  19643. (super-new)
  19644. (inherit apply-fun apply-inject apply-project)
  19645. (define/override (interp-op op)
  19646. (match op
  19647. ['vector-length guarded-vector-length]
  19648. ['vector-ref guarded-vector-ref]
  19649. ['vector-set! guarded-vector-set!]
  19650. ['any-vector-ref (lambda (v i)
  19651. (match v [`(tagged ,v^ ,tg)
  19652. (guarded-vector-ref v^ i)]))]
  19653. ['any-vector-set! (lambda (v i a)
  19654. (match v [`(tagged ,v^ ,tg)
  19655. (guarded-vector-set! v^ i a)]))]
  19656. ['any-vector-length (lambda (v)
  19657. (match v [`(tagged ,v^ ,tg)
  19658. (guarded-vector-length v^)]))]
  19659. [else (super interp-op op)]
  19660. ))
  19661. (define/override ((interp-exp env) e)
  19662. (define (recur e) ((interp-exp env) e))
  19663. (match e
  19664. [(Value v) v]
  19665. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19666. [else ((super interp-exp env) e)]))
  19667. ))
  19668. (define (interp-Lcast p)
  19669. (send (new interp-Lcast-class) interp-program p))
  19670. \end{lstlisting}
  19671. \fi}
  19672. {\if\edition\pythonEd\pythonColor
  19673. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19674. class InterpLcast(InterpLany):
  19675. def interp_exp(self, e, env):
  19676. match e:
  19677. case Cast(value, src, tgt):
  19678. v = self.interp_exp(value, env)
  19679. return self.apply_cast(v, src, tgt)
  19680. case ValueExp(value):
  19681. return value
  19682. ...
  19683. case _:
  19684. return super().interp_exp(e, env)
  19685. \end{lstlisting}
  19686. \fi}
  19687. \end{tcolorbox}
  19688. \caption{The interpreter for \LangCast{}.}
  19689. \label{fig:interp-Lcast}
  19690. \end{figure}
  19691. {\if\edition\racketEd
  19692. \begin{figure}[tbp]
  19693. \begin{tcolorbox}[colback=white]
  19694. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19695. (define (guarded-vector-ref vec i)
  19696. (match vec
  19697. [`(vector-proxy ,proxy)
  19698. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19699. (define rd (vector-ref (vector-ref proxy 1) i))
  19700. (apply-fun rd (list val) 'guarded-vector-ref)]
  19701. [else (vector-ref vec i)]))
  19702. (define (guarded-vector-set! vec i arg)
  19703. (match vec
  19704. [`(vector-proxy ,proxy)
  19705. (define wr (vector-ref (vector-ref proxy 2) i))
  19706. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19707. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19708. [else (vector-set! vec i arg)]))
  19709. (define (guarded-vector-length vec)
  19710. (match vec
  19711. [`(vector-proxy ,proxy)
  19712. (guarded-vector-length (vector-ref proxy 0))]
  19713. [else (vector-length vec)]))
  19714. \end{lstlisting}
  19715. %% {\if\edition\pythonEd\pythonColor
  19716. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19717. %% UNDER CONSTRUCTION
  19718. %% \end{lstlisting}
  19719. %% \fi}
  19720. \end{tcolorbox}
  19721. \caption{The \code{guarded-vector} auxiliary functions.}
  19722. \label{fig:guarded-tuple}
  19723. \end{figure}
  19724. \fi}
  19725. {\if\edition\pythonEd\pythonColor
  19726. \section{Overload Resolution}
  19727. \label{sec:gradual-resolution}
  19728. Recall that when we added support for arrays in
  19729. section~\ref{sec:arrays}, the syntax for the array operations were the
  19730. same as for tuple operations (for example, accessing an element and
  19731. getting the length). So we performed overload resolution, with a pass
  19732. named \code{resolve}, to separate the array and tuple operations. In
  19733. particular, we introduced the primitives \code{array\_load},
  19734. \code{array\_store}, and \code{array\_len}.
  19735. For gradual typing, we further overload these operators to work on
  19736. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19737. updated with new cases for the \CANYTY{} type, translating the element
  19738. access and length operations to the primitives \code{any\_load},
  19739. \code{any\_store}, and \code{any\_len}.
  19740. \fi}
  19741. \section{Cast Insertion}
  19742. \label{sec:gradual-insert-casts}
  19743. In our discussion of type checking of \LangGrad{}, we mentioned how
  19744. the runtime aspect of type checking is carried out by the \code{Cast}
  19745. AST node, which is added to the program by a new pass named
  19746. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19747. language. We now discuss the details of this pass.
  19748. The \code{cast\_insert} pass is closely related to the type checker
  19749. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19750. In particular, the type checker allows implicit casts between
  19751. consistent types. The job of the \code{cast\_insert} pass is to make
  19752. those casts explicit. It does so by inserting
  19753. \code{Cast} nodes into the AST.
  19754. %
  19755. For the most part, the implicit casts occur in places where the type
  19756. checker checks two types for consistency. Consider the case for
  19757. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19758. checker requires that the type of the left operand is consistent with
  19759. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19760. \code{Cast} around the left operand, converting from its type to
  19761. \INTTY{}. The story is similar for the right operand. It is not always
  19762. necessary to insert a cast, for example, if the left operand already has type
  19763. \INTTY{} then there is no need for a \code{Cast}.
  19764. Some of the implicit casts are not as straightforward. One such case
  19765. arises with the
  19766. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19767. see that the type checker requires that the two branches have
  19768. consistent types and that type of the conditional expression is the
  19769. meet of the branches' types. In the target language \LangCast{}, both
  19770. branches will need to have the same type, and that type
  19771. will be the type of the conditional expression. Thus, each branch requires
  19772. a \code{Cast} to convert from its type to the meet of the branches' types.
  19773. The case for the function call exhibits another interesting situation. If
  19774. the function expression is of type \CANYTY{}, then it needs to be cast
  19775. to a function type so that it can be used in a function call in
  19776. \LangCast{}. Which function type should it be cast to? The parameter
  19777. and return types are unknown, so we can simply use \CANYTY{} for all
  19778. of them. Furthermore, in \LangCast{} the argument types will need to
  19779. exactly match the parameter types, so we must cast all the arguments
  19780. to type \CANYTY{} (if they are not already of that type).
  19781. {\if\edition\racketEd
  19782. %
  19783. Likewise, the cases for the tuple operators \code{vector-length},
  19784. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19785. where the tuple expression is of type \CANYTY{}. Instead of
  19786. handling these situations with casts, we recommend translating
  19787. the special-purpose variants of the tuple operators that handle
  19788. tuples of type \CANYTY{}: \code{any-vector-length},
  19789. \code{any-vector-ref}, and \code{any-vector-set!}.
  19790. %
  19791. \fi}
  19792. \section{Lower Casts}
  19793. \label{sec:lower_casts}
  19794. The next step in the journey toward x86 is the \code{lower\_casts}
  19795. pass that translates the casts in \LangCast{} to the lower-level
  19796. \code{Inject} and \code{Project} operators and new operators for
  19797. proxies, extending the \LangLam{} language to \LangProxy{}.
  19798. The \LangProxy{} language can also be described as an extension of
  19799. \LangAny{}, with the addition of proxies. We recommend creating an
  19800. auxiliary function named \code{lower\_cast} that takes an expression
  19801. (in \LangCast{}), a source type, and a target type and translates it
  19802. to an expression in \LangProxy{}.
  19803. The \code{lower\_cast} function can follow a code structure similar to
  19804. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19805. the interpreter for \LangCast{}, because it must handle the same cases
  19806. as \code{apply\_cast} and it needs to mimic the behavior of
  19807. \code{apply\_cast}. The most interesting cases concern
  19808. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19809. {\if\edition\racketEd
  19810. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19811. type to another tuple type is accomplished by creating a proxy that
  19812. intercepts the operations on the underlying tuple. Here we make the
  19813. creation of the proxy explicit with the \code{vector-proxy} AST
  19814. node. It takes three arguments: the first is an expression for the
  19815. tuple, the second is a tuple of functions for casting an element that is
  19816. being read from the tuple, and the third is a tuple of functions for
  19817. casting an element that is being written to the array. You can create
  19818. the functions for reading and writing using lambda expressions. Also,
  19819. as we show in the next section, we need to differentiate these tuples
  19820. of functions from the user-created ones, so we recommend using a new
  19821. AST node named \code{raw-vector} instead of \code{vector}.
  19822. %
  19823. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19824. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19825. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19826. \fi}
  19827. {\if\edition\pythonEd\pythonColor
  19828. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19829. type to another array type is accomplished by creating a proxy that
  19830. intercepts the operations on the underlying array. Here we make the
  19831. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19832. takes fives arguments: the first is an expression for the array, the
  19833. second is a function for casting an element that is being read from
  19834. the array, the third is a function for casting an element that is
  19835. being written to the array, the fourth is the type of the underlying
  19836. array, and the fifth is the type of the proxied array. You can create
  19837. the functions for reading and writing using lambda expressions.
  19838. A cast between two tuple types can be handled in a similar manner. We
  19839. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19840. immutable, so there is no need for a function to cast the value during
  19841. a write. Because there is a separate element type for each slot in
  19842. the tuple, we need more than one function for casting during a read:
  19843. we need a tuple of functions.
  19844. %
  19845. Also, as we show in the next section, we need to differentiate these
  19846. tuples from the user-created ones, so we recommend using a new AST
  19847. node named \code{RawTuple} instead of \code{Tuple} to create the
  19848. tuples of functions.
  19849. %
  19850. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19851. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19852. that involves casting an array of integers to an array of \CANYTY{}.
  19853. \fi}
  19854. \begin{figure}[tbp]
  19855. \begin{tcolorbox}[colback=white]
  19856. {\if\edition\racketEd
  19857. \begin{lstlisting}
  19858. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19859. (begin
  19860. (vector-set! v 0 (f (vector-ref v 0)))
  19861. (vector-set! v 1 (f (vector-ref v 1)))))
  19862. (define (inc [x : Any]) : Any
  19863. (inject (+ (project x Integer) 1) Integer))
  19864. (let ([v (vector 0 41)])
  19865. (begin
  19866. (map_inplace inc (vector-proxy v
  19867. (raw-vector (lambda: ([x9 : Integer]) : Any
  19868. (inject x9 Integer))
  19869. (lambda: ([x9 : Integer]) : Any
  19870. (inject x9 Integer)))
  19871. (raw-vector (lambda: ([x9 : Any]) : Integer
  19872. (project x9 Integer))
  19873. (lambda: ([x9 : Any]) : Integer
  19874. (project x9 Integer)))))
  19875. (vector-ref v 1)))
  19876. \end{lstlisting}
  19877. \fi}
  19878. {\if\edition\pythonEd\pythonColor
  19879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19880. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19881. i = 0
  19882. while i != array_len(v):
  19883. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19884. i = (i + 1)
  19885. def inc(x : int) -> int:
  19886. return (x + 1)
  19887. def main() -> int:
  19888. v = [0, 41]
  19889. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19890. print(array_load(v, 1))
  19891. return 0
  19892. \end{lstlisting}
  19893. \fi}
  19894. \end{tcolorbox}
  19895. \caption{Output of \code{lower\_casts} on the example shown in
  19896. figure~\ref{fig:map-bang}.}
  19897. \label{fig:map-bang-lower-cast}
  19898. \end{figure}
  19899. A cast from one function type to another function type is accomplished
  19900. by generating a \code{lambda} whose parameter and return types match
  19901. the target function type. The body of the \code{lambda} should cast
  19902. the parameters from the target type to the source type. (Yes,
  19903. backward! Functions are contravariant\index{subject}{contravariant}
  19904. in the parameters.) Afterward, call the underlying function and then
  19905. cast the result from the source return type to the target return type.
  19906. Figure~\ref{fig:map-lower-cast} shows the output of the
  19907. \code{lower\_casts} pass on the \code{map} example give in
  19908. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19909. call to \code{map} is wrapped in a \code{lambda}.
  19910. \begin{figure}[tbp]
  19911. \begin{tcolorbox}[colback=white]
  19912. {\if\edition\racketEd
  19913. \begin{lstlisting}
  19914. (define (map [f : (Integer -> Integer)]
  19915. [v : (Vector Integer Integer)])
  19916. : (Vector Integer Integer)
  19917. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19918. (define (inc [x : Any]) : Any
  19919. (inject (+ (project x Integer) 1) Integer))
  19920. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19921. (project (inc (inject x9 Integer)) Integer))
  19922. (vector 0 41)) 1)
  19923. \end{lstlisting}
  19924. \fi}
  19925. {\if\edition\pythonEd\pythonColor
  19926. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19927. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19928. return (f(v[0]), f(v[1]),)
  19929. def inc(x : any) -> any:
  19930. return inject((project(x, int) + 1), int)
  19931. def main() -> int:
  19932. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19933. print(t[1])
  19934. return 0
  19935. \end{lstlisting}
  19936. \fi}
  19937. \end{tcolorbox}
  19938. \caption{Output of \code{lower\_casts} on the example shown in
  19939. figure~\ref{fig:gradual-map}.}
  19940. \label{fig:map-lower-cast}
  19941. \end{figure}
  19942. \section{Differentiate Proxies}
  19943. \label{sec:differentiate-proxies}
  19944. So far, the responsibility of differentiating tuples and tuple proxies
  19945. has been the job of the interpreter.
  19946. %
  19947. \racket{For example, the interpreter for \LangCast{} implements
  19948. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19949. figure~\ref{fig:guarded-tuple}.}
  19950. %
  19951. In the \code{differentiate\_proxies} pass we shift this responsibility
  19952. to the generated code.
  19953. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19954. we used the type \TUPLETYPENAME{} for both
  19955. real tuples and tuple proxies.
  19956. \python{Similarly, we use the type \code{list} for both arrays and
  19957. array proxies.}
  19958. In \LangPVec{} we return the
  19959. \TUPLETYPENAME{} type to its original
  19960. meaning, as the type of just tuples, and we introduce a new type,
  19961. \PTUPLETYNAME{}, whose values
  19962. can be either real tuples or tuple
  19963. proxies.
  19964. %
  19965. {\if\edition\pythonEd\pythonColor
  19966. Likewise, we return the
  19967. \ARRAYTYPENAME{} type to its original
  19968. meaning, as the type of arrays, and we introduce a new type,
  19969. \PARRAYTYNAME{}, whose values
  19970. can be either arrays or array proxies.
  19971. These new types come with a suite of new primitive operations.
  19972. \fi}
  19973. {\if\edition\racketEd
  19974. A tuple proxy is represented by a tuple containing three things: (1) the
  19975. underlying tuple, (2) a tuple of functions for casting elements that
  19976. are read from the tuple, and (3) a tuple of functions for casting
  19977. values to be written to the tuple. So, we define the following
  19978. abbreviation for the type of a tuple proxy:
  19979. \[
  19980. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19981. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19982. \]
  19983. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19984. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19985. %
  19986. Next we describe each of the new primitive operations.
  19987. \begin{description}
  19988. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19989. (\key{PVector} $T \ldots$)]\ \\
  19990. %
  19991. This operation brands a vector as a value of the \code{PVector} type.
  19992. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19993. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19994. %
  19995. This operation brands a vector proxy as value of the \code{PVector} type.
  19996. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19997. \BOOLTY{}] \ \\
  19998. %
  19999. This returns true if the value is a tuple proxy and false if it is a
  20000. real tuple.
  20001. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20002. (\key{Vector} $T \ldots$)]\ \\
  20003. %
  20004. Assuming that the input is a tuple, this operation returns the
  20005. tuple.
  20006. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20007. $\to$ \BOOLTY{}]\ \\
  20008. %
  20009. Given a tuple proxy, this operation returns the length of the tuple.
  20010. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20011. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  20012. %
  20013. Given a tuple proxy, this operation returns the $i$th element of the
  20014. tuple.
  20015. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20016. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20017. Given a tuple proxy, this operation writes a value to the $i$th element
  20018. of the tuple.
  20019. \end{description}
  20020. \fi}
  20021. {\if\edition\pythonEd\pythonColor
  20022. %
  20023. A tuple proxy is represented by a tuple containing (1) the underlying
  20024. tuple and (2) a tuple of functions for casting elements that are read
  20025. from the tuple. The \LangPVec{} language includes the following AST
  20026. classes and primitive functions.
  20027. \begin{description}
  20028. \item[\code{InjectTuple}] \ \\
  20029. %
  20030. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20031. \item[\code{InjectTupleProxy}]\ \\
  20032. %
  20033. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20034. \item[\code{is\_tuple\_proxy}]\ \\
  20035. %
  20036. This primitive returns true if the value is a tuple proxy and false
  20037. if it is a tuple.
  20038. \item[\code{project\_tuple}]\ \\
  20039. %
  20040. Converts a tuple that is branded as \PTUPLETYNAME{}
  20041. back to a tuple.
  20042. \item[\code{proxy\_tuple\_len}]\ \\
  20043. %
  20044. Given a tuple proxy, returns the length of the underlying tuple.
  20045. \item[\code{proxy\_tuple\_load}]\ \\
  20046. %
  20047. Given a tuple proxy, returns the $i$th element of the underlying
  20048. tuple.
  20049. \end{description}
  20050. An array proxy is represented by a tuple containing (1) the underlying
  20051. array, (2) a function for casting elements that are read from the
  20052. array, and (3) a function for casting elements that are written to the
  20053. array. The \LangPVec{} language includes the following AST classes
  20054. and primitive functions.
  20055. \begin{description}
  20056. \item[\code{InjectList}]\ \\
  20057. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20058. \item[\code{InjectListProxy}]\ \\
  20059. %
  20060. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20061. \item[\code{is\_array\_proxy}]\ \\
  20062. %
  20063. Returns true if the value is an array proxy and false if it is an
  20064. array.
  20065. \item[\code{project\_array}]\ \\
  20066. %
  20067. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20068. array.
  20069. \item[\code{proxy\_array\_len}]\ \\
  20070. %
  20071. Given an array proxy, returns the length of the underlying array.
  20072. \item[\code{proxy\_array\_load}]\ \\
  20073. %
  20074. Given an array proxy, returns the $i$th element of the underlying
  20075. array.
  20076. \item[\code{proxy\_array\_store}]\ \\
  20077. %
  20078. Given an array proxy, writes a value to the $i$th element of the
  20079. underlying array.
  20080. \end{description}
  20081. \fi}
  20082. Now we discuss the translation that differentiates tuples and arrays
  20083. from proxies. First, every type annotation in the program is
  20084. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20085. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20086. places. For example, we wrap every tuple creation with an
  20087. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20088. %
  20089. {\if\edition\racketEd
  20090. \begin{minipage}{0.96\textwidth}
  20091. \begin{lstlisting}
  20092. (vector |$e_1 \ldots e_n$|)
  20093. |$\Rightarrow$|
  20094. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20095. \end{lstlisting}
  20096. \end{minipage}
  20097. \fi}
  20098. {\if\edition\pythonEd\pythonColor
  20099. \begin{lstlisting}
  20100. Tuple(|$e_1, \ldots, e_n$|)
  20101. |$\Rightarrow$|
  20102. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20103. \end{lstlisting}
  20104. \fi}
  20105. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20106. AST node that we introduced in the previous
  20107. section does not get injected.
  20108. {\if\edition\racketEd
  20109. \begin{lstlisting}
  20110. (raw-vector |$e_1 \ldots e_n$|)
  20111. |$\Rightarrow$|
  20112. (vector |$e'_1 \ldots e'_n$|)
  20113. \end{lstlisting}
  20114. \fi}
  20115. {\if\edition\pythonEd\pythonColor
  20116. \begin{lstlisting}
  20117. RawTuple(|$e_1, \ldots, e_n$|)
  20118. |$\Rightarrow$|
  20119. Tuple(|$e'_1, \ldots, e'_n$|)
  20120. \end{lstlisting}
  20121. \fi}
  20122. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20123. translates as follows:
  20124. %
  20125. {\if\edition\racketEd
  20126. \begin{lstlisting}
  20127. (vector-proxy |$e_1~e_2~e_3$|)
  20128. |$\Rightarrow$|
  20129. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20130. \end{lstlisting}
  20131. \fi}
  20132. {\if\edition\pythonEd\pythonColor
  20133. \begin{lstlisting}
  20134. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20135. |$\Rightarrow$|
  20136. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20137. \end{lstlisting}
  20138. \fi}
  20139. We translate the element access operations into conditional
  20140. expressions that check whether the value is a proxy and then dispatch
  20141. to either the appropriate proxy tuple operation or the regular tuple
  20142. operation.
  20143. {\if\edition\racketEd
  20144. \begin{lstlisting}
  20145. (vector-ref |$e_1$| |$i$|)
  20146. |$\Rightarrow$|
  20147. (let ([|$v~e_1$|])
  20148. (if (proxy? |$v$|)
  20149. (proxy-vector-ref |$v$| |$i$|)
  20150. (vector-ref (project-vector |$v$|) |$i$|)
  20151. \end{lstlisting}
  20152. \fi}
  20153. %
  20154. Note that in the branch for a tuple, we must apply
  20155. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20156. from the tuple.
  20157. The translation of array operations is similar to the ones for tuples.
  20158. \section{Reveal Casts}
  20159. \label{sec:reveal-casts-gradual}
  20160. {\if\edition\racketEd
  20161. Recall that the \code{reveal\_casts} pass
  20162. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20163. \code{Inject} and \code{Project} into lower-level operations.
  20164. %
  20165. In particular, \code{Project} turns into a conditional expression that
  20166. inspects the tag and retrieves the underlying value. Here we need to
  20167. augment the translation of \code{Project} to handle the situation in which
  20168. the target type is \code{PVector}. Instead of using
  20169. \code{vector-length} we need to use \code{proxy-vector-length}.
  20170. \begin{lstlisting}
  20171. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20172. |$\Rightarrow$|
  20173. (let |$\itm{tmp}$| |$e'$|
  20174. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20175. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20176. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20177. (exit)))
  20178. \end{lstlisting}
  20179. \fi}
  20180. %
  20181. {\if\edition\pythonEd\pythonColor
  20182. Recall that the $\itm{tagof}$ function determines the bits used to
  20183. identify values of different types, and it is used in the \code{reveal\_casts}
  20184. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20185. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  20186. decimal), just like the tuple and array types.
  20187. \fi}
  20188. %
  20189. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20190. \section{Closure Conversion}
  20191. \label{sec:closure-conversion-gradual}
  20192. The auxiliary function that translates type annotations needs to be
  20193. updated to handle the \PTUPLETYNAME{}
  20194. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20195. %
  20196. Otherwise, the only other changes are adding cases that copy the new
  20197. AST nodes.
  20198. \section{Select Instructions}
  20199. \label{sec:select-instructions-gradual}
  20200. \index{subject}{select instructions}
  20201. Recall that the \code{select\_instructions} pass is responsible for
  20202. lowering the primitive operations into x86 instructions. So, we need
  20203. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20204. to x86. To do so, the first question we need to answer is how to
  20205. differentiate between tuple and tuple proxies\python{, and likewise for
  20206. arrays and array proxies}. We need just one bit to accomplish this;
  20207. we use the bit in position $63$ of the 64-bit tag at the front of
  20208. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20209. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20210. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20211. it that way.
  20212. {\if\edition\racketEd
  20213. \begin{lstlisting}
  20214. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20215. |$\Rightarrow$|
  20216. movq |$e'_1$|, |$\itm{lhs'}$|
  20217. \end{lstlisting}
  20218. \fi}
  20219. {\if\edition\pythonEd\pythonColor
  20220. \begin{lstlisting}
  20221. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20222. |$\Rightarrow$|
  20223. movq |$e'_1$|, |$\itm{lhs'}$|
  20224. \end{lstlisting}
  20225. \fi}
  20226. \python{The translation for \code{InjectList} is also a move instruction.}
  20227. \noindent On the other hand,
  20228. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20229. $63$ to $1$.
  20230. %
  20231. {\if\edition\racketEd
  20232. \begin{lstlisting}
  20233. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20234. |$\Rightarrow$|
  20235. movq |$e'_1$|, %r11
  20236. movq |$(1 << 63)$|, %rax
  20237. orq 0(%r11), %rax
  20238. movq %rax, 0(%r11)
  20239. movq %r11, |$\itm{lhs'}$|
  20240. \end{lstlisting}
  20241. \fi}
  20242. {\if\edition\pythonEd\pythonColor
  20243. \begin{lstlisting}
  20244. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20245. |$\Rightarrow$|
  20246. movq |$e'_1$|, %r11
  20247. movq |$(1 << 63)$|, %rax
  20248. orq 0(%r11), %rax
  20249. movq %rax, 0(%r11)
  20250. movq %r11, |$\itm{lhs'}$|
  20251. \end{lstlisting}
  20252. \fi}
  20253. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20254. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20255. The \racket{\code{proxy?} operation consumes}%
  20256. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20257. consume}
  20258. the information so carefully stashed away by the injections. It
  20259. isolates bit $63$ to tell whether the value is a proxy.
  20260. %
  20261. {\if\edition\racketEd
  20262. \begin{lstlisting}
  20263. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20264. |$\Rightarrow$|
  20265. movq |$e_1'$|, %r11
  20266. movq 0(%r11), %rax
  20267. sarq $63, %rax
  20268. andq $1, %rax
  20269. movq %rax, |$\itm{lhs'}$|
  20270. \end{lstlisting}
  20271. \fi}%
  20272. %
  20273. {\if\edition\pythonEd\pythonColor
  20274. \begin{lstlisting}
  20275. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20276. |$\Rightarrow$|
  20277. movq |$e_1'$|, %r11
  20278. movq 0(%r11), %rax
  20279. sarq $63, %rax
  20280. andq $1, %rax
  20281. movq %rax, |$\itm{lhs'}$|
  20282. \end{lstlisting}
  20283. \fi}%
  20284. %
  20285. The \racket{\code{project-vector} operation is}
  20286. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20287. straightforward to translate, so we leave that to the reader.
  20288. Regarding the element access operations for tuples\python{ and arrays}, the
  20289. runtime provides procedures that implement them (they are recursive
  20290. functions!), so here we simply need to translate these tuple
  20291. operations into the appropriate function call. For example, here is
  20292. the translation for
  20293. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20294. {\if\edition\racketEd
  20295. \begin{minipage}{0.96\textwidth}
  20296. \begin{lstlisting}
  20297. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20298. |$\Rightarrow$|
  20299. movq |$e_1'$|, %rdi
  20300. movq |$e_2'$|, %rsi
  20301. callq proxy_vector_ref
  20302. movq %rax, |$\itm{lhs'}$|
  20303. \end{lstlisting}
  20304. \end{minipage}
  20305. \fi}
  20306. {\if\edition\pythonEd\pythonColor
  20307. \begin{lstlisting}
  20308. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20309. |$\Rightarrow$|
  20310. movq |$e_1'$|, %rdi
  20311. movq |$e_2'$|, %rsi
  20312. callq proxy_vector_ref
  20313. movq %rax, |$\itm{lhs'}$|
  20314. \end{lstlisting}
  20315. \fi}
  20316. {\if\edition\pythonEd\pythonColor
  20317. % TODO: revisit the names vecof for python -Jeremy
  20318. We translate
  20319. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20320. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20321. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20322. \fi}
  20323. We have another batch of operations to deal with: those for the
  20324. \CANYTY{} type. Recall that we generate an
  20325. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20326. there is a element access on something of type \CANYTY{}, and
  20327. similarly for
  20328. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20329. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20330. section~\ref{sec:select-Lany} we selected instructions for these
  20331. operations on the basis of the idea that the underlying value was a tuple or
  20332. array. But in the current setting, the underlying value is of type
  20333. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20334. functions to deal with this:
  20335. \code{proxy\_vector\_ref},
  20336. \code{proxy\_vector\_set}, and
  20337. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20338. to determine whether the value is a proxy, and then
  20339. dispatches to the the appropriate code.
  20340. %
  20341. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20342. can be translated as follows.
  20343. We begin by projecting the underlying value out of the tagged value and
  20344. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20345. {\if\edition\racketEd
  20346. \begin{lstlisting}
  20347. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20348. |$\Rightarrow$|
  20349. movq |$\neg 111$|, %rdi
  20350. andq |$e_1'$|, %rdi
  20351. movq |$e_2'$|, %rsi
  20352. callq proxy_vector_ref
  20353. movq %rax, |$\itm{lhs'}$|
  20354. \end{lstlisting}
  20355. \fi}
  20356. {\if\edition\pythonEd\pythonColor
  20357. \begin{lstlisting}
  20358. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20359. |$\Rightarrow$|
  20360. movq |$\neg 111$|, %rdi
  20361. andq |$e_1'$|, %rdi
  20362. movq |$e_2'$|, %rsi
  20363. callq proxy_vector_ref
  20364. movq %rax, |$\itm{lhs'}$|
  20365. \end{lstlisting}
  20366. \fi}
  20367. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20368. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20369. are translated in a similar way. Alternatively, you could generate
  20370. instructions to open-code
  20371. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20372. and \code{proxy\_vector\_length} functions.
  20373. \begin{exercise}\normalfont\normalsize
  20374. Implement a compiler for the gradually typed \LangGrad{} language by
  20375. extending and adapting your compiler for \LangLam{}. Create ten new
  20376. partially typed test programs. In addition to testing with these
  20377. new programs, test your compiler on all the tests for \LangLam{}
  20378. and for \LangDyn{}.
  20379. %
  20380. \racket{Sometimes you may get a type-checking error on the
  20381. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20382. the \CANYTY{} type around each subexpression that has caused a type
  20383. error. Although \LangDyn{} does not have explicit casts, you can
  20384. induce one by wrapping the subexpression \code{e} with a call to
  20385. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20386. %
  20387. \python{Sometimes you may get a type-checking error on the
  20388. \LangDyn{} programs, but you can adapt them by inserting a
  20389. temporary variable of type \CANYTY{} that is initialized with the
  20390. troublesome expression.}
  20391. \end{exercise}
  20392. \begin{figure}[t]
  20393. \begin{tcolorbox}[colback=white]
  20394. {\if\edition\racketEd
  20395. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20396. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20397. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20398. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20399. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20400. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20401. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20402. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20403. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20404. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20405. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20406. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20407. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20408. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20409. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20410. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20411. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20412. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20413. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20414. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20415. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20416. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20417. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20418. \path[->,bend left=15] (Lgradual) edge [above] node
  20419. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20420. \path[->,bend left=15] (Lgradual2) edge [above] node
  20421. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20422. \path[->,bend left=15] (Lgradual3) edge [above] node
  20423. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20424. \path[->,bend left=15] (Lgradual4) edge [left] node
  20425. {\ttfamily\footnotesize shrink} (Lgradualr);
  20426. \path[->,bend left=15] (Lgradualr) edge [above] node
  20427. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20428. \path[->,bend right=15] (Lgradualp) edge [above] node
  20429. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20430. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20431. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20432. \path[->,bend right=15] (Llambdapp) edge [above] node
  20433. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20434. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20435. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20436. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20437. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20438. \path[->,bend left=15] (F1-2) edge [above] node
  20439. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20440. \path[->,bend left=15] (F1-3) edge [left] node
  20441. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20442. \path[->,bend left=15] (F1-4) edge [below] node
  20443. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20444. \path[->,bend right=15] (F1-5) edge [above] node
  20445. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20446. \path[->,bend right=15] (F1-6) edge [above] node
  20447. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20448. \path[->,bend right=15] (C3-2) edge [right] node
  20449. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20450. \path[->,bend right=15] (x86-2) edge [right] node
  20451. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20452. \path[->,bend right=15] (x86-2-1) edge [below] node
  20453. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20454. \path[->,bend right=15] (x86-2-2) edge [right] node
  20455. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20456. \path[->,bend left=15] (x86-3) edge [above] node
  20457. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20458. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20459. \end{tikzpicture}
  20460. \fi}
  20461. {\if\edition\pythonEd\pythonColor
  20462. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20463. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20464. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20465. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20466. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20467. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20468. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20469. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20470. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20471. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20472. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20473. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20474. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20475. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20476. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20477. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20478. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20479. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20480. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20481. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20482. \path[->,bend left=15] (Lgradual) edge [above] node
  20483. {\ttfamily\footnotesize shrink} (Lgradual2);
  20484. \path[->,bend left=15] (Lgradual2) edge [above] node
  20485. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20486. \path[->,bend left=15] (Lgradual3) edge [above] node
  20487. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20488. \path[->,bend left=15] (Lgradual4) edge [left] node
  20489. {\ttfamily\footnotesize resolve} (Lgradualr);
  20490. \path[->,bend left=15] (Lgradualr) edge [below] node
  20491. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20492. \path[->,bend right=15] (Lgradualp) edge [above] node
  20493. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20494. \path[->,bend right=15] (Llambdapp) edge [above] node
  20495. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20496. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20497. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20498. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20499. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20500. \path[->,bend left=15] (F1-1) edge [above] node
  20501. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20502. \path[->,bend left=15] (F1-2) edge [above] node
  20503. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20504. \path[->,bend left=15] (F1-3) edge [right] node
  20505. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20506. \path[->,bend right=15] (F1-5) edge [above] node
  20507. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20508. \path[->,bend right=15] (F1-6) edge [above] node
  20509. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20510. \path[->,bend right=15] (C3-2) edge [right] node
  20511. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20512. \path[->,bend right=15] (x86-2) edge [below] node
  20513. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20514. \path[->,bend right=15] (x86-3) edge [below] node
  20515. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20516. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20517. \end{tikzpicture}
  20518. \fi}
  20519. \end{tcolorbox}
  20520. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20521. \label{fig:Lgradual-passes}
  20522. \end{figure}
  20523. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20524. needed for the compilation of \LangGrad{}.
  20525. \section{Further Reading}
  20526. This chapter just scratches the surface of gradual typing. The basic
  20527. approach described here is missing two key ingredients that one would
  20528. want in a implementation of gradual typing: blame
  20529. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20530. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20531. problem addressed by blame tracking is that when a cast on a
  20532. higher-order value fails, it often does so at a point in the program
  20533. that is far removed from the original cast. Blame tracking is a
  20534. technique for propagating extra information through casts and proxies
  20535. so that when a cast fails, the error message can point back to the
  20536. original location of the cast in the source program.
  20537. The problem addressed by space-efficient casts also relates to
  20538. higher-order casts. It turns out that in partially typed programs, a
  20539. function or tuple can flow through a great many casts at runtime. With
  20540. the approach described in this chapter, each cast adds another
  20541. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20542. considerable space, but it also makes the function calls and tuple
  20543. operations slow. For example, a partially typed version of quicksort
  20544. could, in the worst case, build a chain of proxies of length $O(n)$
  20545. around the tuple, changing the overall time complexity of the
  20546. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20547. solution to this problem by representing casts using the coercion
  20548. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20549. long chains of proxies by compressing them into a concise normal
  20550. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20551. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20552. the Grift compiler:
  20553. \begin{center}
  20554. \url{https://github.com/Gradual-Typing/Grift}
  20555. \end{center}
  20556. There are also interesting interactions between gradual typing and
  20557. other language features, such as generics, information-flow types, and
  20558. type inference, to name a few. We recommend to the reader the
  20559. online gradual typing bibliography for more material:
  20560. \begin{center}
  20561. \url{http://samth.github.io/gradual-typing-bib/}
  20562. \end{center}
  20563. % TODO: challenge problem:
  20564. % type analysis and type specialization?
  20565. % coercions?
  20566. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20567. \chapter{Generics}
  20568. \label{ch:Lpoly}
  20569. \setcounter{footnote}{0}
  20570. This chapter studies the compilation of
  20571. generics\index{subject}{generics} (aka parametric
  20572. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20573. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20574. enable programmers to make code more reusable by parameterizing
  20575. functions and data structures with respect to the types on which they
  20576. operate. For example, figure~\ref{fig:map-poly} revisits the
  20577. \code{map} example and this time gives it a more fitting type. This
  20578. \code{map} function is parameterized with respect to the element type
  20579. of the tuple. The type of \code{map} is the following generic type
  20580. specified by the \code{All} type with parameter \code{T}:
  20581. {\if\edition\racketEd
  20582. \begin{lstlisting}
  20583. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20584. \end{lstlisting}
  20585. \fi}
  20586. {\if\edition\pythonEd\pythonColor
  20587. \begin{lstlisting}
  20588. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20589. \end{lstlisting}
  20590. \fi}
  20591. %
  20592. The idea is that \code{map} can be used at \emph{all} choices of a
  20593. type for parameter \code{T}. In the example shown in
  20594. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20595. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20596. \code{T}, but we could have just as well applied \code{map} to a tuple
  20597. of Booleans.
  20598. %
  20599. A \emph{monomorphic} function is simply one that is not generic.
  20600. %
  20601. We use the term \emph{instantiation} for the process (within the
  20602. language implementation) of turning a generic function into a
  20603. monomorphic one, where the type parameters have been replaced by
  20604. types.
  20605. {\if\edition\pythonEd\pythonColor
  20606. %
  20607. In Python, when writing a generic function such as \code{map}, one
  20608. does not explicitly write its generic type (using \code{All}).
  20609. Instead, that the function is generic is implied by the use of type
  20610. variables (such as \code{T}) in the type annotations of its
  20611. parameters.
  20612. %
  20613. \fi}
  20614. \begin{figure}[tbp]
  20615. % poly_test_2.rkt
  20616. \begin{tcolorbox}[colback=white]
  20617. {\if\edition\racketEd
  20618. \begin{lstlisting}
  20619. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20620. (define (map f v)
  20621. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20622. (define (inc [x : Integer]) : Integer (+ x 1))
  20623. (vector-ref (map inc (vector 0 41)) 1)
  20624. \end{lstlisting}
  20625. \fi}
  20626. {\if\edition\pythonEd\pythonColor
  20627. \begin{lstlisting}
  20628. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20629. return (f(tup[0]), f(tup[1]))
  20630. def add1(x : int) -> int:
  20631. return x + 1
  20632. t = map(add1, (0, 41))
  20633. print(t[1])
  20634. \end{lstlisting}
  20635. \fi}
  20636. \end{tcolorbox}
  20637. \caption{A generic version of the \code{map} function.}
  20638. \label{fig:map-poly}
  20639. \end{figure}
  20640. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20641. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20642. shows the definition of the abstract syntax.
  20643. %
  20644. {\if\edition\racketEd
  20645. We add a second form for function definitions in which a type
  20646. declaration comes before the \code{define}. In the abstract syntax,
  20647. the return type in the \code{Def} is \CANYTY{}, but that should be
  20648. ignored in favor of the return type in the type declaration. (The
  20649. \CANYTY{} comes from using the same parser as discussed in
  20650. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20651. enables the use of an \code{All} type for a function, thereby making
  20652. it generic.
  20653. \fi}
  20654. %
  20655. The grammar for types is extended to include the type of a generic
  20656. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20657. abstract syntax)}.
  20658. \newcommand{\LpolyGrammarRacket}{
  20659. \begin{array}{lcl}
  20660. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20661. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20662. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20663. \end{array}
  20664. }
  20665. \newcommand{\LpolyASTRacket}{
  20666. \begin{array}{lcl}
  20667. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20668. \Def &::=& \DECL{\Var}{\Type} \\
  20669. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20670. \end{array}
  20671. }
  20672. \newcommand{\LpolyGrammarPython}{
  20673. \begin{array}{lcl}
  20674. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20675. \end{array}
  20676. }
  20677. \newcommand{\LpolyASTPython}{
  20678. \begin{array}{lcl}
  20679. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20680. \MID \key{GenericVar}\LP\Var\RP
  20681. \end{array}
  20682. }
  20683. \begin{figure}[tp]
  20684. \centering
  20685. \begin{tcolorbox}[colback=white]
  20686. \footnotesize
  20687. {\if\edition\racketEd
  20688. \[
  20689. \begin{array}{l}
  20690. \gray{\LintGrammarRacket{}} \\ \hline
  20691. \gray{\LvarGrammarRacket{}} \\ \hline
  20692. \gray{\LifGrammarRacket{}} \\ \hline
  20693. \gray{\LwhileGrammarRacket} \\ \hline
  20694. \gray{\LtupGrammarRacket} \\ \hline
  20695. \gray{\LfunGrammarRacket} \\ \hline
  20696. \gray{\LlambdaGrammarRacket} \\ \hline
  20697. \LpolyGrammarRacket \\
  20698. \begin{array}{lcl}
  20699. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20700. \end{array}
  20701. \end{array}
  20702. \]
  20703. \fi}
  20704. {\if\edition\pythonEd\pythonColor
  20705. \[
  20706. \begin{array}{l}
  20707. \gray{\LintGrammarPython{}} \\ \hline
  20708. \gray{\LvarGrammarPython{}} \\ \hline
  20709. \gray{\LifGrammarPython{}} \\ \hline
  20710. \gray{\LwhileGrammarPython} \\ \hline
  20711. \gray{\LtupGrammarPython} \\ \hline
  20712. \gray{\LfunGrammarPython} \\ \hline
  20713. \gray{\LlambdaGrammarPython} \\\hline
  20714. \LpolyGrammarPython \\
  20715. \begin{array}{lcl}
  20716. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20717. \end{array}
  20718. \end{array}
  20719. \]
  20720. \fi}
  20721. \end{tcolorbox}
  20722. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20723. (figure~\ref{fig:Llam-concrete-syntax}).}
  20724. \label{fig:Lpoly-concrete-syntax}
  20725. \end{figure}
  20726. \begin{figure}[tp]
  20727. \centering
  20728. \begin{tcolorbox}[colback=white]
  20729. \footnotesize
  20730. {\if\edition\racketEd
  20731. \[
  20732. \begin{array}{l}
  20733. \gray{\LintOpAST} \\ \hline
  20734. \gray{\LvarASTRacket{}} \\ \hline
  20735. \gray{\LifASTRacket{}} \\ \hline
  20736. \gray{\LwhileASTRacket{}} \\ \hline
  20737. \gray{\LtupASTRacket{}} \\ \hline
  20738. \gray{\LfunASTRacket} \\ \hline
  20739. \gray{\LlambdaASTRacket} \\ \hline
  20740. \LpolyASTRacket \\
  20741. \begin{array}{lcl}
  20742. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20743. \end{array}
  20744. \end{array}
  20745. \]
  20746. \fi}
  20747. {\if\edition\pythonEd\pythonColor
  20748. \[
  20749. \begin{array}{l}
  20750. \gray{\LintASTPython} \\ \hline
  20751. \gray{\LvarASTPython{}} \\ \hline
  20752. \gray{\LifASTPython{}} \\ \hline
  20753. \gray{\LwhileASTPython{}} \\ \hline
  20754. \gray{\LtupASTPython{}} \\ \hline
  20755. \gray{\LfunASTPython} \\ \hline
  20756. \gray{\LlambdaASTPython} \\ \hline
  20757. \LpolyASTPython \\
  20758. \begin{array}{lcl}
  20759. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20760. \end{array}
  20761. \end{array}
  20762. \]
  20763. \fi}
  20764. \end{tcolorbox}
  20765. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20766. (figure~\ref{fig:Llam-syntax}).}
  20767. \label{fig:Lpoly-syntax}
  20768. \end{figure}
  20769. By including the \code{All} type in the $\Type$ nonterminal of the
  20770. grammar we choose to make generics first class, which has interesting
  20771. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20772. not include syntax for the \code{All} type. It is inferred for functions whose
  20773. type annotations contain type variables.} Many languages with generics, such as
  20774. C++~\citep{stroustrup88:_param_types} and Standard
  20775. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20776. may be helpful to see an example of first-class generics in action. In
  20777. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20778. whose parameter is a generic function. Indeed, because the grammar for
  20779. $\Type$ includes the \code{All} type, a generic function may also be
  20780. returned from a function or stored inside a tuple. The body of
  20781. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20782. and also to an integer, which would not be possible if \code{f} were
  20783. not generic.
  20784. \begin{figure}[tbp]
  20785. \begin{tcolorbox}[colback=white]
  20786. {\if\edition\racketEd
  20787. \begin{lstlisting}
  20788. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20789. (define (apply_twice f)
  20790. (if (f #t) (f 42) (f 777)))
  20791. (: id (All (T) (T -> T)))
  20792. (define (id x) x)
  20793. (apply_twice id)
  20794. \end{lstlisting}
  20795. \fi}
  20796. {\if\edition\pythonEd\pythonColor
  20797. \begin{lstlisting}
  20798. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20799. if f(True):
  20800. return f(42)
  20801. else:
  20802. return f(777)
  20803. def id(x: T) -> T:
  20804. return x
  20805. print(apply_twice(id))
  20806. \end{lstlisting}
  20807. \fi}
  20808. \end{tcolorbox}
  20809. \caption{An example illustrating first-class generics.}
  20810. \label{fig:apply-twice}
  20811. \end{figure}
  20812. The type checker for \LangPoly{} shown in
  20813. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20814. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20815. {\if\edition\pythonEd\pythonColor
  20816. %
  20817. Regarding function definitions, if the type annotations on its
  20818. parameters contain generic variables, then the function is generic and
  20819. therefore its type is an \code{All} type wrapped around a function
  20820. type. Otherwise the function is monomorphic and its type is simply
  20821. a function type.
  20822. %
  20823. \fi}
  20824. The type checking of a function application is extended to handle the
  20825. case in which the operator expression is a generic function. In that case
  20826. the type arguments are deduced by matching the types of the parameters
  20827. with the types of the arguments.
  20828. %
  20829. The \code{match\_types} auxiliary function
  20830. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20831. recursively descending through a parameter type \code{param\_ty} and
  20832. the corresponding argument type \code{arg\_ty}, making sure that they
  20833. are equal except when there is a type parameter in the parameter
  20834. type. Upon encountering a type parameter for the first time, the
  20835. algorithm deduces an association of the type parameter to the
  20836. corresponding part of the argument type. If it is not the first time
  20837. that the type parameter has been encountered, the algorithm looks up
  20838. its deduced type and makes sure that it is equal to the corresponding
  20839. part of the argument type. The return type of the application is the
  20840. return type of the generic function with the type parameters
  20841. replaced by the deduced type arguments, using the
  20842. \code{substitute\_type} auxiliary function, which is also listed in
  20843. figure~\ref{fig:type-check-Lpoly-aux}.
  20844. The type checker extends type equality to handle the \code{All} type.
  20845. This is not quite as simple as for other types, such as function and
  20846. tuple types, because two \code{All} types can be syntactically
  20847. different even though they are equivalent. For example,
  20848. \begin{center}
  20849. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20850. \end{center}
  20851. is equivalent to
  20852. \begin{center}
  20853. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20854. \end{center}
  20855. Two generic types are equal if they differ only in
  20856. the choice of the names of the type parameters. The definition of type
  20857. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20858. parameters in one type to match the type parameters of the other type.
  20859. {\if\edition\racketEd
  20860. %
  20861. The type checker also ensures that only defined type variables appear
  20862. in type annotations. The \code{check\_well\_formed} function for which
  20863. the definition is shown in figure~\ref{fig:well-formed-types}
  20864. recursively inspects a type, making sure that each type variable has
  20865. been defined.
  20866. %
  20867. \fi}
  20868. \begin{figure}[tbp]
  20869. \begin{tcolorbox}[colback=white]
  20870. {\if\edition\racketEd
  20871. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20872. (define type-check-poly-class
  20873. (class type-check-Llambda-class
  20874. (super-new)
  20875. (inherit check-type-equal?)
  20876. (define/override (type-check-apply env e1 es)
  20877. (define-values (e^ ty) ((type-check-exp env) e1))
  20878. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20879. ((type-check-exp env) e)))
  20880. (match ty
  20881. [`(,ty^* ... -> ,rt)
  20882. (for ([arg-ty ty*] [param-ty ty^*])
  20883. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20884. (values e^ es^ rt)]
  20885. [`(All ,xs (,tys ... -> ,rt))
  20886. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20887. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20888. (match_types env^^ param-ty arg-ty)))
  20889. (define targs
  20890. (for/list ([x xs])
  20891. (match (dict-ref env^^ x (lambda () #f))
  20892. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20893. x (Apply e1 es))]
  20894. [ty ty])))
  20895. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20896. [else (error 'type-check "expected a function, not ~a" ty)]))
  20897. (define/override ((type-check-exp env) e)
  20898. (match e
  20899. [(Lambda `([,xs : ,Ts] ...) rT body)
  20900. (for ([T Ts]) ((check_well_formed env) T))
  20901. ((check_well_formed env) rT)
  20902. ((super type-check-exp env) e)]
  20903. [(HasType e1 ty)
  20904. ((check_well_formed env) ty)
  20905. ((super type-check-exp env) e)]
  20906. [else ((super type-check-exp env) e)]))
  20907. (define/override ((type-check-def env) d)
  20908. (verbose 'type-check "poly/def" d)
  20909. (match d
  20910. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20911. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20912. (for ([p ps]) ((check_well_formed ts-env) p))
  20913. ((check_well_formed ts-env) rt)
  20914. (define new-env (append ts-env (map cons xs ps) env))
  20915. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20916. (check-type-equal? ty^ rt body)
  20917. (Generic ts (Def f p:t* rt info body^))]
  20918. [else ((super type-check-def env) d)]))
  20919. (define/override (type-check-program p)
  20920. (match p
  20921. [(Program info body)
  20922. (type-check-program (ProgramDefsExp info '() body))]
  20923. [(ProgramDefsExp info ds body)
  20924. (define ds^ (combine-decls-defs ds))
  20925. (define new-env (for/list ([d ds^])
  20926. (cons (def-name d) (fun-def-type d))))
  20927. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20928. (define-values (body^ ty) ((type-check-exp new-env) body))
  20929. (check-type-equal? ty 'Integer body)
  20930. (ProgramDefsExp info ds^^ body^)]))
  20931. ))
  20932. \end{lstlisting}
  20933. \fi}
  20934. {\if\edition\pythonEd\pythonColor
  20935. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20936. def type_check_exp(self, e, env):
  20937. match e:
  20938. case Call(Name(f), args) if f in builtin_functions:
  20939. return super().type_check_exp(e, env)
  20940. case Call(func, args):
  20941. func_t = self.type_check_exp(func, env)
  20942. func.has_type = func_t
  20943. match func_t:
  20944. case AllType(ps, FunctionType(p_tys, rt)):
  20945. for arg in args:
  20946. arg.has_type = self.type_check_exp(arg, env)
  20947. arg_tys = [arg.has_type for arg in args]
  20948. deduced = {}
  20949. for (p, a) in zip(p_tys, arg_tys):
  20950. self.match_types(p, a, deduced, e)
  20951. return self.substitute_type(rt, deduced)
  20952. case _:
  20953. return super().type_check_exp(e, env)
  20954. case _:
  20955. return super().type_check_exp(e, env)
  20956. def type_check(self, p):
  20957. match p:
  20958. case Module(body):
  20959. env = {}
  20960. for s in body:
  20961. match s:
  20962. case FunctionDef(name, params, bod, dl, returns, comment):
  20963. params_t = [t for (x,t) in params]
  20964. ty_params = set()
  20965. for t in params_t:
  20966. ty_params |$\mid$|= self.generic_variables(t)
  20967. ty = FunctionType(params_t, returns)
  20968. if len(ty_params) > 0:
  20969. ty = AllType(list(ty_params), ty)
  20970. env[name] = ty
  20971. self.check_stmts(body, IntType(), env)
  20972. case _:
  20973. raise Exception('type_check: unexpected ' + repr(p))
  20974. \end{lstlisting}
  20975. \fi}
  20976. \end{tcolorbox}
  20977. \caption{Type checker for the \LangPoly{} language.}
  20978. \label{fig:type-check-Lpoly}
  20979. \end{figure}
  20980. \begin{figure}[tbp]
  20981. \begin{tcolorbox}[colback=white]
  20982. {\if\edition\racketEd
  20983. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20984. (define/override (type-equal? t1 t2)
  20985. (match* (t1 t2)
  20986. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20987. (define env (map cons xs ys))
  20988. (type-equal? (substitute_type env T1) T2)]
  20989. [(other wise)
  20990. (super type-equal? t1 t2)]))
  20991. (define/public (match_types env pt at)
  20992. (match* (pt at)
  20993. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20994. [('Void 'Void) env] [('Any 'Any) env]
  20995. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20996. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20997. (match_types env^ pt1 at1))]
  20998. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20999. (define env^ (match_types env prt art))
  21000. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21001. (match_types env^^ pt1 at1))]
  21002. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21003. (define env^ (append (map cons pxs axs) env))
  21004. (match_types env^ pt1 at1)]
  21005. [((? symbol? x) at)
  21006. (match (dict-ref env x (lambda () #f))
  21007. [#f (error 'type-check "undefined type variable ~a" x)]
  21008. ['Type (cons (cons x at) env)]
  21009. [t^ (check-type-equal? at t^ 'matching) env])]
  21010. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21011. (define/public (substitute_type env pt)
  21012. (match pt
  21013. ['Integer 'Integer] ['Boolean 'Boolean]
  21014. ['Void 'Void] ['Any 'Any]
  21015. [`(Vector ,ts ...)
  21016. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21017. [`(,ts ... -> ,rt)
  21018. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21019. [`(All ,xs ,t)
  21020. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21021. [(? symbol? x) (dict-ref env x)]
  21022. [else (error 'type-check "expected a type not ~a" pt)]))
  21023. (define/public (combine-decls-defs ds)
  21024. (match ds
  21025. ['() '()]
  21026. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21027. (unless (equal? name f)
  21028. (error 'type-check "name mismatch, ~a != ~a" name f))
  21029. (match type
  21030. [`(All ,xs (,ps ... -> ,rt))
  21031. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21032. (cons (Generic xs (Def name params^ rt info body))
  21033. (combine-decls-defs ds^))]
  21034. [`(,ps ... -> ,rt)
  21035. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21036. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21037. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21038. [`(,(Def f params rt info body) . ,ds^)
  21039. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21040. \end{lstlisting}
  21041. \fi}
  21042. {\if\edition\pythonEd\pythonColor
  21043. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21044. def match_types(self, param_ty, arg_ty, deduced, e):
  21045. match (param_ty, arg_ty):
  21046. case (GenericVar(id), _):
  21047. if id in deduced:
  21048. self.check_type_equal(arg_ty, deduced[id], e)
  21049. else:
  21050. deduced[id] = arg_ty
  21051. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21052. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21053. new_arg_ty = self.substitute_type(arg_ty, rename)
  21054. self.match_types(ty, new_arg_ty, deduced, e)
  21055. case (TupleType(ps), TupleType(ts)):
  21056. for (p, a) in zip(ps, ts):
  21057. self.match_types(p, a, deduced, e)
  21058. case (ListType(p), ListType(a)):
  21059. self.match_types(p, a, deduced, e)
  21060. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21061. for (pp, ap) in zip(pps, aps):
  21062. self.match_types(pp, ap, deduced, e)
  21063. self.match_types(prt, art, deduced, e)
  21064. case (IntType(), IntType()):
  21065. pass
  21066. case (BoolType(), BoolType()):
  21067. pass
  21068. case _:
  21069. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21070. def substitute_type(self, ty, var_map):
  21071. match ty:
  21072. case GenericVar(id):
  21073. return var_map[id]
  21074. case AllType(ps, ty):
  21075. new_map = copy.deepcopy(var_map)
  21076. for p in ps:
  21077. new_map[p] = GenericVar(p)
  21078. return AllType(ps, self.substitute_type(ty, new_map))
  21079. case TupleType(ts):
  21080. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21081. case ListType(ty):
  21082. return ListType(self.substitute_type(ty, var_map))
  21083. case FunctionType(pts, rt):
  21084. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21085. self.substitute_type(rt, var_map))
  21086. case IntType():
  21087. return IntType()
  21088. case BoolType():
  21089. return BoolType()
  21090. case _:
  21091. raise Exception('substitute_type: unexpected ' + repr(ty))
  21092. def check_type_equal(self, t1, t2, e):
  21093. match (t1, t2):
  21094. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21095. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21096. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21097. case (_, _):
  21098. return super().check_type_equal(t1, t2, e)
  21099. \end{lstlisting}
  21100. \fi}
  21101. \end{tcolorbox}
  21102. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21103. \label{fig:type-check-Lpoly-aux}
  21104. \end{figure}
  21105. {\if\edition\racketEd
  21106. \begin{figure}[tbp]
  21107. \begin{tcolorbox}[colback=white]
  21108. \begin{lstlisting}
  21109. (define/public ((check_well_formed env) ty)
  21110. (match ty
  21111. ['Integer (void)]
  21112. ['Boolean (void)]
  21113. ['Void (void)]
  21114. [(? symbol? a)
  21115. (match (dict-ref env a (lambda () #f))
  21116. ['Type (void)]
  21117. [else (error 'type-check "undefined type variable ~a" a)])]
  21118. [`(Vector ,ts ...)
  21119. (for ([t ts]) ((check_well_formed env) t))]
  21120. [`(,ts ... -> ,t)
  21121. (for ([t ts]) ((check_well_formed env) t))
  21122. ((check_well_formed env) t)]
  21123. [`(All ,xs ,t)
  21124. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21125. ((check_well_formed env^) t)]
  21126. [else (error 'type-check "unrecognized type ~a" ty)]))
  21127. \end{lstlisting}
  21128. \end{tcolorbox}
  21129. \caption{Well-formed types.}
  21130. \label{fig:well-formed-types}
  21131. \end{figure}
  21132. \fi}
  21133. % TODO: interpreter for R'_10
  21134. \clearpage
  21135. \section{Compiling Generics}
  21136. \label{sec:compiling-poly}
  21137. Broadly speaking, there are four approaches to compiling generics, as
  21138. follows:
  21139. \begin{description}
  21140. \item[Monomorphization] generates a different version of a generic
  21141. function for each set of type arguments with which it is used,
  21142. producing type-specialized code. This approach results in the most
  21143. efficient code but requires whole-program compilation (no separate
  21144. compilation) and may increase code size. Unfortunately,
  21145. monomorphization is incompatible with first-class generics because
  21146. it is not always possible to determine which generic functions are
  21147. used with which type arguments during compilation. (It can be done
  21148. at runtime with just-in-time compilation.) Monomorphization is
  21149. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21150. generic functions in NESL~\citep{Blelloch:1993aa} and
  21151. ML~\citep{Weeks:2006aa}.
  21152. \item[Uniform representation] generates one version of each generic
  21153. function and requires all values to have a common \emph{boxed} format,
  21154. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21155. generic and monomorphic code is compiled similarly to code in a
  21156. dynamically typed language (like \LangDyn{}), in which primitive
  21157. operators require their arguments to be projected from \CANYTY{} and
  21158. their results to be injected into \CANYTY{}. (In object-oriented
  21159. languages, the projection is accomplished via virtual method
  21160. dispatch.) The uniform representation approach is compatible with
  21161. separate compilation and with first-class generics. However, it
  21162. produces the least efficient code because it introduces overhead in
  21163. the entire program. This approach is used in
  21164. Java~\citep{Bracha:1998fk},
  21165. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21166. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21167. \item[Mixed representation] generates one version of each generic
  21168. function, using a boxed representation for type variables. However,
  21169. monomorphic code is compiled as usual (as in \LangLam{}), and
  21170. conversions are performed at the boundaries between monomorphic code
  21171. and polymorphic code (for example, when a generic function is instantiated
  21172. and called). This approach is compatible with separate compilation
  21173. and first-class generics and maintains efficiency in monomorphic
  21174. code. The trade-off is increased overhead at the boundary between
  21175. monomorphic and generic code. This approach is used in
  21176. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21177. Java 5 with the addition of autoboxing.
  21178. \item[Type passing] uses the unboxed representation in both
  21179. monomorphic and generic code. Each generic function is compiled to a
  21180. single function with extra parameters that describe the type
  21181. arguments. The type information is used by the generated code to
  21182. determine how to access the unboxed values at runtime. This approach is
  21183. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21184. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21185. compilation and first-class generics and maintains the
  21186. efficiency for monomorphic code. There is runtime overhead in
  21187. polymorphic code from dispatching on type information.
  21188. \end{description}
  21189. In this chapter we use the mixed representation approach, partly
  21190. because of its favorable attributes and partly because it is
  21191. straightforward to implement using the tools that we have already
  21192. built to support gradual typing. The work of compiling generic
  21193. functions is performed in two passes, \code{resolve} and
  21194. \code{erase\_types}, that we discuss next. The output of
  21195. \code{erase\_types} is \LangCast{}
  21196. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21197. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21198. \section{Resolve Instantiation}
  21199. \label{sec:generic-resolve}
  21200. Recall that the type checker for \LangPoly{} deduces the type
  21201. arguments at call sites to a generic function. The purpose of the
  21202. \code{resolve} pass is to turn this implicit instantiation into an
  21203. explicit one, by adding \code{inst} nodes to the syntax of the
  21204. intermediate language. An \code{inst} node records the mapping of
  21205. type parameters to type arguments. The semantics of the \code{inst}
  21206. node is to instantiate the result of its first argument, a generic
  21207. function, to produce a monomorphic function. However, because the
  21208. interpreter never analyzes type annotations, instantiation can be a
  21209. no-op and simply return the generic function.
  21210. %
  21211. The output language of the \code{resolve} pass is \LangInst{},
  21212. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21213. {\if\edition\racketEd
  21214. The \code{resolve} pass combines the type declaration and polymorphic
  21215. function into a single definition, using the \code{Poly} form, to make
  21216. polymorphic functions more convenient to process in the next pass of the
  21217. compiler.
  21218. \fi}
  21219. \newcommand{\LinstASTRacket}{
  21220. \begin{array}{lcl}
  21221. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21222. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21223. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21224. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21225. \end{array}
  21226. }
  21227. \newcommand{\LinstASTPython}{
  21228. \begin{array}{lcl}
  21229. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21230. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21231. \end{array}
  21232. }
  21233. \begin{figure}[tp]
  21234. \centering
  21235. \begin{tcolorbox}[colback=white]
  21236. \small
  21237. {\if\edition\racketEd
  21238. \[
  21239. \begin{array}{l}
  21240. \gray{\LintOpAST} \\ \hline
  21241. \gray{\LvarASTRacket{}} \\ \hline
  21242. \gray{\LifASTRacket{}} \\ \hline
  21243. \gray{\LwhileASTRacket{}} \\ \hline
  21244. \gray{\LtupASTRacket{}} \\ \hline
  21245. \gray{\LfunASTRacket} \\ \hline
  21246. \gray{\LlambdaASTRacket} \\ \hline
  21247. \LinstASTRacket \\
  21248. \begin{array}{lcl}
  21249. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21250. \end{array}
  21251. \end{array}
  21252. \]
  21253. \fi}
  21254. {\if\edition\pythonEd\pythonColor
  21255. \[
  21256. \begin{array}{l}
  21257. \gray{\LintASTPython} \\ \hline
  21258. \gray{\LvarASTPython{}} \\ \hline
  21259. \gray{\LifASTPython{}} \\ \hline
  21260. \gray{\LwhileASTPython{}} \\ \hline
  21261. \gray{\LtupASTPython{}} \\ \hline
  21262. \gray{\LfunASTPython} \\ \hline
  21263. \gray{\LlambdaASTPython} \\ \hline
  21264. \LinstASTPython \\
  21265. \begin{array}{lcl}
  21266. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21267. \end{array}
  21268. \end{array}
  21269. \]
  21270. \fi}
  21271. \end{tcolorbox}
  21272. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21273. (figure~\ref{fig:Llam-syntax}).}
  21274. \label{fig:Lpoly-prime-syntax}
  21275. \end{figure}
  21276. The output of the \code{resolve} pass on the generic \code{map}
  21277. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21278. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21279. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21280. \begin{figure}[tbp]
  21281. % poly_test_2.rkt
  21282. \begin{tcolorbox}[colback=white]
  21283. {\if\edition\racketEd
  21284. \begin{lstlisting}
  21285. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21286. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21287. (define (inc [x : Integer]) : Integer (+ x 1))
  21288. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21289. (Integer))
  21290. inc (vector 0 41)) 1)
  21291. \end{lstlisting}
  21292. \fi}
  21293. {\if\edition\pythonEd\pythonColor
  21294. \begin{lstlisting}
  21295. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21296. return (f(tup[0]), f(tup[1]))
  21297. def add1(x : int) -> int:
  21298. return x + 1
  21299. t = inst(map, {T: int})(add1, (0, 41))
  21300. print(t[1])
  21301. \end{lstlisting}
  21302. \fi}
  21303. \end{tcolorbox}
  21304. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21305. \label{fig:map-resolve}
  21306. \end{figure}
  21307. \section{Erase Generic Types}
  21308. \label{sec:erase_types}
  21309. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21310. represent type variables. For example, figure~\ref{fig:map-erase}
  21311. shows the output of the \code{erase\_types} pass on the generic
  21312. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21313. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21314. \code{All} types are removed from the type of \code{map}.
  21315. \begin{figure}[tbp]
  21316. \begin{tcolorbox}[colback=white]
  21317. {\if\edition\racketEd
  21318. \begin{lstlisting}
  21319. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21320. : (Vector Any Any)
  21321. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21322. (define (inc [x : Integer]) : Integer (+ x 1))
  21323. (vector-ref ((cast map
  21324. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21325. ((Integer -> Integer) (Vector Integer Integer)
  21326. -> (Vector Integer Integer)))
  21327. inc (vector 0 41)) 1)
  21328. \end{lstlisting}
  21329. \fi}
  21330. {\if\edition\pythonEd\pythonColor
  21331. \begin{lstlisting}
  21332. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21333. return (f(tup[0]), f(tup[1]))
  21334. def add1(x : int) -> int:
  21335. return (x + 1)
  21336. def main() -> int:
  21337. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21338. print(t[1])
  21339. return 0
  21340. \end{lstlisting}
  21341. {\small
  21342. where\\
  21343. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21344. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21345. }
  21346. \fi}
  21347. \end{tcolorbox}
  21348. \caption{The generic \code{map} example after type erasure.}
  21349. \label{fig:map-erase}
  21350. \end{figure}
  21351. This process of type erasure creates a challenge at points of
  21352. instantiation. For example, consider the instantiation of
  21353. \code{map} shown in figure~\ref{fig:map-resolve}.
  21354. The type of \code{map} is
  21355. %
  21356. {\if\edition\racketEd
  21357. \begin{lstlisting}
  21358. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21359. \end{lstlisting}
  21360. \fi}
  21361. {\if\edition\pythonEd\pythonColor
  21362. \begin{lstlisting}
  21363. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21364. \end{lstlisting}
  21365. \fi}
  21366. %
  21367. and it is instantiated to
  21368. %
  21369. {\if\edition\racketEd
  21370. \begin{lstlisting}
  21371. ((Integer -> Integer) (Vector Integer Integer)
  21372. -> (Vector Integer Integer))
  21373. \end{lstlisting}
  21374. \fi}
  21375. {\if\edition\pythonEd\pythonColor
  21376. \begin{lstlisting}
  21377. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21378. \end{lstlisting}
  21379. \fi}
  21380. %
  21381. After erasure, the type of \code{map} is
  21382. %
  21383. {\if\edition\racketEd
  21384. \begin{lstlisting}
  21385. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21386. \end{lstlisting}
  21387. \fi}
  21388. {\if\edition\pythonEd\pythonColor
  21389. \begin{lstlisting}
  21390. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21391. \end{lstlisting}
  21392. \fi}
  21393. %
  21394. but we need to convert it to the instantiated type. This is easy to
  21395. do in the language \LangCast{} with a single \code{cast}. In the
  21396. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21397. \code{map} has been compiled to a \code{cast} from the type of
  21398. \code{map} to the instantiated type. The source and the target type of a
  21399. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21400. the case because both the source and target are obtained from the same
  21401. generic type of \code{map}, replacing the type parameters with
  21402. \CANYTY{} in the former and with the deduced type arguments in the
  21403. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21404. To implement the \code{erase\_types} pass, we first recommend defining
  21405. a recursive function that translates types, named
  21406. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21407. follows.
  21408. %
  21409. {\if\edition\racketEd
  21410. \begin{lstlisting}
  21411. |$T$|
  21412. |$\Rightarrow$|
  21413. Any
  21414. \end{lstlisting}
  21415. \fi}
  21416. {\if\edition\pythonEd\pythonColor
  21417. \begin{lstlisting}
  21418. GenericVar(|$T$|)
  21419. |$\Rightarrow$|
  21420. Any
  21421. \end{lstlisting}
  21422. \fi}
  21423. %
  21424. \noindent The \code{erase\_type} function also removes the generic
  21425. \code{All} types.
  21426. %
  21427. {\if\edition\racketEd
  21428. \begin{lstlisting}
  21429. (All |$xs$| |$T_1$|)
  21430. |$\Rightarrow$|
  21431. |$T'_1$|
  21432. \end{lstlisting}
  21433. \fi}
  21434. {\if\edition\pythonEd\pythonColor
  21435. \begin{lstlisting}
  21436. AllType(|$xs$|, |$T_1$|)
  21437. |$\Rightarrow$|
  21438. |$T'_1$|
  21439. \end{lstlisting}
  21440. \fi}
  21441. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21442. %
  21443. In this compiler pass, apply the \code{erase\_type} function to all
  21444. the type annotations in the program.
  21445. Regarding the translation of expressions, the case for \code{Inst} is
  21446. the interesting one. We translate it into a \code{Cast}, as shown
  21447. next.
  21448. The type of the subexpression $e$ is a generic type of the form
  21449. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21450. The source type of the cast is the erasure of $T$, the type $T_s$.
  21451. %
  21452. {\if\edition\racketEd
  21453. %
  21454. The target type $T_t$ is the result of substituting the argument types
  21455. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21456. erasure.
  21457. %
  21458. \begin{lstlisting}
  21459. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21460. |$\Rightarrow$|
  21461. (Cast |$e'$| |$T_s$| |$T_t$|)
  21462. \end{lstlisting}
  21463. %
  21464. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21465. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21466. \fi}
  21467. {\if\edition\pythonEd\pythonColor
  21468. %
  21469. The target type $T_t$ is the result of substituting the deduced
  21470. argument types $d$ in $T$ and then performing type erasure.
  21471. %
  21472. \begin{lstlisting}
  21473. Inst(|$e$|, |$d$|)
  21474. |$\Rightarrow$|
  21475. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21476. \end{lstlisting}
  21477. %
  21478. where
  21479. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21480. \fi}
  21481. Finally, each generic function is translated to a regular
  21482. function in which type erasure has been applied to all the type
  21483. annotations and the body.
  21484. %% \begin{lstlisting}
  21485. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21486. %% |$\Rightarrow$|
  21487. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21488. %% \end{lstlisting}
  21489. \begin{exercise}\normalfont\normalsize
  21490. Implement a compiler for the polymorphic language \LangPoly{} by
  21491. extending and adapting your compiler for \LangGrad{}. Create six new
  21492. test programs that use polymorphic functions. Some of them should
  21493. make use of first-class generics.
  21494. \end{exercise}
  21495. \begin{figure}[tbp]
  21496. \begin{tcolorbox}[colback=white]
  21497. {\if\edition\racketEd
  21498. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21499. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21500. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21501. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21502. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21503. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21504. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21505. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21506. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21507. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21508. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21509. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21510. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21511. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21512. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21513. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21514. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21515. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21516. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21517. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21518. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21519. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21520. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21521. \path[->,bend left=15] (Lpoly) edge [above] node
  21522. {\ttfamily\footnotesize resolve} (Lpolyp);
  21523. \path[->,bend left=15] (Lpolyp) edge [above] node
  21524. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21525. \path[->,bend left=15] (Lgradualp) edge [above] node
  21526. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21527. \path[->,bend left=15] (Llambdapp) edge [left] node
  21528. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21529. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21530. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21531. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21532. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21533. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21534. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21535. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21536. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21537. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21538. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21539. \path[->,bend left=15] (F1-1) edge [above] node
  21540. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21541. \path[->,bend left=15] (F1-2) edge [above] node
  21542. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21543. \path[->,bend left=15] (F1-3) edge [left] node
  21544. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21545. \path[->,bend left=15] (F1-4) edge [below] node
  21546. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21547. \path[->,bend right=15] (F1-5) edge [above] node
  21548. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21549. \path[->,bend right=15] (F1-6) edge [above] node
  21550. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21551. \path[->,bend right=15] (C3-2) edge [right] node
  21552. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21553. \path[->,bend right=15] (x86-2) edge [right] node
  21554. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21555. \path[->,bend right=15] (x86-2-1) edge [below] node
  21556. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21557. \path[->,bend right=15] (x86-2-2) edge [right] node
  21558. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21559. \path[->,bend left=15] (x86-3) edge [above] node
  21560. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21561. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21562. \end{tikzpicture}
  21563. \fi}
  21564. {\if\edition\pythonEd\pythonColor
  21565. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21566. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21567. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21568. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21569. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21570. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21571. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21572. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21573. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21574. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21575. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21576. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21577. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21578. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21579. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21580. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21581. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21582. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21583. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21584. \path[->,bend left=15] (Lgradual) edge [above] node
  21585. {\ttfamily\footnotesize shrink} (Lgradual2);
  21586. \path[->,bend left=15] (Lgradual2) edge [above] node
  21587. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21588. \path[->,bend left=15] (Lgradual3) edge [above] node
  21589. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21590. \path[->,bend left=15] (Lgradual4) edge [left] node
  21591. {\ttfamily\footnotesize resolve} (Lgradualr);
  21592. \path[->,bend left=15] (Lgradualr) edge [below] node
  21593. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21594. \path[->,bend right=15] (Llambdapp) edge [above] node
  21595. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21596. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21597. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21598. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21599. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21600. \path[->,bend right=15] (F1-1) edge [below] node
  21601. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21602. \path[->,bend right=15] (F1-2) edge [below] node
  21603. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21604. \path[->,bend left=15] (F1-3) edge [above] node
  21605. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21606. \path[->,bend left=15] (F1-5) edge [left] node
  21607. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21608. \path[->,bend left=5] (F1-6) edge [below] node
  21609. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21610. \path[->,bend right=15] (C3-2) edge [right] node
  21611. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21612. \path[->,bend right=15] (x86-2) edge [below] node
  21613. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21614. \path[->,bend right=15] (x86-3) edge [below] node
  21615. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21616. \path[->,bend left=15] (x86-4) edge [above] node
  21617. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21618. \end{tikzpicture}
  21619. \fi}
  21620. \end{tcolorbox}
  21621. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21622. \label{fig:Lpoly-passes}
  21623. \end{figure}
  21624. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21625. needed to compile \LangPoly{}.
  21626. % TODO: challenge problem: specialization of instantiations
  21627. % Further Reading
  21628. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21629. \clearpage
  21630. \appendix
  21631. \chapter{Appendix}
  21632. \setcounter{footnote}{0}
  21633. {\if\edition\racketEd
  21634. \section{Interpreters}
  21635. \label{appendix:interp}
  21636. \index{subject}{interpreter}
  21637. We provide interpreters for each of the source languages \LangInt{},
  21638. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21639. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21640. intermediate languages \LangCVar{} and \LangCIf{} are in
  21641. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21642. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21643. \key{interp.rkt} file.
  21644. \section{Utility Functions}
  21645. \label{appendix:utilities}
  21646. The utility functions described in this section are in the
  21647. \key{utilities.rkt} file of the support code.
  21648. \paragraph{\code{interp-tests}}
  21649. This function runs the compiler passes and the interpreters on each of
  21650. the specified tests to check whether each pass is correct. The
  21651. \key{interp-tests} function has the following parameters:
  21652. \begin{description}
  21653. \item[name (a string)] A name to identify the compiler.
  21654. \item[typechecker] A function of exactly one argument that either
  21655. raises an error using the \code{error} function when it encounters a
  21656. type error, or returns \code{\#f} when it encounters a type
  21657. error. If there is no type error, the type checker returns the
  21658. program.
  21659. \item[passes] A list with one entry per pass. An entry is a list
  21660. consisting of four things:
  21661. \begin{enumerate}
  21662. \item a string giving the name of the pass;
  21663. \item the function that implements the pass (a translator from AST
  21664. to AST);
  21665. \item a function that implements the interpreter (a function from
  21666. AST to result value) for the output language; and,
  21667. \item a type checker for the output language. Type checkers for
  21668. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21669. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21670. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21671. type checker entry is optional. The support code does not provide
  21672. type checkers for the x86 languages.
  21673. \end{enumerate}
  21674. \item[source-interp] An interpreter for the source language. The
  21675. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21676. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21677. \item[tests] A list of test numbers that specifies which tests to
  21678. run (explained next).
  21679. \end{description}
  21680. %
  21681. The \key{interp-tests} function assumes that the subdirectory
  21682. \key{tests} has a collection of Racket programs whose names all start
  21683. with the family name, followed by an underscore and then the test
  21684. number, and ending with the file extension \key{.rkt}. Also, for each test
  21685. program that calls \code{read} one or more times, there is a file with
  21686. the same name except that the file extension is \key{.in}, which
  21687. provides the input for the Racket program. If the test program is
  21688. expected to fail type checking, then there should be an empty file of
  21689. the same name with extension \key{.tyerr}.
  21690. \paragraph{\code{compiler-tests}}
  21691. This function runs the compiler passes to generate x86 (a \key{.s}
  21692. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21693. It runs the machine code and checks that the output is $42$. The
  21694. parameters to the \code{compiler-tests} function are similar to those
  21695. of the \code{interp-tests} function, and they consist of
  21696. \begin{itemize}
  21697. \item a compiler name (a string),
  21698. \item a type checker,
  21699. \item description of the passes,
  21700. \item name of a test-family, and
  21701. \item a list of test numbers.
  21702. \end{itemize}
  21703. \paragraph{\code{compile-file}}
  21704. This function takes a description of the compiler passes (see the
  21705. comment for \key{interp-tests}) and returns a function that, given a
  21706. program file name (a string ending in \key{.rkt}), applies all the
  21707. passes and writes the output to a file whose name is the same as the
  21708. program file name with extension \key{.rkt} replaced by \key{.s}.
  21709. \paragraph{\code{read-program}}
  21710. This function takes a file path and parses that file (it must be a
  21711. Racket program) into an abstract syntax tree.
  21712. \paragraph{\code{parse-program}}
  21713. This function takes an S-expression representation of an abstract
  21714. syntax tree and converts it into the struct-based representation.
  21715. \paragraph{\code{assert}}
  21716. This function takes two parameters, a string (\code{msg}) and Boolean
  21717. (\code{bool}), and displays the message \key{msg} if the Boolean
  21718. \key{bool} is false.
  21719. \paragraph{\code{lookup}}
  21720. % remove discussion of lookup? -Jeremy
  21721. This function takes a key and an alist and returns the first value that is
  21722. associated with the given key, if there is one. If not, an error is
  21723. triggered. The alist may contain both immutable pairs (built with
  21724. \key{cons}) and mutable pairs (built with \key{mcons}).
  21725. %The \key{map2} function ...
  21726. \fi} %\racketEd
  21727. \section{x86 Instruction Set Quick Reference}
  21728. \label{sec:x86-quick-reference}
  21729. \index{subject}{x86}
  21730. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21731. do. We write $A \to B$ to mean that the value of $A$ is written into
  21732. location $B$. Address offsets are given in bytes. The instruction
  21733. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21734. registers (such as \code{\%rax}), or memory references (such as
  21735. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21736. reference per instruction. Other operands must be immediates or
  21737. registers.
  21738. \begin{table}[tbp]
  21739. \centering
  21740. \begin{tabular}{l|l}
  21741. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21742. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21743. \texttt{negq} $A$ & $- A \to A$ \\
  21744. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21745. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21746. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21747. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21748. \texttt{retq} & Pops the return address and jumps to it. \\
  21749. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21750. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21751. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21752. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21753. be an immediate). \\
  21754. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21755. matches the condition code of the instruction; otherwise go to the
  21756. next instructions. The condition codes are \key{e} for \emph{equal},
  21757. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21758. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21759. \texttt{jl} $L$ & \\
  21760. \texttt{jle} $L$ & \\
  21761. \texttt{jg} $L$ & \\
  21762. \texttt{jge} $L$ & \\
  21763. \texttt{jmp} $L$ & Jump to label $L$. \\
  21764. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21765. \texttt{movzbq} $A$, $B$ &
  21766. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21767. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21768. and the extra bytes of $B$ are set to zero.} \\
  21769. & \\
  21770. & \\
  21771. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21772. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21773. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21774. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21775. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21776. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21777. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21778. description of the condition codes. $A$ must be a single byte register
  21779. (e.g., \texttt{al} or \texttt{cl}).} \\
  21780. \texttt{setl} $A$ & \\
  21781. \texttt{setle} $A$ & \\
  21782. \texttt{setg} $A$ & \\
  21783. \texttt{setge} $A$ &
  21784. \end{tabular}
  21785. \vspace{5pt}
  21786. \caption{Quick reference for the x86 instructions used in this book.}
  21787. \label{tab:x86-instr}
  21788. \end{table}
  21789. \backmatter
  21790. \addtocontents{toc}{\vspace{11pt}}
  21791. \cleardoublepage % needed for right page number in TOC for References
  21792. %% \nocite{*} is a way to get all the entries in the .bib file to
  21793. %% print in the bibliography:
  21794. \nocite{*}\let\bibname\refname
  21795. \addcontentsline{toc}{fmbm}{\refname}
  21796. \printbibliography
  21797. %\printindex{authors}{Author Index}
  21798. \printindex{subject}{Index}
  21799. \end{document}
  21800. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21801. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21802. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21803. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21804. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21805. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21806. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21807. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21808. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21809. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21810. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21811. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21812. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21813. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21814. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21815. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21816. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21817. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21818. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21819. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21820. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21821. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21822. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21823. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21824. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21825. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21826. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21827. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21828. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21829. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21830. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21831. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21832. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21833. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21834. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21835. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21836. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21837. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21838. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21839. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21840. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21841. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21842. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21843. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21844. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21845. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21846. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21847. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21848. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21849. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21850. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21851. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21852. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21853. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21854. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21855. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21856. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21857. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21858. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21859. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21860. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21861. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21862. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21863. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21864. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21865. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21866. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21867. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21868. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21869. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21870. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21871. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21872. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21873. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21874. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21875. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21876. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21877. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21878. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21879. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21880. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21881. % LocalWords: pseudocode underapproximation underapproximations LALR
  21882. % LocalWords: semilattices overapproximate incrementing Earley docs
  21883. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21884. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21885. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21886. % LocalWords: LC partialevaluation pythonEd TOC TrappedError