book.tex 828 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785
  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. {\if\edition\racketEd
  118. Library of Congress Cataloging-in-Publication Data\\
  119. \ \\
  120. Names: Siek, Jeremy, author. \\
  121. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  122. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  123. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  124. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  125. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  126. LC record available at https://lccn.loc.gov/2022015399\\
  127. LC ebook record available at https://lccn.loc.gov/2022015400\\
  128. \ \\
  129. \fi}
  130. 10 9 8 7 6 5 4 3 2 1
  131. %% Jeremy G. Siek. Available for free viewing
  132. %% or personal downloading under the
  133. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  134. %% license.
  135. %% Copyright in this monograph has been licensed exclusively to The MIT
  136. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  137. %% version to the public in 2022. All inquiries regarding rights should
  138. %% be addressed to The MIT Press, Rights and Permissions Department.
  139. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  140. %% All rights reserved. No part of this book may be reproduced in any
  141. %% form by any electronic or mechanical means (including photocopying,
  142. %% recording, or information storage and retrieval) without permission in
  143. %% writing from the publisher.
  144. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  145. %% United States of America.
  146. %% Library of Congress Cataloging-in-Publication Data is available.
  147. %% ISBN:
  148. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  149. \end{copyrightpage}
  150. \dedication{This book is dedicated to Katie, my partner in everything,
  151. my children, who grew up during the writing of this book, and the
  152. programming language students at Indiana University, whose
  153. thoughtful questions made this a better book.}
  154. %% \begin{epigraphpage}
  155. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  156. %% \textit{Book Name if any}}
  157. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  158. %% \end{epigraphpage}
  159. \tableofcontents
  160. %\listoffigures
  161. %\listoftables
  162. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  163. \chapter*{Preface}
  164. \addcontentsline{toc}{fmbm}{Preface}
  165. There is a magical moment when a programmer presses the \emph{run}
  166. button and the software begins to execute. Somehow a program written
  167. in a high-level language is running on a computer that is capable only
  168. of shuffling bits. Here we reveal the wizardry that makes that moment
  169. possible. Beginning with the groundbreaking work of Backus and
  170. colleagues in the 1950s, computer scientists developed techniques for
  171. constructing programs called \emph{compilers} that automatically
  172. translate high-level programs into machine code.
  173. We take you on a journey through constructing your own compiler for a
  174. small but powerful language. Along the way we explain the essential
  175. concepts, algorithms, and data structures that underlie compilers. We
  176. develop your understanding of how programs are mapped onto computer
  177. hardware, which is helpful in reasoning about properties at the
  178. junction of hardware and software, such as execution time, software
  179. errors, and security vulnerabilities. For those interested in
  180. pursuing compiler construction as a career, our goal is to provide a
  181. stepping-stone to advanced topics such as just-in-time compilation,
  182. program analysis, and program optimization. For those interested in
  183. designing and implementing programming languages, we connect language
  184. design choices to their impact on the compiler and the generated code.
  185. A compiler is typically organized as a sequence of stages that
  186. progressively translate a program to the code that runs on
  187. hardware. We take this approach to the extreme by partitioning our
  188. compiler into a large number of \emph{nanopasses}, each of which
  189. performs a single task. This enables the testing of each pass in
  190. isolation and focuses our attention, making the compiler far easier to
  191. understand.
  192. The most familiar approach to describing compilers is to dedicate each
  193. chapter to one pass. The problem with that approach is that it
  194. obfuscates how language features motivate design choices in a
  195. compiler. We instead take an \emph{incremental} approach in which we
  196. build a complete compiler in each chapter, starting with a small input
  197. language that includes only arithmetic and variables. We add new
  198. language features in subsequent chapters, extending the compiler as
  199. necessary.
  200. Our choice of language features is designed to elicit fundamental
  201. concepts and algorithms used in compilers.
  202. \begin{itemize}
  203. \item We begin with integer arithmetic and local variables in
  204. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  205. the fundamental tools of compiler construction: \emph{abstract
  206. syntax trees} and \emph{recursive functions}.
  207. {\if\edition\pythonEd\pythonColor
  208. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  209. parser framework to create a parser for the language of integer
  210. arithmetic and local variables. We learn about the parsing
  211. algorithms inside Lark, including Earley and LALR(1).
  212. %
  213. \fi}
  214. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  215. \emph{graph coloring} to assign variables to machine registers.
  216. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  217. motivates an elegant recursive algorithm for translating them into
  218. conditional \code{goto} statements.
  219. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  220. variables}. This elicits the need for \emph{dataflow
  221. analysis} in the register allocator.
  222. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  223. \emph{garbage collection}.
  224. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  225. without lexical scoping, similar to functions in the C programming
  226. language~\citep{Kernighan:1988nx}. The reader learns about the
  227. procedure call stack and \emph{calling conventions} and how they interact
  228. with register allocation and garbage collection. The chapter also
  229. describes how to generate efficient tail calls.
  230. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  231. scoping, that is, \emph{lambda} expressions. The reader learns about
  232. \emph{closure conversion}, in which lambdas are translated into a
  233. combination of functions and tuples.
  234. % Chapter about classes and objects?
  235. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  236. point the input languages are statically typed. The reader extends
  237. the statically typed language with an \code{Any} type that serves
  238. as a target for compiling the dynamically typed language.
  239. %% {\if\edition\pythonEd\pythonColor
  240. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  241. %% \emph{classes}.
  242. %% \fi}
  243. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  244. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  245. in which different regions of a program may be static or dynamically
  246. typed. The reader implements runtime support for \emph{proxies} that
  247. allow values to safely move between regions.
  248. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  249. leveraging the \code{Any} type and type casts developed in chapters
  250. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  251. \end{itemize}
  252. There are many language features that we do not include. Our choices
  253. balance the incidental complexity of a feature versus the fundamental
  254. concepts that it exposes. For example, we include tuples and not
  255. records because although they both elicit the study of heap allocation and
  256. garbage collection, records come with more incidental complexity.
  257. Since 2009, drafts of this book have served as the textbook for
  258. sixteen-week compiler courses for upper-level undergraduates and
  259. first-year graduate students at the University of Colorado and Indiana
  260. University.
  261. %
  262. Students come into the course having learned the basics of
  263. programming, data structures and algorithms, and discrete
  264. mathematics.
  265. %
  266. At the beginning of the course, students form groups of two to four
  267. people. The groups complete approximately one chapter every two
  268. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  269. according to the students interests while respecting the dependencies
  270. between chapters shown in
  271. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  272. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  273. implementation of efficient tail calls.
  274. %
  275. The last two weeks of the course involve a final project in which
  276. students design and implement a compiler extension of their choosing.
  277. The last few chapters can be used in support of these projects. Many
  278. chapters include a challenge problem that we assign to the graduate
  279. students.
  280. For compiler courses at universities on the quarter system
  281. (about ten weeks in length), we recommend completing the course
  282. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  283. some scaffolding code to the students for each compiler pass.
  284. %
  285. The course can be adapted to emphasize functional languages by
  286. skipping chapter~\ref{ch:Lwhile} (loops) and including
  287. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  288. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  289. %
  290. %% \python{A course that emphasizes object-oriented languages would
  291. %% include Chapter~\ref{ch:Lobject}.}
  292. This book has been used in compiler courses at California Polytechnic
  293. State University, Portland State University, Rose–Hulman Institute of
  294. Technology, University of Freiburg, University of Massachusetts
  295. Lowell, and the University of Vermont.
  296. \begin{figure}[tp]
  297. \begin{tcolorbox}[colback=white]
  298. {\if\edition\racketEd
  299. \begin{tikzpicture}[baseline=(current bounding box.center)]
  300. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  301. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  302. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  303. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  304. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  305. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  306. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  307. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  308. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  309. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  310. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  311. \path[->] (C1) edge [above] node {} (C2);
  312. \path[->] (C2) edge [above] node {} (C3);
  313. \path[->] (C3) edge [above] node {} (C4);
  314. \path[->] (C4) edge [above] node {} (C5);
  315. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  316. \path[->] (C5) edge [above] node {} (C7);
  317. \path[->] (C6) edge [above] node {} (C7);
  318. \path[->] (C4) edge [above] node {} (C8);
  319. \path[->] (C4) edge [above] node {} (C9);
  320. \path[->] (C7) edge [above] node {} (C10);
  321. \path[->] (C8) edge [above] node {} (C10);
  322. \path[->] (C10) edge [above] node {} (C11);
  323. \end{tikzpicture}
  324. \fi}
  325. {\if\edition\pythonEd\pythonColor
  326. \begin{tikzpicture}[baseline=(current bounding box.center)]
  327. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  328. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  329. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  330. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  331. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  332. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  333. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  334. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  335. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  336. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  337. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  338. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  339. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  340. \path[->] (Prelim) edge [above] node {} (Var);
  341. \path[->] (Var) edge [above] node {} (Reg);
  342. \path[->] (Var) edge [above] node {} (Parse);
  343. \path[->] (Reg) edge [above] node {} (Cond);
  344. \path[->] (Cond) edge [above] node {} (Tuple);
  345. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  346. \path[->] (Cond) edge [above] node {} (Fun);
  347. \path[->] (Tuple) edge [above] node {} (Lam);
  348. \path[->] (Fun) edge [above] node {} (Lam);
  349. \path[->] (Cond) edge [above] node {} (Dyn);
  350. \path[->] (Cond) edge [above] node {} (Loop);
  351. \path[->] (Lam) edge [above] node {} (Gradual);
  352. \path[->] (Dyn) edge [above] node {} (Gradual);
  353. % \path[->] (Dyn) edge [above] node {} (CO);
  354. \path[->] (Gradual) edge [above] node {} (Generic);
  355. \end{tikzpicture}
  356. \fi}
  357. \end{tcolorbox}
  358. \caption{Diagram of chapter dependencies.}
  359. \label{fig:chapter-dependences}
  360. \end{figure}
  361. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  362. the implementation of the compiler and for the input language, so the
  363. reader should be proficient with Racket or Scheme. There are many
  364. excellent resources for learning Scheme and
  365. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  366. %
  367. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  368. both for the implementation of the compiler and for the input language, so the
  369. reader should be proficient with Python. There are many
  370. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  371. %
  372. The support code for this book is in the GitHub repository at
  373. the following location:
  374. \begin{center}\small\texttt
  375. https://github.com/IUCompilerCourse/
  376. \end{center}
  377. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  378. is helpful but not necessary for the reader to have taken a computer
  379. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  380. assembly language that are needed in the compiler.
  381. %
  382. We follow the System V calling
  383. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  384. that we generate works with the runtime system (written in C) when it
  385. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  386. operating systems on Intel hardware.
  387. %
  388. On the Windows operating system, \code{gcc} uses the Microsoft x64
  389. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  390. assembly code that we generate does \emph{not} work with the runtime
  391. system on Windows. One workaround is to use a virtual machine with
  392. Linux as the guest operating system.
  393. \section*{Acknowledgments}
  394. The tradition of compiler construction at Indiana University goes back
  395. to research and courses on programming languages by Daniel Friedman in
  396. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  397. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  398. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  399. the compiler course and continued the development of Chez Scheme.
  400. %
  401. The compiler course evolved to incorporate novel pedagogical ideas
  402. while also including elements of real-world compilers. One of
  403. Friedman's ideas was to split the compiler into many small
  404. passes. Another idea, called ``the game,'' was to test the code
  405. generated by each pass using interpreters.
  406. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  407. developed infrastructure to support this approach and evolved the
  408. course to use even smaller
  409. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  410. design decisions in this book are inspired by the assignment
  411. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  412. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  413. organization of the course made it difficult for students to
  414. understand the rationale for the compiler design. Ghuloum proposed the
  415. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  416. based.
  417. I thank the many students who served as teaching assistants for the
  418. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  419. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  420. garbage collector and x86 interpreter, Michael Vollmer for work on
  421. efficient tail calls, and Michael Vitousek for help with the first
  422. offering of the incremental compiler course at IU.
  423. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  424. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  425. Michael Wollowski for teaching courses based on drafts of this book
  426. and for their feedback. I thank the National Science Foundation for
  427. the grants that helped to support this work: Grant Numbers 1518844,
  428. 1763922, and 1814460.
  429. I thank Ronald Garcia for helping me survive Dybvig's compiler
  430. course in the early 2000s and especially for finding the bug that
  431. sent our garbage collector on a wild goose chase!
  432. \mbox{}\\
  433. \noindent Jeremy G. Siek \\
  434. Bloomington, Indiana
  435. \mainmatter
  436. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  437. \chapter{Preliminaries}
  438. \label{ch:trees-recur}
  439. \setcounter{footnote}{0}
  440. In this chapter we review the basic tools needed to implement a
  441. compiler. Programs are typically input by a programmer as text, that
  442. is, a sequence of characters. The program-as-text representation is
  443. called \emph{concrete syntax}. We use concrete syntax to concisely
  444. write down and talk about programs. Inside the compiler, we use
  445. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  446. that efficiently supports the operations that the compiler needs to
  447. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  448. syntax}\index{subject}{abstract syntax
  449. tree}\index{subject}{AST}\index{subject}{program}
  450. The process of translating concrete syntax to abstract syntax is
  451. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  452. chapter~\ref{ch:parsing}}.
  453. \racket{This book does not cover the theory and implementation of parsing.
  454. We refer the readers interested in parsing to the thorough treatment
  455. of parsing by \citet{Aho:2006wb}.}%
  456. %
  457. \racket{A parser is provided in the support code for translating from
  458. concrete to abstract syntax.}%
  459. %
  460. \python{For now we use Python's \code{ast} module to translate from concrete
  461. to abstract syntax.}
  462. ASTs can be represented inside the compiler in many different ways,
  463. depending on the programming language used to write the compiler.
  464. %
  465. \racket{We use Racket's
  466. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  467. feature to represent ASTs (section~\ref{sec:ast}).}
  468. %
  469. \python{We use Python classes and objects to represent ASTs, especially the
  470. classes defined in the standard \code{ast} module for the Python
  471. source language.}
  472. %
  473. We use grammars to define the abstract syntax of programming languages
  474. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  475. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  476. recursive functions to construct and deconstruct ASTs
  477. (section~\ref{sec:recursion}). This chapter provides a brief
  478. introduction to these components.
  479. \racket{\index{subject}{struct}}
  480. \python{\index{subject}{class}\index{subject}{object}}
  481. \section{Abstract Syntax Trees}
  482. \label{sec:ast}
  483. Compilers use abstract syntax trees to represent programs because they
  484. often need to ask questions such as, for a given part of a program,
  485. what kind of language feature is it? What are its subparts? Consider
  486. the program on the left and the diagram of its AST on the
  487. right~\eqref{eq:arith-prog}. This program is an addition operation
  488. that has two subparts, a \racket{read}\python{input} operation and a
  489. negation. The negation has another subpart, the integer constant
  490. \code{8}. By using a tree to represent the program, we can easily
  491. follow the links to go from one part of a program to its subparts.
  492. \begin{center}
  493. \begin{minipage}{0.4\textwidth}
  494. {\if\edition\racketEd
  495. \begin{lstlisting}
  496. (+ (read) (- 8))
  497. \end{lstlisting}
  498. \fi}
  499. {\if\edition\pythonEd\pythonColor
  500. \begin{lstlisting}
  501. input_int() + -8
  502. \end{lstlisting}
  503. \fi}
  504. \end{minipage}
  505. \begin{minipage}{0.4\textwidth}
  506. \begin{equation}
  507. \begin{tikzpicture}
  508. \node[draw] (plus) at (0 , 0) {\key{+}};
  509. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  510. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  511. \node[draw] (8) at (1 , -2) {\key{8}};
  512. \draw[->] (plus) to (read);
  513. \draw[->] (plus) to (minus);
  514. \draw[->] (minus) to (8);
  515. \end{tikzpicture}
  516. \label{eq:arith-prog}
  517. \end{equation}
  518. \end{minipage}
  519. \end{center}
  520. We use the standard terminology for trees to describe ASTs: each
  521. rectangle above is called a \emph{node}. The arrows connect a node to its
  522. \emph{children}, which are also nodes. The top-most node is the
  523. \emph{root}. Every node except for the root has a \emph{parent} (the
  524. node of which it is the child). If a node has no children, it is a
  525. \emph{leaf} node; otherwise it is an \emph{internal} node.
  526. \index{subject}{node}
  527. \index{subject}{children}
  528. \index{subject}{root}
  529. \index{subject}{parent}
  530. \index{subject}{leaf}
  531. \index{subject}{internal node}
  532. %% Recall that an \emph{symbolic expression} (S-expression) is either
  533. %% \begin{enumerate}
  534. %% \item an atom, or
  535. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  536. %% where $e_1$ and $e_2$ are each an S-expression.
  537. %% \end{enumerate}
  538. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  539. %% null value \code{'()}, etc. We can create an S-expression in Racket
  540. %% simply by writing a backquote (called a quasi-quote in Racket)
  541. %% followed by the textual representation of the S-expression. It is
  542. %% quite common to use S-expressions to represent a list, such as $a, b
  543. %% ,c$ in the following way:
  544. %% \begin{lstlisting}
  545. %% `(a . (b . (c . ())))
  546. %% \end{lstlisting}
  547. %% Each element of the list is in the first slot of a pair, and the
  548. %% second slot is either the rest of the list or the null value, to mark
  549. %% the end of the list. Such lists are so common that Racket provides
  550. %% special notation for them that removes the need for the periods
  551. %% and so many parenthesis:
  552. %% \begin{lstlisting}
  553. %% `(a b c)
  554. %% \end{lstlisting}
  555. %% The following expression creates an S-expression that represents AST
  556. %% \eqref{eq:arith-prog}.
  557. %% \begin{lstlisting}
  558. %% `(+ (read) (- 8))
  559. %% \end{lstlisting}
  560. %% When using S-expressions to represent ASTs, the convention is to
  561. %% represent each AST node as a list and to put the operation symbol at
  562. %% the front of the list. The rest of the list contains the children. So
  563. %% in the above case, the root AST node has operation \code{`+} and its
  564. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  565. %% diagram \eqref{eq:arith-prog}.
  566. %% To build larger S-expressions one often needs to splice together
  567. %% several smaller S-expressions. Racket provides the comma operator to
  568. %% splice an S-expression into a larger one. For example, instead of
  569. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  570. %% we could have first created an S-expression for AST
  571. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  572. %% S-expression.
  573. %% \begin{lstlisting}
  574. %% (define ast1.4 `(- 8))
  575. %% (define ast1_1 `(+ (read) ,ast1.4))
  576. %% \end{lstlisting}
  577. %% In general, the Racket expression that follows the comma (splice)
  578. %% can be any expression that produces an S-expression.
  579. {\if\edition\racketEd
  580. We define a Racket \code{struct} for each kind of node. For this
  581. chapter we require just two kinds of nodes: one for integer constants
  582. (aka literals\index{subject}{literals})
  583. and one for primitive operations. The following is the \code{struct}
  584. definition for integer constants.\footnote{All the AST structures are
  585. defined in the file \code{utilities.rkt} in the support code.}
  586. \begin{lstlisting}
  587. (struct Int (value))
  588. \end{lstlisting}
  589. An integer node contains just one thing: the integer value.
  590. We establish the convention that \code{struct} names, such
  591. as \code{Int}, are capitalized.
  592. To create an AST node for the integer $8$, we write \INT{8}.
  593. \begin{lstlisting}
  594. (define eight (Int 8))
  595. \end{lstlisting}
  596. We say that the value created by \INT{8} is an
  597. \emph{instance} of the
  598. \code{Int} structure.
  599. The following is the \code{struct} definition for primitive operations.
  600. \begin{lstlisting}
  601. (struct Prim (op args))
  602. \end{lstlisting}
  603. A primitive operation node includes an operator symbol \code{op} and a
  604. list of child arguments called \code{args}. For example, to create an
  605. AST that negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. (define neg-eight (Prim '- (list eight)))
  608. \end{lstlisting}
  609. Primitive operations may have zero or more children. The \code{read}
  610. operator has zero:
  611. \begin{lstlisting}
  612. (define rd (Prim 'read '()))
  613. \end{lstlisting}
  614. The addition operator has two children:
  615. \begin{lstlisting}
  616. (define ast1_1 (Prim '+ (list rd neg-eight)))
  617. \end{lstlisting}
  618. We have made a design choice regarding the \code{Prim} structure.
  619. Instead of using one structure for many different operations
  620. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  621. structure for each operation, as follows:
  622. \begin{lstlisting}
  623. (struct Read ())
  624. (struct Add (left right))
  625. (struct Neg (value))
  626. \end{lstlisting}
  627. The reason that we choose to use just one structure is that many parts
  628. of the compiler can use the same code for the different primitive
  629. operators, so we might as well just write that code once by using a
  630. single structure.
  631. %
  632. \fi}
  633. {\if\edition\pythonEd\pythonColor
  634. We use a Python \code{class} for each kind of node.
  635. The following is the class definition for
  636. constants (aka literals\index{subject}{literals})
  637. from the Python \code{ast} module.
  638. \begin{lstlisting}
  639. class Constant:
  640. def __init__(self, value):
  641. self.value = value
  642. \end{lstlisting}
  643. An integer constant node includes just one thing: the integer value.
  644. To create an AST node for the integer $8$, we write \INT{8}.
  645. \begin{lstlisting}
  646. eight = Constant(8)
  647. \end{lstlisting}
  648. We say that the value created by \INT{8} is an
  649. \emph{instance} of the \code{Constant} class.
  650. The following is the class definition for unary operators.
  651. \begin{lstlisting}
  652. class UnaryOp:
  653. def __init__(self, op, operand):
  654. self.op = op
  655. self.operand = operand
  656. \end{lstlisting}
  657. The specific operation is specified by the \code{op} parameter. For
  658. example, the class \code{USub} is for unary subtraction.
  659. (More unary operators are introduced in later chapters.) To create an AST that
  660. negates the number $8$, we write the following.
  661. \begin{lstlisting}
  662. neg_eight = UnaryOp(USub(), eight)
  663. \end{lstlisting}
  664. The call to the \code{input\_int} function is represented by the
  665. \code{Call} and \code{Name} classes.
  666. \begin{lstlisting}
  667. class Call:
  668. def __init__(self, func, args):
  669. self.func = func
  670. self.args = args
  671. class Name:
  672. def __init__(self, id):
  673. self.id = id
  674. \end{lstlisting}
  675. To create an AST node that calls \code{input\_int}, we write
  676. \begin{lstlisting}
  677. read = Call(Name('input_int'), [])
  678. \end{lstlisting}
  679. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  680. the \code{BinOp} class for binary operators.
  681. \begin{lstlisting}
  682. class BinOp:
  683. def __init__(self, left, op, right):
  684. self.op = op
  685. self.left = left
  686. self.right = right
  687. \end{lstlisting}
  688. Similar to \code{UnaryOp}, the specific operation is specified by the
  689. \code{op} parameter, which for now is just an instance of the
  690. \code{Add} class. So to create the AST
  691. node that adds negative eight to some user input, we write the following.
  692. \begin{lstlisting}
  693. ast1_1 = BinOp(read, Add(), neg_eight)
  694. \end{lstlisting}
  695. \fi}
  696. To compile a program such as \eqref{eq:arith-prog}, we need to know
  697. that the operation associated with the root node is addition and we
  698. need to be able to access its two
  699. children. \racket{Racket}\python{Python} provides pattern matching to
  700. support these kinds of queries, as we see in
  701. section~\ref{sec:pattern-matching}.
  702. We often write down the concrete syntax of a program even when we
  703. actually have in mind the AST, because the concrete syntax is more
  704. concise. We recommend that you always think of programs as abstract
  705. syntax trees.
  706. \section{Grammars}
  707. \label{sec:grammar}
  708. \index{subject}{integer}
  709. %\index{subject}{constant}
  710. A programming language can be thought of as a \emph{set} of programs.
  711. The set is infinite (that is, one can always create larger programs),
  712. so one cannot simply describe a language by listing all the
  713. programs in the language. Instead we write down a set of rules, a
  714. \emph{context-free grammar}, for building programs. Grammars are often used to
  715. define the concrete syntax of a language, but they can also be used to
  716. describe the abstract syntax. We write our rules in a variant of
  717. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  718. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  719. we describe a small language, named \LangInt{}, that consists of
  720. integers and arithmetic operations.\index{subject}{grammar}
  721. \index{subject}{context-free grammar}
  722. The first grammar rule for the abstract syntax of \LangInt{} says that an
  723. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  724. \begin{equation}
  725. \Exp ::= \INT{\Int} \label{eq:arith-int}
  726. \end{equation}
  727. %
  728. Each rule has a left-hand side and a right-hand side.
  729. If you have an AST node that matches the
  730. right-hand side, then you can categorize it according to the
  731. left-hand side.
  732. %
  733. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  734. are \emph{terminal} symbols and must literally appear in the program for the
  735. rule to be applicable.\index{subject}{terminal}
  736. %
  737. Our grammars do not mention \emph{white space}, that is, delimiter
  738. characters like spaces, tabs, and new lines. White space may be
  739. inserted between symbols for disambiguation and to improve
  740. readability. \index{subject}{white space}
  741. %
  742. A name such as $\Exp$ that is defined by the grammar rules is a
  743. \emph{nonterminal}. \index{subject}{nonterminal}
  744. %
  745. The name $\Int$ is also a nonterminal, but instead of defining it with
  746. a grammar rule, we define it with the following explanation. An
  747. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  748. $-$ (for negative integers), such that the sequence of decimals
  749. %
  750. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  751. enables the representation of integers using 63 bits, which simplifies
  752. several aspects of compilation.
  753. %
  754. Thus, these integers correspond to the Racket \texttt{fixnum}
  755. datatype on a 64-bit machine.}
  756. %
  757. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  758. enables the representation of integers using 64 bits, which simplifies
  759. several aspects of compilation. In contrast, integers in Python have
  760. unlimited precision, but the techniques needed to handle unlimited
  761. precision fall outside the scope of this book.}
  762. The second grammar rule is the \READOP{} operation, which receives an
  763. input integer from the user of the program.
  764. \begin{equation}
  765. \Exp ::= \READ{} \label{eq:arith-read}
  766. \end{equation}
  767. The third rule categorizes the negation of an $\Exp$ node as an
  768. $\Exp$.
  769. \begin{equation}
  770. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  771. \end{equation}
  772. We can apply these rules to categorize the ASTs that are in the
  773. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  774. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  775. following AST is an $\Exp$.
  776. \begin{center}
  777. \begin{minipage}{0.5\textwidth}
  778. \NEG{\INT{\code{8}}}
  779. \end{minipage}
  780. \begin{minipage}{0.25\textwidth}
  781. \begin{equation}
  782. \begin{tikzpicture}
  783. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  784. \node[draw, circle] (8) at (0, -1.2) {$8$};
  785. \draw[->] (minus) to (8);
  786. \end{tikzpicture}
  787. \label{eq:arith-neg8}
  788. \end{equation}
  789. \end{minipage}
  790. \end{center}
  791. The next two grammar rules are for addition and subtraction expressions:
  792. \begin{align}
  793. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  794. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  795. \end{align}
  796. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  797. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  798. \eqref{eq:arith-read}, and we have already categorized
  799. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  800. to show that
  801. \[
  802. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  803. \]
  804. is an $\Exp$ in the \LangInt{} language.
  805. If you have an AST for which these rules do not apply, then the
  806. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  807. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  808. because there is no rule for the \key{*} operator. Whenever we
  809. define a language with a grammar, the language includes only those
  810. programs that are justified by the grammar rules.
  811. {\if\edition\pythonEd\pythonColor
  812. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  813. There is a statement for printing the value of an expression
  814. \[
  815. \Stmt{} ::= \PRINT{\Exp}
  816. \]
  817. and a statement that evaluates an expression but ignores the result.
  818. \[
  819. \Stmt{} ::= \EXPR{\Exp}
  820. \]
  821. \fi}
  822. {\if\edition\racketEd
  823. The last grammar rule for \LangInt{} states that there is a
  824. \code{Program} node to mark the top of the whole program:
  825. \[
  826. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  827. \]
  828. The \code{Program} structure is defined as follows:
  829. \begin{lstlisting}
  830. (struct Program (info body))
  831. \end{lstlisting}
  832. where \code{body} is an expression. In further chapters, the \code{info}
  833. part is used to store auxiliary information, but for now it is
  834. just the empty list.
  835. \fi}
  836. {\if\edition\pythonEd\pythonColor
  837. The last grammar rule for \LangInt{} states that there is a
  838. \code{Module} node to mark the top of the whole program:
  839. \[
  840. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  841. \]
  842. The asterisk $*$ indicates a list of the preceding grammar item, in
  843. this case a list of statements.
  844. %
  845. The \code{Module} class is defined as follows:
  846. \begin{lstlisting}
  847. class Module:
  848. def __init__(self, body):
  849. self.body = body
  850. \end{lstlisting}
  851. where \code{body} is a list of statements.
  852. \fi}
  853. It is common to have many grammar rules with the same left-hand side
  854. but different right-hand sides, such as the rules for $\Exp$ in the
  855. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  856. combine several right-hand sides into a single rule.
  857. The concrete syntax for \LangInt{} is shown in
  858. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  859. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  860. %
  861. \racket{The \code{read-program} function provided in
  862. \code{utilities.rkt} of the support code reads a program from a file
  863. (the sequence of characters in the concrete syntax of Racket) and
  864. parses it into an abstract syntax tree. Refer to the description of
  865. \code{read-program} in appendix~\ref{appendix:utilities} for more
  866. details.}
  867. %
  868. \python{The \code{parse} function in Python's \code{ast} module
  869. converts the concrete syntax (represented as a string) into an
  870. abstract syntax tree.}
  871. \newcommand{\LintGrammarRacket}{
  872. \begin{array}{rcl}
  873. \Type &::=& \key{Integer} \\
  874. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  875. \MID \CSUB{\Exp}{\Exp}
  876. \end{array}
  877. }
  878. \newcommand{\LintASTRacket}{
  879. \begin{array}{rcl}
  880. \Type &::=& \key{Integer} \\
  881. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  882. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  883. \end{array}
  884. }
  885. \newcommand{\LintGrammarPython}{
  886. \begin{array}{rcl}
  887. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  888. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  889. \end{array}
  890. }
  891. \newcommand{\LintASTPython}{
  892. \begin{array}{rcl}
  893. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  894. \itm{unaryop} &::= & \code{USub()} \\
  895. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  896. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp} \\
  897. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  898. \end{array}
  899. }
  900. \begin{figure}[tp]
  901. \begin{tcolorbox}[colback=white]
  902. {\if\edition\racketEd
  903. \[
  904. \begin{array}{l}
  905. \LintGrammarRacket \\
  906. \begin{array}{rcl}
  907. \LangInt{} &::=& \Exp
  908. \end{array}
  909. \end{array}
  910. \]
  911. \fi}
  912. {\if\edition\pythonEd\pythonColor
  913. \[
  914. \begin{array}{l}
  915. \LintGrammarPython \\
  916. \begin{array}{rcl}
  917. \LangInt{} &::=& \Stmt^{*}
  918. \end{array}
  919. \end{array}
  920. \]
  921. \fi}
  922. \end{tcolorbox}
  923. \caption{The concrete syntax of \LangInt{}.}
  924. \label{fig:r0-concrete-syntax}
  925. \end{figure}
  926. \begin{figure}[tp]
  927. \begin{tcolorbox}[colback=white]
  928. {\if\edition\racketEd
  929. \[
  930. \begin{array}{l}
  931. \LintASTRacket{} \\
  932. \begin{array}{rcl}
  933. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  934. \end{array}
  935. \end{array}
  936. \]
  937. \fi}
  938. {\if\edition\pythonEd\pythonColor
  939. \[
  940. \begin{array}{l}
  941. \LintASTPython\\
  942. \begin{array}{rcl}
  943. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  944. \end{array}
  945. \end{array}
  946. \]
  947. \fi}
  948. \end{tcolorbox}
  949. \python{
  950. \index{subject}{Constant@\texttt{Constant}}
  951. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  952. \index{subject}{USub@\texttt{USub}}
  953. \index{subject}{inputint@\texttt{input\_int}}
  954. \index{subject}{Call@\texttt{Call}}
  955. \index{subject}{Name@\texttt{Name}}
  956. \index{subject}{BinOp@\texttt{BinOp}}
  957. \index{subject}{Add@\texttt{Add}}
  958. \index{subject}{Sub@\texttt{Sub}}
  959. \index{subject}{print@\texttt{print}}
  960. \index{subject}{Expr@\texttt{Expr}}
  961. \index{subject}{Module@\texttt{Module}}
  962. }
  963. \caption{The abstract syntax of \LangInt{}.}
  964. \label{fig:r0-syntax}
  965. \end{figure}
  966. \section{Pattern Matching}
  967. \label{sec:pattern-matching}
  968. As mentioned in section~\ref{sec:ast}, compilers often need to access
  969. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  970. provides the \texttt{match} feature to access the parts of a value.
  971. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  972. \begin{center}
  973. \begin{minipage}{1.0\textwidth}
  974. {\if\edition\racketEd
  975. \begin{lstlisting}
  976. (match ast1_1
  977. [(Prim op (list child1 child2))
  978. (print op)])
  979. \end{lstlisting}
  980. \fi}
  981. {\if\edition\pythonEd\pythonColor
  982. \begin{lstlisting}
  983. match ast1_1:
  984. case BinOp(child1, op, child2):
  985. print(op)
  986. \end{lstlisting}
  987. \fi}
  988. \end{minipage}
  989. \end{center}
  990. {\if\edition\racketEd
  991. %
  992. In this example, the \texttt{match} form checks whether the AST
  993. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  994. three pattern variables \texttt{op}, \texttt{child1}, and
  995. \texttt{child2}. In general, a match clause consists of a
  996. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  997. recursively defined to be a pattern variable, a structure name
  998. followed by a pattern for each of the structure's arguments, or an
  999. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1000. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1001. and chapter 9 of The Racket
  1002. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1003. for complete descriptions of \code{match}.)
  1004. %
  1005. The body of a match clause may contain arbitrary Racket code. The
  1006. pattern variables can be used in the scope of the body, such as
  1007. \code{op} in \code{(print op)}.
  1008. %
  1009. \fi}
  1010. %
  1011. %
  1012. {\if\edition\pythonEd\pythonColor
  1013. %
  1014. In the example above, the \texttt{match} form checks whether the AST
  1015. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1016. three pattern variables (\texttt{child1}, \texttt{op}, and
  1017. \texttt{child2}). In general, each \code{case} consists of a
  1018. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1019. recursively defined to be one of the following: a pattern variable, a
  1020. class name followed by a pattern for each of its constructor's
  1021. arguments, or other literals\index{subject}{literals} such as strings
  1022. or lists.
  1023. %
  1024. The body of each \code{case} may contain arbitrary Python code. The
  1025. pattern variables can be used in the body, such as \code{op} in
  1026. \code{print(op)}.
  1027. %
  1028. \fi}
  1029. A \code{match} form may contain several clauses, as in the following
  1030. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1031. the AST. The \code{match} proceeds through the clauses in order,
  1032. checking whether the pattern can match the input AST. The body of the
  1033. first clause that matches is executed. The output of \code{leaf} for
  1034. several ASTs is shown on the right side of the following:
  1035. \begin{center}
  1036. \begin{minipage}{0.6\textwidth}
  1037. {\if\edition\racketEd
  1038. \begin{lstlisting}
  1039. (define (leaf arith)
  1040. (match arith
  1041. [(Int n) #t]
  1042. [(Prim 'read '()) #t]
  1043. [(Prim '- (list e1)) #f]
  1044. [(Prim '+ (list e1 e2)) #f]
  1045. [(Prim '- (list e1 e2)) #f]))
  1046. (leaf (Prim 'read '()))
  1047. (leaf (Prim '- (list (Int 8))))
  1048. (leaf (Int 8))
  1049. \end{lstlisting}
  1050. \fi}
  1051. {\if\edition\pythonEd\pythonColor
  1052. \begin{lstlisting}
  1053. def leaf(arith):
  1054. match arith:
  1055. case Constant(n):
  1056. return True
  1057. case Call(Name('input_int'), []):
  1058. return True
  1059. case UnaryOp(USub(), e1):
  1060. return False
  1061. case BinOp(e1, Add(), e2):
  1062. return False
  1063. case BinOp(e1, Sub(), e2):
  1064. return False
  1065. print(leaf(Call(Name('input_int'), [])))
  1066. print(leaf(UnaryOp(USub(), eight)))
  1067. print(leaf(Constant(8)))
  1068. \end{lstlisting}
  1069. \fi}
  1070. \end{minipage}
  1071. \vrule
  1072. \begin{minipage}{0.25\textwidth}
  1073. {\if\edition\racketEd
  1074. \begin{lstlisting}
  1075. #t
  1076. #f
  1077. #t
  1078. \end{lstlisting}
  1079. \fi}
  1080. {\if\edition\pythonEd\pythonColor
  1081. \begin{lstlisting}
  1082. True
  1083. False
  1084. True
  1085. \end{lstlisting}
  1086. \fi}
  1087. \end{minipage}
  1088. \index{subject}{True@\TRUE{}}
  1089. \index{subject}{False@\FALSE{}}
  1090. \end{center}
  1091. When constructing a \code{match} expression, we refer to the grammar
  1092. definition to identify which nonterminal we are expecting to match
  1093. against, and then we make sure that (1) we have one
  1094. \racket{clause}\python{case} for each alternative of that nonterminal
  1095. and (2) the pattern in each \racket{clause}\python{case}
  1096. corresponds to the corresponding right-hand side of a grammar
  1097. rule. For the \code{match} in the \code{leaf} function, we refer to
  1098. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1099. nonterminal has four alternatives, so the \code{match} has four
  1100. \racket{clauses}\python{cases}. The pattern in each
  1101. \racket{clause}\python{case} corresponds to the right-hand side of a
  1102. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1103. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1104. translating from grammars to patterns, replace nonterminals such as
  1105. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1106. \code{e2}).
  1107. \section{Recursive Functions}
  1108. \label{sec:recursion}
  1109. \index{subject}{recursive function}
  1110. Programs are inherently recursive. For example, an expression is often
  1111. made of smaller expressions. Thus, the natural way to process an
  1112. entire program is to use a recursive function. As a first example of
  1113. such a recursive function, we define the function \code{is\_exp} as
  1114. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1115. value and determine whether or not it is an expression in \LangInt{}.
  1116. %
  1117. We say that a function is defined by \emph{structural recursion} if
  1118. it is defined using a sequence of match \racket{clauses}\python{cases}
  1119. that correspond to a grammar and the body of each
  1120. \racket{clause}\python{case} makes a recursive call on each child
  1121. node.\footnote{This principle of structuring code according to the
  1122. data definition is advocated in the book \emph{How to Design
  1123. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1124. second function, named \code{stmt}, that recognizes whether a value
  1125. is a \LangInt{} statement.} \python{Finally, }
  1126. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1127. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1128. In general, we can write one recursive function to handle each
  1129. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1130. two examples at the bottom of the figure, the first is in
  1131. \LangInt{} and the second is not.
  1132. \begin{figure}[tp]
  1133. \begin{tcolorbox}[colback=white]
  1134. {\if\edition\racketEd
  1135. \begin{lstlisting}
  1136. (define (is_exp ast)
  1137. (match ast
  1138. [(Int n) #t]
  1139. [(Prim 'read '()) #t]
  1140. [(Prim '- (list e)) (is_exp e)]
  1141. [(Prim '+ (list e1 e2))
  1142. (and (is_exp e1) (is_exp e2))]
  1143. [(Prim '- (list e1 e2))
  1144. (and (is_exp e1) (is_exp e2))]
  1145. [else #f]))
  1146. (define (is_Lint ast)
  1147. (match ast
  1148. [(Program '() e) (is_exp e)]
  1149. [else #f]))
  1150. (is_Lint (Program '() ast1_1)
  1151. (is_Lint (Program '()
  1152. (Prim '* (list (Prim 'read '())
  1153. (Prim '+ (list (Int 8)))))))
  1154. \end{lstlisting}
  1155. \fi}
  1156. {\if\edition\pythonEd\pythonColor
  1157. \begin{lstlisting}
  1158. def is_exp(e):
  1159. match e:
  1160. case Constant(n):
  1161. return True
  1162. case Call(Name('input_int'), []):
  1163. return True
  1164. case UnaryOp(USub(), e1):
  1165. return is_exp(e1)
  1166. case BinOp(e1, Add(), e2):
  1167. return is_exp(e1) and is_exp(e2)
  1168. case BinOp(e1, Sub(), e2):
  1169. return is_exp(e1) and is_exp(e2)
  1170. case _:
  1171. return False
  1172. def stmt(s):
  1173. match s:
  1174. case Expr(Call(Name('print'), [e])):
  1175. return is_exp(e)
  1176. case Expr(e):
  1177. return is_exp(e)
  1178. case _:
  1179. return False
  1180. def is_Lint(p):
  1181. match p:
  1182. case Module(body):
  1183. return all([stmt(s) for s in body])
  1184. case _:
  1185. return False
  1186. print(is_Lint(Module([Expr(ast1_1)])))
  1187. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1188. UnaryOp(Add(), Constant(8))))])))
  1189. \end{lstlisting}
  1190. \fi}
  1191. \end{tcolorbox}
  1192. \caption{Example of recursive functions for \LangInt{}. These functions
  1193. recognize whether an AST is in \LangInt{}.}
  1194. \label{fig:exp-predicate}
  1195. \end{figure}
  1196. %% You may be tempted to merge the two functions into one, like this:
  1197. %% \begin{center}
  1198. %% \begin{minipage}{0.5\textwidth}
  1199. %% \begin{lstlisting}
  1200. %% (define (Lint ast)
  1201. %% (match ast
  1202. %% [(Int n) #t]
  1203. %% [(Prim 'read '()) #t]
  1204. %% [(Prim '- (list e)) (Lint e)]
  1205. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1206. %% [(Program '() e) (Lint e)]
  1207. %% [else #f]))
  1208. %% \end{lstlisting}
  1209. %% \end{minipage}
  1210. %% \end{center}
  1211. %% %
  1212. %% Sometimes such a trick will save a few lines of code, especially when
  1213. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1214. %% \emph{not} recommended because it can get you into trouble.
  1215. %% %
  1216. %% For example, the above function is subtly wrong:
  1217. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1218. %% returns true when it should return false.
  1219. \section{Interpreters}
  1220. \label{sec:interp_Lint}
  1221. \index{subject}{interpreter}
  1222. The behavior of a program is defined by the specification of the
  1223. programming language.
  1224. %
  1225. \racket{For example, the Scheme language is defined in the report by
  1226. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1227. reference manual~\citep{plt-tr}.}
  1228. %
  1229. \python{For example, the Python language is defined in the Python
  1230. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1231. %
  1232. In this book we use interpreters to specify each language that we
  1233. consider. An interpreter that is designated as the definition of a
  1234. language is called a \emph{definitional
  1235. interpreter}~\citep{reynolds72:_def_interp}.
  1236. \index{subject}{definitional interpreter} We warm up by creating a
  1237. definitional interpreter for the \LangInt{} language. This interpreter
  1238. serves as a second example of structural recursion. The definition of the
  1239. \code{interp\_Lint} function is shown in
  1240. figure~\ref{fig:interp_Lint}.
  1241. %
  1242. \racket{The body of the function is a match on the input program
  1243. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1244. which in turn has one match clause per grammar rule for \LangInt{}
  1245. expressions.}
  1246. %
  1247. \python{The body of the function matches on the \code{Module} AST node
  1248. and then invokes \code{interp\_stmt} on each statement in the
  1249. module. The \code{interp\_stmt} function includes a case for each
  1250. grammar rule of the \Stmt{} nonterminal, and it calls
  1251. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1252. function includes a case for each grammar rule of the \Exp{}
  1253. nonterminal. We use several auxiliary functions such as \code{add64}
  1254. and \code{input\_int} that are defined in the support code for this book.}
  1255. \begin{figure}[tp]
  1256. \begin{tcolorbox}[colback=white]
  1257. {\if\edition\racketEd
  1258. \begin{lstlisting}
  1259. (define (interp_exp e)
  1260. (match e
  1261. [(Int n) n]
  1262. [(Prim 'read '())
  1263. (define r (read))
  1264. (cond [(fixnum? r) r]
  1265. [else (error 'interp_exp "read expected an integer" r)])]
  1266. [(Prim '- (list e))
  1267. (define v (interp_exp e))
  1268. (fx- 0 v)]
  1269. [(Prim '+ (list e1 e2))
  1270. (define v1 (interp_exp e1))
  1271. (define v2 (interp_exp e2))
  1272. (fx+ v1 v2)]
  1273. [(Prim '- (list e1 e2))
  1274. (define v1 (interp_exp e1))
  1275. (define v2 (interp_exp e2))
  1276. (fx- v1 v2)]))
  1277. (define (interp_Lint p)
  1278. (match p
  1279. [(Program '() e) (interp_exp e)]))
  1280. \end{lstlisting}
  1281. \fi}
  1282. {\if\edition\pythonEd\pythonColor
  1283. \begin{lstlisting}
  1284. def interp_exp(e):
  1285. match e:
  1286. case BinOp(left, Add(), right):
  1287. l = interp_exp(left); r = interp_exp(right)
  1288. return add64(l, r)
  1289. case BinOp(left, Sub(), right):
  1290. l = interp_exp(left); r = interp_exp(right)
  1291. return sub64(l, r)
  1292. case UnaryOp(USub(), v):
  1293. return neg64(interp_exp(v))
  1294. case Constant(value):
  1295. return value
  1296. case Call(Name('input_int'), []):
  1297. return input_int()
  1298. def interp_stmt(s):
  1299. match s:
  1300. case Expr(Call(Name('print'), [arg])):
  1301. print(interp_exp(arg))
  1302. case Expr(value):
  1303. interp_exp(value)
  1304. def interp_Lint(p):
  1305. match p:
  1306. case Module(body):
  1307. for s in body:
  1308. interp_stmt(s)
  1309. \end{lstlisting}
  1310. \fi}
  1311. \end{tcolorbox}
  1312. \caption{Interpreter for the \LangInt{} language.}
  1313. \label{fig:interp_Lint}
  1314. \end{figure}
  1315. Let us consider the result of interpreting a few \LangInt{} programs. The
  1316. following program adds two integers:
  1317. {\if\edition\racketEd
  1318. \begin{lstlisting}
  1319. (+ 10 32)
  1320. \end{lstlisting}
  1321. \fi}
  1322. {\if\edition\pythonEd\pythonColor
  1323. \begin{lstlisting}
  1324. print(10 + 32)
  1325. \end{lstlisting}
  1326. \fi}
  1327. %
  1328. \noindent The result is \key{42}, the answer to life, the universe,
  1329. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1330. the Galaxy} by Douglas Adams.}
  1331. %
  1332. We wrote this program in concrete syntax, whereas the parsed
  1333. abstract syntax is
  1334. {\if\edition\racketEd
  1335. \begin{lstlisting}
  1336. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1337. \end{lstlisting}
  1338. \fi}
  1339. {\if\edition\pythonEd\pythonColor
  1340. \begin{lstlisting}
  1341. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1342. \end{lstlisting}
  1343. \fi}
  1344. The following program demonstrates that expressions may be nested within
  1345. each other, in this case nesting several additions and negations.
  1346. {\if\edition\racketEd
  1347. \begin{lstlisting}
  1348. (+ 10 (- (+ 12 20)))
  1349. \end{lstlisting}
  1350. \fi}
  1351. {\if\edition\pythonEd\pythonColor
  1352. \begin{lstlisting}
  1353. print(10 + -(12 + 20))
  1354. \end{lstlisting}
  1355. \fi}
  1356. %
  1357. \noindent What is the result of this program?
  1358. {\if\edition\racketEd
  1359. As mentioned previously, the \LangInt{} language does not support
  1360. arbitrarily large integers but only $63$-bit integers, so we
  1361. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1362. in Racket.
  1363. Suppose that
  1364. \[
  1365. n = 999999999999999999
  1366. \]
  1367. which indeed fits in $63$ bits. What happens when we run the
  1368. following program in our interpreter?
  1369. \begin{lstlisting}
  1370. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1371. \end{lstlisting}
  1372. It produces the following error:
  1373. \begin{lstlisting}
  1374. fx+: result is not a fixnum
  1375. \end{lstlisting}
  1376. We establish the convention that if running the definitional
  1377. interpreter on a program produces an error, then the meaning of that
  1378. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1379. error is a \code{trapped-error}. A compiler for the language is under
  1380. no obligation regarding programs with unspecified behavior; it does
  1381. not have to produce an executable, and if it does, that executable can
  1382. do anything. On the other hand, if the error is a
  1383. \code{trapped-error}, then the compiler must produce an executable and
  1384. it is required to report that an error occurred. To signal an error,
  1385. exit with a return code of \code{255}. The interpreters in chapters
  1386. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1387. \code{trapped-error}.
  1388. \fi}
  1389. % TODO: how to deal with too-large integers in the Python interpreter?
  1390. %% This convention applies to the languages defined in this
  1391. %% book, as a way to simplify the student's task of implementing them,
  1392. %% but this convention is not applicable to all programming languages.
  1393. %%
  1394. The last feature of the \LangInt{} language, the \READOP{} operation,
  1395. prompts the user of the program for an integer. Recall that program
  1396. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1397. \code{8}. So, if we run {\if\edition\racketEd
  1398. \begin{lstlisting}
  1399. (interp_Lint (Program '() ast1_1))
  1400. \end{lstlisting}
  1401. \fi}
  1402. {\if\edition\pythonEd\pythonColor
  1403. \begin{lstlisting}
  1404. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1405. \end{lstlisting}
  1406. \fi}
  1407. \noindent and if the input is \code{50}, the result is \code{42}.
  1408. We include the \READOP{} operation in \LangInt{} so that a clever
  1409. student cannot implement a compiler for \LangInt{} that simply runs
  1410. the interpreter during compilation to obtain the output and then
  1411. generates the trivial code to produce the output.\footnote{Yes, a
  1412. clever student did this in the first instance of this course!}
  1413. The job of a compiler is to translate a program in one language into a
  1414. program in another language so that the output program behaves the
  1415. same way as the input program. This idea is depicted in the
  1416. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1417. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1418. Given a compiler that translates from language $\mathcal{L}_1$ to
  1419. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1420. compiler must translate it into some program $P_2$ such that
  1421. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1422. same input $i$ yields the same output $o$.
  1423. \begin{equation} \label{eq:compile-correct}
  1424. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1425. \node (p1) at (0, 0) {$P_1$};
  1426. \node (p2) at (3, 0) {$P_2$};
  1427. \node (o) at (3, -2.5) {$o$};
  1428. \path[->] (p1) edge [above] node {compile} (p2);
  1429. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1430. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1431. \end{tikzpicture}
  1432. \end{equation}
  1433. \python{We establish the convention that if running the definitional
  1434. interpreter on a program produces an error, then the meaning of that
  1435. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1436. unless the exception raised is a \code{TrappedError}. A compiler for
  1437. the language is under no obligation regarding programs with
  1438. unspecified behavior; it does not have to produce an executable, and
  1439. if it does, that executable can do anything. On the other hand, if
  1440. the error is a \code{TrappedError}, then the compiler must produce
  1441. an executable and it is required to report that an error
  1442. occurred. To signal an error, exit with a return code of \code{255}.
  1443. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1444. section \ref{sec:arrays} use \code{TrappedError}.}
  1445. In the next section we see our first example of a compiler.
  1446. \section{Example Compiler: A Partial Evaluator}
  1447. \label{sec:partial-evaluation}
  1448. In this section we consider a compiler that translates \LangInt{}
  1449. programs into \LangInt{} programs that may be more efficient. The
  1450. compiler eagerly computes the parts of the program that do not depend
  1451. on any inputs, a process known as \emph{partial
  1452. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1453. For example, given the following program
  1454. {\if\edition\racketEd
  1455. \begin{lstlisting}
  1456. (+ (read) (- (+ 5 3)))
  1457. \end{lstlisting}
  1458. \fi}
  1459. {\if\edition\pythonEd\pythonColor
  1460. \begin{lstlisting}
  1461. print(input_int() + -(5 + 3) )
  1462. \end{lstlisting}
  1463. \fi}
  1464. \noindent our compiler translates it into the program
  1465. {\if\edition\racketEd
  1466. \begin{lstlisting}
  1467. (+ (read) -8)
  1468. \end{lstlisting}
  1469. \fi}
  1470. {\if\edition\pythonEd\pythonColor
  1471. \begin{lstlisting}
  1472. print(input_int() + -8)
  1473. \end{lstlisting}
  1474. \fi}
  1475. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1476. evaluator for the \LangInt{} language. The output of the partial evaluator
  1477. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1478. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1479. whereas the code for partially evaluating the negation and addition
  1480. operations is factored into three auxiliary functions:
  1481. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1482. functions is the output of partially evaluating the children.
  1483. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1484. arguments are integers and if they are, perform the appropriate
  1485. arithmetic. Otherwise, they create an AST node for the arithmetic
  1486. operation.
  1487. \begin{figure}[tp]
  1488. \begin{tcolorbox}[colback=white]
  1489. {\if\edition\racketEd
  1490. \begin{lstlisting}
  1491. (define (pe_neg r)
  1492. (match r
  1493. [(Int n) (Int (fx- 0 n))]
  1494. [else (Prim '- (list r))]))
  1495. (define (pe_add r1 r2)
  1496. (match* (r1 r2)
  1497. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1498. [(_ _) (Prim '+ (list r1 r2))]))
  1499. (define (pe_sub r1 r2)
  1500. (match* (r1 r2)
  1501. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1502. [(_ _) (Prim '- (list r1 r2))]))
  1503. (define (pe_exp e)
  1504. (match e
  1505. [(Int n) (Int n)]
  1506. [(Prim 'read '()) (Prim 'read '())]
  1507. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1508. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1509. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1510. (define (pe_Lint p)
  1511. (match p
  1512. [(Program '() e) (Program '() (pe_exp e))]))
  1513. \end{lstlisting}
  1514. \fi}
  1515. {\if\edition\pythonEd\pythonColor
  1516. \begin{lstlisting}
  1517. def pe_neg(r):
  1518. match r:
  1519. case Constant(n):
  1520. return Constant(neg64(n))
  1521. case _:
  1522. return UnaryOp(USub(), r)
  1523. def pe_add(r1, r2):
  1524. match (r1, r2):
  1525. case (Constant(n1), Constant(n2)):
  1526. return Constant(add64(n1, n2))
  1527. case _:
  1528. return BinOp(r1, Add(), r2)
  1529. def pe_sub(r1, r2):
  1530. match (r1, r2):
  1531. case (Constant(n1), Constant(n2)):
  1532. return Constant(sub64(n1, n2))
  1533. case _:
  1534. return BinOp(r1, Sub(), r2)
  1535. def pe_exp(e):
  1536. match e:
  1537. case BinOp(left, Add(), right):
  1538. return pe_add(pe_exp(left), pe_exp(right))
  1539. case BinOp(left, Sub(), right):
  1540. return pe_sub(pe_exp(left), pe_exp(right))
  1541. case UnaryOp(USub(), v):
  1542. return pe_neg(pe_exp(v))
  1543. case Constant(value):
  1544. return e
  1545. case Call(Name('input_int'), []):
  1546. return e
  1547. def pe_stmt(s):
  1548. match s:
  1549. case Expr(Call(Name('print'), [arg])):
  1550. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1551. case Expr(value):
  1552. return Expr(pe_exp(value))
  1553. def pe_P_int(p):
  1554. match p:
  1555. case Module(body):
  1556. new_body = [pe_stmt(s) for s in body]
  1557. return Module(new_body)
  1558. \end{lstlisting}
  1559. \fi}
  1560. \end{tcolorbox}
  1561. \caption{A partial evaluator for \LangInt{}.}
  1562. \label{fig:pe-arith}
  1563. \end{figure}
  1564. To gain some confidence that the partial evaluator is correct, we can
  1565. test whether it produces programs that produce the same result as the
  1566. input programs. That is, we can test whether it satisfies the diagram
  1567. of \eqref{eq:compile-correct}.
  1568. %
  1569. {\if\edition\racketEd
  1570. The following code runs the partial evaluator on several examples and
  1571. tests the output program. The \texttt{parse-program} and
  1572. \texttt{assert} functions are defined in
  1573. appendix~\ref{appendix:utilities}.\\
  1574. \begin{minipage}{1.0\textwidth}
  1575. \begin{lstlisting}
  1576. (define (test_pe p)
  1577. (assert "testing pe_Lint"
  1578. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1579. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1580. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1581. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1582. \end{lstlisting}
  1583. \end{minipage}
  1584. \fi}
  1585. % TODO: python version of testing the PE
  1586. \begin{exercise}\normalfont\normalsize
  1587. Create three programs in the \LangInt{} language and test whether
  1588. partially evaluating them with \code{pe\_Lint} and then
  1589. interpreting them with \code{interp\_Lint} gives the same result
  1590. as directly interpreting them with \code{interp\_Lint}.
  1591. \end{exercise}
  1592. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1593. \chapter{Integers and Variables}
  1594. \label{ch:Lvar}
  1595. \setcounter{footnote}{0}
  1596. This chapter covers compiling a subset of
  1597. \racket{Racket}\python{Python} to x86-64 assembly
  1598. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1599. integer arithmetic and local variables. We often refer to x86-64
  1600. simply as x86. The chapter first describes the \LangVar{} language
  1601. (section~\ref{sec:s0}) and then introduces x86 assembly
  1602. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1603. discuss only the instructions needed for compiling \LangVar{}. We
  1604. introduce more x86 instructions in subsequent chapters. After
  1605. introducing \LangVar{} and x86, we reflect on their differences and
  1606. create a plan to break down the translation from \LangVar{} to x86
  1607. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1608. the chapter gives detailed hints regarding each step. We aim to give
  1609. enough hints that the well-prepared reader, together with a few
  1610. friends, can implement a compiler from \LangVar{} to x86 in a short
  1611. time. To suggest the scale of this first compiler, we note that the
  1612. instructor solution for the \LangVar{} compiler is approximately
  1613. \racket{500}\python{300} lines of code.
  1614. \section{The \LangVar{} Language}
  1615. \label{sec:s0}
  1616. \index{subject}{variable}
  1617. The \LangVar{} language extends the \LangInt{} language with
  1618. variables. The concrete syntax of the \LangVar{} language is defined
  1619. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1620. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1621. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1622. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1623. \key{-} is a unary operator, and \key{+} is a binary operator.
  1624. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1625. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1626. the top of the program.
  1627. %% The $\itm{info}$
  1628. %% field of the \key{Program} structure contains an \emph{association
  1629. %% list} (a list of key-value pairs) that is used to communicate
  1630. %% auxiliary data from one compiler pass the next.
  1631. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1632. exhibit several compilation techniques.
  1633. \newcommand{\LvarGrammarRacket}{
  1634. \begin{array}{rcl}
  1635. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1636. \end{array}
  1637. }
  1638. \newcommand{\LvarASTRacket}{
  1639. \begin{array}{rcl}
  1640. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1641. \end{array}
  1642. }
  1643. \newcommand{\LvarGrammarPython}{
  1644. \begin{array}{rcl}
  1645. \Exp &::=& \Var{} \\
  1646. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1647. \end{array}
  1648. }
  1649. \newcommand{\LvarASTPython}{
  1650. \begin{array}{rcl}
  1651. \Exp{} &::=& \VAR{\Var{}} \\
  1652. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1653. \end{array}
  1654. }
  1655. \begin{figure}[tp]
  1656. \centering
  1657. \begin{tcolorbox}[colback=white]
  1658. {\if\edition\racketEd
  1659. \[
  1660. \begin{array}{l}
  1661. \gray{\LintGrammarRacket{}} \\ \hline
  1662. \LvarGrammarRacket{} \\
  1663. \begin{array}{rcl}
  1664. \LangVarM{} &::=& \Exp
  1665. \end{array}
  1666. \end{array}
  1667. \]
  1668. \fi}
  1669. {\if\edition\pythonEd\pythonColor
  1670. \[
  1671. \begin{array}{l}
  1672. \gray{\LintGrammarPython} \\ \hline
  1673. \LvarGrammarPython \\
  1674. \begin{array}{rcl}
  1675. \LangVarM{} &::=& \Stmt^{*}
  1676. \end{array}
  1677. \end{array}
  1678. \]
  1679. \fi}
  1680. \end{tcolorbox}
  1681. \caption{The concrete syntax of \LangVar{}.}
  1682. \label{fig:Lvar-concrete-syntax}
  1683. \end{figure}
  1684. \begin{figure}[tp]
  1685. \centering
  1686. \begin{tcolorbox}[colback=white]
  1687. {\if\edition\racketEd
  1688. \[
  1689. \begin{array}{l}
  1690. \gray{\LintASTRacket{}} \\ \hline
  1691. \LvarASTRacket \\
  1692. \begin{array}{rcl}
  1693. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1694. \end{array}
  1695. \end{array}
  1696. \]
  1697. \fi}
  1698. {\if\edition\pythonEd\pythonColor
  1699. \[
  1700. \begin{array}{l}
  1701. \gray{\LintASTPython}\\ \hline
  1702. \LvarASTPython \\
  1703. \begin{array}{rcl}
  1704. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1705. \end{array}
  1706. \end{array}
  1707. \]
  1708. \fi}
  1709. \end{tcolorbox}
  1710. \caption{The abstract syntax of \LangVar{}.}
  1711. \label{fig:Lvar-syntax}
  1712. \end{figure}
  1713. {\if\edition\racketEd
  1714. Let us dive further into the syntax and semantics of the \LangVar{}
  1715. language. The \key{let} feature defines a variable for use within its
  1716. body and initializes the variable with the value of an expression.
  1717. The abstract syntax for \key{let} is shown in
  1718. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1719. \begin{lstlisting}
  1720. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1721. \end{lstlisting}
  1722. For example, the following program initializes \code{x} to $32$ and then
  1723. evaluates the body \code{(+ 10 x)}, producing $42$.
  1724. \begin{lstlisting}
  1725. (let ([x (+ 12 20)]) (+ 10 x))
  1726. \end{lstlisting}
  1727. \fi}
  1728. %
  1729. {\if\edition\pythonEd\pythonColor
  1730. %
  1731. The \LangVar{} language includes an assignment statement, which defines a
  1732. variable for use in later statements and initializes the variable with
  1733. the value of an expression. The abstract syntax for assignment is
  1734. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1735. assignment is \index{subject}{Assign@\texttt{Assign}}
  1736. \begin{lstlisting}
  1737. |$\itm{var}$| = |$\itm{exp}$|
  1738. \end{lstlisting}
  1739. For example, the following program initializes the variable \code{x}
  1740. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1741. \begin{lstlisting}
  1742. x = 12 + 20
  1743. print(10 + x)
  1744. \end{lstlisting}
  1745. \fi}
  1746. {\if\edition\racketEd
  1747. %
  1748. When there are multiple \key{let}s for the same variable, the closest
  1749. enclosing \key{let} is used. That is, variable definitions overshadow
  1750. prior definitions. Consider the following program with two \key{let}s
  1751. that define two variables named \code{x}. Can you figure out the
  1752. result?
  1753. \begin{lstlisting}
  1754. (let ([x 32]) (+ (let ([x 10]) x) x))
  1755. \end{lstlisting}
  1756. For the purposes of depicting which variable occurrences correspond to
  1757. which definitions, the following shows the \code{x}'s annotated with
  1758. subscripts to distinguish them. Double-check that your answer for the
  1759. previous program is the same as your answer for this annotated version
  1760. of the program.
  1761. \begin{lstlisting}
  1762. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1763. \end{lstlisting}
  1764. The initializing expression is always evaluated before the body of the
  1765. \key{let}, so in the following, the \key{read} for \code{x} is
  1766. performed before the \key{read} for \code{y}. Given the input
  1767. $52$ then $10$, the following produces $42$ (not $-42$).
  1768. \begin{lstlisting}
  1769. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1770. \end{lstlisting}
  1771. \fi}
  1772. \subsection{Extensible Interpreters via Method Overriding}
  1773. \label{sec:extensible-interp}
  1774. \index{subject}{method overriding}
  1775. To prepare for discussing the interpreter of \LangVar{}, we explain
  1776. why we implement it in an object-oriented style. Throughout this book
  1777. we define many interpreters, one for each language that we
  1778. study. Because each language builds on the prior one, there is a lot
  1779. of commonality between these interpreters. We want to write down the
  1780. common parts just once instead of many times. A naive interpreter for
  1781. \LangVar{} would handle the \racket{cases for variables and
  1782. \code{let}} \python{case for variables} but dispatch to an
  1783. interpreter for \LangInt{} in the rest of the cases. The following
  1784. code sketches this idea. (We explain the \code{env} parameter in
  1785. section~\ref{sec:interp-Lvar}.)
  1786. \begin{center}
  1787. {\if\edition\racketEd
  1788. \begin{minipage}{0.45\textwidth}
  1789. \begin{lstlisting}
  1790. (define ((interp_Lint env) e)
  1791. (match e
  1792. [(Prim '- (list e1))
  1793. (fx- 0 ((interp_Lint env) e1))]
  1794. ...))
  1795. \end{lstlisting}
  1796. \end{minipage}
  1797. \begin{minipage}{0.45\textwidth}
  1798. \begin{lstlisting}
  1799. (define ((interp_Lvar env) e)
  1800. (match e
  1801. [(Var x)
  1802. (dict-ref env x)]
  1803. [(Let x e body)
  1804. (define v ((interp_Lvar env) e))
  1805. (define env^ (dict-set env x v))
  1806. ((interp_Lvar env^) body)]
  1807. [else ((interp_Lint env) e)]))
  1808. \end{lstlisting}
  1809. \end{minipage}
  1810. \fi}
  1811. {\if\edition\pythonEd\pythonColor
  1812. \begin{minipage}{0.45\textwidth}
  1813. \begin{lstlisting}
  1814. def interp_Lint(e, env):
  1815. match e:
  1816. case UnaryOp(USub(), e1):
  1817. return - interp_Lint(e1, env)
  1818. ...
  1819. \end{lstlisting}
  1820. \end{minipage}
  1821. \begin{minipage}{0.45\textwidth}
  1822. \begin{lstlisting}
  1823. def interp_Lvar(e, env):
  1824. match e:
  1825. case Name(id):
  1826. return env[id]
  1827. case _:
  1828. return interp_Lint(e, env)
  1829. \end{lstlisting}
  1830. \end{minipage}
  1831. \fi}
  1832. \end{center}
  1833. The problem with this naive approach is that it does not handle
  1834. situations in which an \LangVar{} feature, such as a variable, is
  1835. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1836. in the following program.
  1837. {\if\edition\racketEd
  1838. \begin{lstlisting}
  1839. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1840. \end{lstlisting}
  1841. \fi}
  1842. {\if\edition\pythonEd\pythonColor
  1843. \begin{minipage}{1.0\textwidth}
  1844. \begin{lstlisting}
  1845. y = 10
  1846. print(-y)
  1847. \end{lstlisting}
  1848. \end{minipage}
  1849. \fi}
  1850. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1851. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1852. then it recursively calls \code{interp\_Lint} again on its argument.
  1853. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1854. an error!
  1855. To make our interpreters extensible we need something called
  1856. \emph{open recursion}\index{subject}{open recursion}, in which the
  1857. tying of the recursive knot is delayed until the functions are
  1858. composed. Object-oriented languages provide open recursion via method
  1859. overriding. The following code uses
  1860. method overriding to interpret \LangInt{} and \LangVar{} using
  1861. %
  1862. \racket{the
  1863. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1864. \index{subject}{class} feature of Racket.}%
  1865. %
  1866. \python{a Python \code{class} definition.}
  1867. %
  1868. We define one class for each language and define a method for
  1869. interpreting expressions inside each class. The class for \LangVar{}
  1870. inherits from the class for \LangInt{}, and the method
  1871. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1872. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1873. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1874. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1875. \code{interp\_exp} in \LangInt{}.
  1876. \begin{center}
  1877. \hspace{-20pt}
  1878. {\if\edition\racketEd
  1879. \begin{minipage}{0.45\textwidth}
  1880. \begin{lstlisting}
  1881. (define interp-Lint-class
  1882. (class object%
  1883. (define/public ((interp_exp env) e)
  1884. (match e
  1885. [(Prim '- (list e))
  1886. (fx- 0 ((interp_exp env) e))]
  1887. ...))
  1888. ...))
  1889. \end{lstlisting}
  1890. \end{minipage}
  1891. \begin{minipage}{0.45\textwidth}
  1892. \begin{lstlisting}
  1893. (define interp-Lvar-class
  1894. (class interp-Lint-class
  1895. (define/override ((interp_exp env) e)
  1896. (match e
  1897. [(Var x)
  1898. (dict-ref env x)]
  1899. [(Let x e body)
  1900. (define v ((interp_exp env) e))
  1901. (define env^ (dict-set env x v))
  1902. ((interp_exp env^) body)]
  1903. [else
  1904. (super (interp_exp env) e)]))
  1905. ...
  1906. ))
  1907. \end{lstlisting}
  1908. \end{minipage}
  1909. \fi}
  1910. {\if\edition\pythonEd\pythonColor
  1911. \begin{minipage}{0.45\textwidth}
  1912. \begin{lstlisting}
  1913. class InterpLint:
  1914. def interp_exp(e):
  1915. match e:
  1916. case UnaryOp(USub(), e1):
  1917. return neg64(self.interp_exp(e1))
  1918. ...
  1919. ...
  1920. \end{lstlisting}
  1921. \end{minipage}
  1922. \begin{minipage}{0.45\textwidth}
  1923. \begin{lstlisting}
  1924. def InterpLvar(InterpLint):
  1925. def interp_exp(e):
  1926. match e:
  1927. case Name(id):
  1928. return env[id]
  1929. case _:
  1930. return super().interp_exp(e)
  1931. ...
  1932. \end{lstlisting}
  1933. \end{minipage}
  1934. \fi}
  1935. \end{center}
  1936. We return to the troublesome example, repeated here:
  1937. {\if\edition\racketEd
  1938. \begin{lstlisting}
  1939. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1940. \end{lstlisting}
  1941. \fi}
  1942. {\if\edition\pythonEd\pythonColor
  1943. \begin{lstlisting}
  1944. y = 10
  1945. print(-y)
  1946. \end{lstlisting}
  1947. \fi}
  1948. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1949. \racket{on this expression,}
  1950. \python{on the \code{-y} expression,}
  1951. %
  1952. which we call \code{e0}, by creating an object of the \LangVar{} class
  1953. and calling the \code{interp\_exp} method
  1954. {\if\edition\racketEd
  1955. \begin{lstlisting}
  1956. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1957. \end{lstlisting}
  1958. \fi}
  1959. {\if\edition\pythonEd\pythonColor
  1960. \begin{lstlisting}
  1961. InterpLvar().interp_exp(e0)
  1962. \end{lstlisting}
  1963. \fi}
  1964. \noindent To process the \code{-} operator, the default case of
  1965. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1966. method in \LangInt{}. But then for the recursive method call, it
  1967. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1968. \code{Var} node is handled correctly. Thus, method overriding gives us
  1969. the open recursion that we need to implement our interpreters in an
  1970. extensible way.
  1971. \subsection{Definitional Interpreter for \LangVar{}}
  1972. \label{sec:interp-Lvar}
  1973. Having justified the use of classes and methods to implement
  1974. interpreters, we revisit the definitional interpreter for \LangInt{}
  1975. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1976. create an interpreter for \LangVar{}, shown in
  1977. figure~\ref{fig:interp-Lvar}.
  1978. %
  1979. \python{We change the \code{interp\_stmt} method in the interpreter
  1980. for \LangInt{} to take two extra parameters named \code{env}, which
  1981. we discuss in the next paragraph, and \code{cont} for
  1982. \emph{continuation}, which is the technical name for what comes
  1983. after a particular point in a program. The \code{cont} parameter is
  1984. the list of statements that that follow the current statement. Note
  1985. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  1986. statement and passes the rest of the statements as the argument for
  1987. \code{cont}. This organization enables each statement to decide what
  1988. if anything should be evaluated after it, for example, allowing a
  1989. \code{return} statement to exit early from a function (see
  1990. Chapter~\ref{ch:Lfun}).}
  1991. The interpreter for \LangVar{} adds two new cases for
  1992. variables and \racket{\key{let}}\python{assignment}. For
  1993. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1994. value bound to a variable to all the uses of the variable. To
  1995. accomplish this, we maintain a mapping from variables to values called
  1996. an \emph{environment}\index{subject}{environment}.
  1997. %
  1998. We use
  1999. %
  2000. \racket{an association list (alist) }%
  2001. %
  2002. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2003. %
  2004. to represent the environment.
  2005. %
  2006. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2007. and the \code{racket/dict} package.}
  2008. %
  2009. The \code{interp\_exp} function takes the current environment,
  2010. \code{env}, as an extra parameter. When the interpreter encounters a
  2011. variable, it looks up the corresponding value in the environment. If
  2012. the variable is not in the environment (because the variable was not
  2013. defined) then the lookup will fail and the interpreter will
  2014. halt with an error. Recall that the compiler is not obligated to
  2015. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2016. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2017. prohibit access to undefined variables.}
  2018. %
  2019. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2020. initializing expression, extends the environment with the result
  2021. value bound to the variable, using \code{dict-set}, then evaluates
  2022. the body of the \key{Let}.}
  2023. %
  2024. \python{When the interpreter encounters an assignment, it evaluates
  2025. the initializing expression and then associates the resulting value
  2026. with the variable in the environment.}
  2027. \begin{figure}[tp]
  2028. \begin{tcolorbox}[colback=white]
  2029. {\if\edition\racketEd
  2030. \begin{lstlisting}
  2031. (define interp-Lint-class
  2032. (class object%
  2033. (super-new)
  2034. (define/public ((interp_exp env) e)
  2035. (match e
  2036. [(Int n) n]
  2037. [(Prim 'read '())
  2038. (define r (read))
  2039. (cond [(fixnum? r) r]
  2040. [else (error 'interp_exp "expected an integer" r)])]
  2041. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2042. [(Prim '+ (list e1 e2))
  2043. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2044. [(Prim '- (list e1 e2))
  2045. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2046. (define/public (interp_program p)
  2047. (match p
  2048. [(Program '() e) ((interp_exp '()) e)]))
  2049. ))
  2050. \end{lstlisting}
  2051. \fi}
  2052. {\if\edition\pythonEd\pythonColor
  2053. \begin{lstlisting}
  2054. class InterpLint:
  2055. def interp_exp(self, e, env):
  2056. match e:
  2057. case BinOp(left, Add(), right):
  2058. l = self.interp_exp(left, env)
  2059. r = self.interp_exp(right, env)
  2060. return add64(l, r)
  2061. case BinOp(left, Sub(), right):
  2062. l = self.interp_exp(left, env)
  2063. r = self.interp_exp(right, env)
  2064. return sub64(l, r)
  2065. case UnaryOp(USub(), v):
  2066. return neg64(self.interp_exp(v, env))
  2067. case Constant(value):
  2068. return value
  2069. case Call(Name('input_int'), []):
  2070. return int(input())
  2071. def interp_stmt(self, s, env, cont):
  2072. match s:
  2073. case Expr(Call(Name('print'), [arg])):
  2074. val = self.interp_exp(arg, env)
  2075. print(val, end='')
  2076. return self.interp_stmts(cont, env)
  2077. case Expr(value):
  2078. self.interp_exp(value, env)
  2079. return self.interp_stmts(cont, env)
  2080. case _:
  2081. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2082. def interp_stmts(self, ss, env):
  2083. match ss:
  2084. case []:
  2085. return 0
  2086. case [s, *ss]:
  2087. return self.interp_stmt(s, env, ss)
  2088. def interp(self, p):
  2089. match p:
  2090. case Module(body):
  2091. self.interp_stmts(body, {})
  2092. def interp_Lint(p):
  2093. return InterpLint().interp(p)
  2094. \end{lstlisting}
  2095. \fi}
  2096. \end{tcolorbox}
  2097. \caption{Interpreter for \LangInt{} as a class.}
  2098. \label{fig:interp-Lint-class}
  2099. \end{figure}
  2100. \begin{figure}[tp]
  2101. \begin{tcolorbox}[colback=white]
  2102. {\if\edition\racketEd
  2103. \begin{lstlisting}
  2104. (define interp-Lvar-class
  2105. (class interp-Lint-class
  2106. (super-new)
  2107. (define/override ((interp_exp env) e)
  2108. (match e
  2109. [(Var x) (dict-ref env x)]
  2110. [(Let x e body)
  2111. (define new-env (dict-set env x ((interp_exp env) e)))
  2112. ((interp_exp new-env) body)]
  2113. [else ((super interp_exp env) e)]))
  2114. ))
  2115. (define (interp_Lvar p)
  2116. (send (new interp-Lvar-class) interp_program p))
  2117. \end{lstlisting}
  2118. \fi}
  2119. {\if\edition\pythonEd\pythonColor
  2120. \begin{lstlisting}
  2121. class InterpLvar(InterpLint):
  2122. def interp_exp(self, e, env):
  2123. match e:
  2124. case Name(id):
  2125. return env[id]
  2126. case _:
  2127. return super().interp_exp(e, env)
  2128. def interp_stmt(self, s, env, cont):
  2129. match s:
  2130. case Assign([lhs], value):
  2131. env[lhs.id] = self.interp_exp(value, env)
  2132. return self.interp_stmts(cont, env)
  2133. case _:
  2134. return super().interp_stmt(s, env, cont)
  2135. def interp_Lvar(p):
  2136. return InterpLvar().interp(p)
  2137. \end{lstlisting}
  2138. \fi}
  2139. \end{tcolorbox}
  2140. \caption{Interpreter for the \LangVar{} language.}
  2141. \label{fig:interp-Lvar}
  2142. \end{figure}
  2143. {\if\edition\racketEd
  2144. \begin{figure}[tp]
  2145. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2146. \small
  2147. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2148. An \emph{association list} (called an alist) is a list of key-value pairs.
  2149. For example, we can map people to their ages with an alist
  2150. \index{subject}{alist}\index{subject}{association list}
  2151. \begin{lstlisting}[basicstyle=\ttfamily]
  2152. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2153. \end{lstlisting}
  2154. The \emph{dictionary} interface is for mapping keys to values.
  2155. Every alist implements this interface. \index{subject}{dictionary}
  2156. The package
  2157. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2158. provides many functions for working with dictionaries, such as
  2159. \begin{description}
  2160. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2161. returns the value associated with the given $\itm{key}$.
  2162. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2163. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2164. and otherwise is the same as $\itm{dict}$.
  2165. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2166. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2167. of keys and values in $\itm{dict}$. For example, the following
  2168. creates a new alist in which the ages are incremented:
  2169. \end{description}
  2170. \vspace{-10pt}
  2171. \begin{lstlisting}[basicstyle=\ttfamily]
  2172. (for/list ([(k v) (in-dict ages)])
  2173. (cons k (add1 v)))
  2174. \end{lstlisting}
  2175. \end{tcolorbox}
  2176. %\end{wrapfigure}
  2177. \caption{Association lists implement the dictionary interface.}
  2178. \label{fig:alist}
  2179. \end{figure}
  2180. \fi}
  2181. The goal for this chapter is to implement a compiler that translates
  2182. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2183. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2184. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2185. That is, they output the same integer $n$. We depict this correctness
  2186. criteria in the following diagram:
  2187. \[
  2188. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2189. \node (p1) at (0, 0) {$P_1$};
  2190. \node (p2) at (4, 0) {$P_2$};
  2191. \node (o) at (4, -2) {$n$};
  2192. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2193. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2194. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2195. \end{tikzpicture}
  2196. \]
  2197. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2198. compiling \LangVar{}.
  2199. \section{The \LangXInt{} Assembly Language}
  2200. \label{sec:x86}
  2201. \index{subject}{x86}
  2202. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2203. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2204. assembler.
  2205. %
  2206. A program begins with a \code{main} label followed by a sequence of
  2207. instructions. The \key{globl} directive makes the \key{main} procedure
  2208. externally visible so that the operating system can call it.
  2209. %
  2210. An x86 program is stored in the computer's memory. For our purposes,
  2211. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2212. values. The computer has a \emph{program counter}
  2213. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2214. \code{rip} register that points to the address of the next instruction
  2215. to be executed. For most instructions, the program counter is
  2216. incremented after the instruction is executed so that it points to the
  2217. next instruction in memory. Most x86 instructions take two operands,
  2218. each of which is an integer constant (called an \emph{immediate
  2219. value}\index{subject}{immediate value}), a
  2220. \emph{register}\index{subject}{register}, or a memory location.
  2221. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2222. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2223. && \key{r8} \MID \key{r9} \MID \key{r10}
  2224. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2225. \MID \key{r14} \MID \key{r15}}
  2226. \newcommand{\GrammarXInt}{
  2227. \begin{array}{rcl}
  2228. \Reg &::=& \allregisters{} \\
  2229. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2230. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2231. \key{subq} \; \Arg\key{,} \Arg \MID
  2232. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2233. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2234. \key{callq} \; \mathit{label} \MID
  2235. \key{retq} \MID
  2236. \key{jmp}\,\itm{label} \MID \\
  2237. && \itm{label}\key{:}\; \Instr
  2238. \end{array}
  2239. }
  2240. \begin{figure}[tp]
  2241. \begin{tcolorbox}[colback=white]
  2242. {\if\edition\racketEd
  2243. \[
  2244. \begin{array}{l}
  2245. \GrammarXInt \\
  2246. \begin{array}{lcl}
  2247. \LangXIntM{} &::= & \key{.globl main}\\
  2248. & & \key{main:} \; \Instr\ldots
  2249. \end{array}
  2250. \end{array}
  2251. \]
  2252. \fi}
  2253. {\if\edition\pythonEd\pythonColor
  2254. \[
  2255. \begin{array}{lcl}
  2256. \Reg &::=& \allregisters{} \\
  2257. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2258. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2259. \key{subq} \; \Arg\key{,} \Arg \MID
  2260. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2261. && \key{callq} \; \mathit{label} \MID
  2262. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2263. \LangXIntM{} &::= & \key{.globl main}\\
  2264. & & \key{main:} \; \Instr^{*}
  2265. \end{array}
  2266. \]
  2267. \fi}
  2268. \end{tcolorbox}
  2269. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2270. \label{fig:x86-int-concrete}
  2271. \end{figure}
  2272. A register is a special kind of variable that holds a 64-bit
  2273. value. There are 16 general-purpose registers in the computer; their
  2274. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2275. written with a percent sign, \key{\%}, followed by the register name,
  2276. for example \key{\%rax}.
  2277. An immediate value is written using the notation \key{\$}$n$ where $n$
  2278. is an integer.
  2279. %
  2280. %
  2281. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2282. which obtains the address stored in register $r$ and then adds $n$
  2283. bytes to the address. The resulting address is used to load or to store
  2284. to memory depending on whether it occurs as a source or destination
  2285. argument of an instruction.
  2286. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2287. the source $s$ and destination $d$, applies the arithmetic operation,
  2288. and then writes the result to the destination $d$. \index{subject}{instruction}
  2289. %
  2290. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2291. stores the result in $d$.
  2292. %
  2293. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2294. specified by the label, and $\key{retq}$ returns from a procedure to
  2295. its caller.
  2296. %
  2297. We discuss procedure calls in more detail further in this chapter and
  2298. in chapter~\ref{ch:Lfun}.
  2299. %
  2300. The last letter \key{q} indicates that these instructions operate on
  2301. quadwords, which are 64-bit values.
  2302. %
  2303. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2304. counter to the address of the instruction immediately after the
  2305. specified label.}
  2306. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2307. all the x86 instructions used in this book.
  2308. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2309. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2310. \lstinline{movq $10, %rax}
  2311. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2312. adds $32$ to the $10$ in \key{rax} and
  2313. puts the result, $42$, into \key{rax}.
  2314. %
  2315. The last instruction \key{retq} finishes the \key{main} function by
  2316. returning the integer in \key{rax} to the operating system. The
  2317. operating system interprets this integer as the program's exit
  2318. code. By convention, an exit code of 0 indicates that a program has
  2319. completed successfully, and all other exit codes indicate various
  2320. errors.
  2321. %
  2322. \racket{However, in this book we return the result of the program
  2323. as the exit code.}
  2324. \begin{figure}[tbp]
  2325. \begin{minipage}{0.45\textwidth}
  2326. \begin{tcolorbox}[colback=white]
  2327. \begin{lstlisting}
  2328. .globl main
  2329. main:
  2330. movq $10, %rax
  2331. addq $32, %rax
  2332. retq
  2333. \end{lstlisting}
  2334. \end{tcolorbox}
  2335. \end{minipage}
  2336. \caption{An x86 program that computes
  2337. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2338. \label{fig:p0-x86}
  2339. \end{figure}
  2340. We exhibit the use of memory for storing intermediate results in the
  2341. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2342. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2343. uses a region of memory called the \emph{procedure call stack}
  2344. (\emph{stack} for
  2345. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2346. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2347. for each procedure call. The memory layout for an individual frame is
  2348. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2349. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2350. address of the item at the top of the stack. In general, we use the
  2351. term \emph{pointer}\index{subject}{pointer} for something that
  2352. contains an address. The stack grows downward in memory, so we
  2353. increase the size of the stack by subtracting from the stack pointer.
  2354. In the context of a procedure call, the \emph{return
  2355. address}\index{subject}{return address} is the location of the
  2356. instruction that immediately follows the call instruction on the
  2357. caller side. The function call instruction, \code{callq}, pushes the
  2358. return address onto the stack prior to jumping to the procedure. The
  2359. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2360. pointer} and is used to access variables that are stored in the
  2361. frame of the current procedure call. The base pointer of the caller
  2362. is stored immediately after the return address.
  2363. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2364. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2365. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2366. $-16\key{(\%rbp)}$, and so on.
  2367. \begin{figure}[tbp]
  2368. \begin{minipage}{0.66\textwidth}
  2369. \begin{tcolorbox}[colback=white]
  2370. {\if\edition\racketEd
  2371. \begin{lstlisting}
  2372. start:
  2373. movq $10, -8(%rbp)
  2374. negq -8(%rbp)
  2375. movq -8(%rbp), %rax
  2376. addq $52, %rax
  2377. jmp conclusion
  2378. .globl main
  2379. main:
  2380. pushq %rbp
  2381. movq %rsp, %rbp
  2382. subq $16, %rsp
  2383. jmp start
  2384. conclusion:
  2385. addq $16, %rsp
  2386. popq %rbp
  2387. retq
  2388. \end{lstlisting}
  2389. \fi}
  2390. {\if\edition\pythonEd\pythonColor
  2391. \begin{lstlisting}
  2392. .globl main
  2393. main:
  2394. pushq %rbp
  2395. movq %rsp, %rbp
  2396. subq $16, %rsp
  2397. movq $10, -8(%rbp)
  2398. negq -8(%rbp)
  2399. movq -8(%rbp), %rax
  2400. addq $52, %rax
  2401. addq $16, %rsp
  2402. popq %rbp
  2403. retq
  2404. \end{lstlisting}
  2405. \fi}
  2406. \end{tcolorbox}
  2407. \end{minipage}
  2408. \caption{An x86 program that computes
  2409. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2410. \label{fig:p1-x86}
  2411. \end{figure}
  2412. \begin{figure}[tbp]
  2413. \begin{minipage}{0.66\textwidth}
  2414. \begin{tcolorbox}[colback=white]
  2415. \centering
  2416. \begin{tabular}{|r|l|} \hline
  2417. Position & Contents \\ \hline
  2418. $8$(\key{\%rbp}) & return address \\
  2419. $0$(\key{\%rbp}) & old \key{rbp} \\
  2420. $-8$(\key{\%rbp}) & variable $1$ \\
  2421. $-16$(\key{\%rbp}) & variable $2$ \\
  2422. \ldots & \ldots \\
  2423. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2424. \end{tabular}
  2425. \end{tcolorbox}
  2426. \end{minipage}
  2427. \caption{Memory layout of a frame.}
  2428. \label{fig:frame}
  2429. \end{figure}
  2430. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2431. is transferred from the operating system to the \code{main} function.
  2432. The operating system issues a \code{callq main} instruction that
  2433. pushes its return address on the stack and then jumps to
  2434. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2435. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2436. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2437. out of alignment (because the \code{callq} pushed the return address).
  2438. The first three instructions are the typical
  2439. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2440. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2441. pointer \code{rsp} and then saves the base pointer of the caller at
  2442. address \code{rsp} on the stack. The next instruction \code{movq
  2443. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2444. which is pointing to the location of the old base pointer. The
  2445. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2446. make enough room for storing variables. This program needs one
  2447. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2448. 16-byte-aligned, and then we are ready to make calls to other functions.
  2449. \racket{The last instruction of the prelude is \code{jmp start}, which
  2450. transfers control to the instructions that were generated from the
  2451. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2452. \racket{The first instruction under the \code{start} label is}
  2453. %
  2454. \python{The first instruction after the prelude is}
  2455. %
  2456. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2457. %
  2458. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2459. $1$ to $-10$.
  2460. %
  2461. The next instruction moves the $-10$ from variable $1$ into the
  2462. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2463. the value in \code{rax}, updating its contents to $42$.
  2464. \racket{The three instructions under the label \code{conclusion} are the
  2465. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2466. %
  2467. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2468. \code{main} function consists of the last three instructions.}
  2469. %
  2470. The first two restore the \code{rsp} and \code{rbp} registers to their
  2471. states at the beginning of the procedure. In particular,
  2472. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2473. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2474. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2475. \key{retq}, jumps back to the procedure that called this one and adds
  2476. $8$ to the stack pointer.
  2477. Our compiler needs a convenient representation for manipulating x86
  2478. programs, so we define an abstract syntax for x86, shown in
  2479. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2480. \LangXInt{}.
  2481. %
  2482. {\if\edition\pythonEd\pythonColor%
  2483. The main difference between this and the concrete syntax of \LangXInt{}
  2484. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2485. names, and register names are explicitly represented by strings.
  2486. \fi} %
  2487. {\if\edition\racketEd
  2488. The main difference between this and the concrete syntax of \LangXInt{}
  2489. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2490. front of every instruction. Instead instructions are grouped into
  2491. \emph{basic blocks}\index{subject}{basic block} with a
  2492. label associated with every basic block; this is why the \key{X86Program}
  2493. struct includes an alist mapping labels to basic blocks. The reason for this
  2494. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2495. introduce conditional branching. The \code{Block} structure includes
  2496. an $\itm{info}$ field that is not needed in this chapter but becomes
  2497. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2498. $\itm{info}$ field should contain an empty list.
  2499. \fi}
  2500. %
  2501. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2502. node includes an integer for representing the arity of the function,
  2503. that is, the number of arguments, which is helpful to know during
  2504. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2505. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2506. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2507. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2508. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2509. \MID \skey{r14} \MID \skey{r15}}
  2510. \newcommand{\ASTXIntRacket}{
  2511. \begin{array}{lcl}
  2512. \Reg &::=& \allregisters{} \\
  2513. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2514. \MID \DEREF{\Reg}{\Int} \\
  2515. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2516. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2517. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2518. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2519. &\MID& \PUSHQ{\Arg}
  2520. \MID \POPQ{\Arg} \\
  2521. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2522. \MID \RETQ{}
  2523. \MID \JMP{\itm{label}} \\
  2524. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2525. \end{array}
  2526. }
  2527. \newcommand{\ASTXIntPython}{
  2528. \begin{array}{lcl}
  2529. \Reg &::=& \allregisters{} \\
  2530. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2531. \MID \DEREF{\Reg}{\Int} \\
  2532. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2533. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2534. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2535. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2536. &\MID& \PUSHQ{\Arg}
  2537. \MID \POPQ{\Arg} \\
  2538. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2539. \MID \RETQ{}
  2540. \MID \JMP{\itm{label}} \\
  2541. \Block &::= & \Instr^{+}
  2542. \end{array}
  2543. }
  2544. \begin{figure}[tp]
  2545. \begin{tcolorbox}[colback=white]
  2546. \small
  2547. {\if\edition\racketEd
  2548. \[\arraycolsep=3pt
  2549. \begin{array}{l}
  2550. \ASTXIntRacket \\
  2551. \begin{array}{lcl}
  2552. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2553. \end{array}
  2554. \end{array}
  2555. \]
  2556. \fi}
  2557. {\if\edition\pythonEd\pythonColor
  2558. \[
  2559. \begin{array}{lcl}
  2560. \Reg &::=& \allastregisters{} \\
  2561. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2562. \MID \DEREF{\Reg}{\Int} \\
  2563. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2564. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2565. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2566. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2567. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2568. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2569. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2570. \end{array}
  2571. \]
  2572. \fi}
  2573. \end{tcolorbox}
  2574. \caption{The abstract syntax of \LangXInt{} assembly.}
  2575. \label{fig:x86-int-ast}
  2576. \end{figure}
  2577. \section{Planning the Trip to x86}
  2578. \label{sec:plan-s0-x86}
  2579. To compile one language to another, it helps to focus on the
  2580. differences between the two languages because the compiler will need
  2581. to bridge those differences. What are the differences between \LangVar{}
  2582. and x86 assembly? Here are some of the most important ones:
  2583. \begin{enumerate}
  2584. \item x86 arithmetic instructions typically have two arguments and
  2585. update the second argument in place. In contrast, \LangVar{}
  2586. arithmetic operations take two arguments and produce a new value.
  2587. An x86 instruction may have at most one memory-accessing argument.
  2588. Furthermore, some x86 instructions place special restrictions on
  2589. their arguments.
  2590. \item An argument of an \LangVar{} operator can be a deeply nested
  2591. expression, whereas x86 instructions restrict their arguments to be
  2592. integer constants, registers, and memory locations.
  2593. {\if\edition\racketEd
  2594. \item The order of execution in x86 is explicit in the syntax, which
  2595. is a sequence of instructions and jumps to labeled positions,
  2596. whereas in \LangVar{} the order of evaluation is a left-to-right
  2597. depth-first traversal of the abstract syntax tree. \fi}
  2598. \item A program in \LangVar{} can have any number of variables,
  2599. whereas x86 has 16 registers and the procedure call stack.
  2600. {\if\edition\racketEd
  2601. \item Variables in \LangVar{} can shadow other variables with the
  2602. same name. In x86, registers have unique names, and memory locations
  2603. have unique addresses.
  2604. \fi}
  2605. \end{enumerate}
  2606. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2607. down the problem into several steps, which deal with these differences
  2608. one at a time. Each of these steps is called a \emph{pass} of the
  2609. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2610. %
  2611. This term indicates that each step passes over, or traverses, the AST
  2612. of the program.
  2613. %
  2614. Furthermore, we follow the nanopass approach, which means that we
  2615. strive for each pass to accomplish one clear objective rather than two
  2616. or three at the same time.
  2617. %
  2618. We begin by sketching how we might implement each pass and give each
  2619. pass a name. We then figure out an ordering of the passes and the
  2620. input/output language for each pass. The very first pass has
  2621. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2622. its output language. In between these two passes, we can choose
  2623. whichever language is most convenient for expressing the output of
  2624. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2625. \emph{intermediate language} of our own design. Finally, to
  2626. implement each pass we write one recursive function per nonterminal in
  2627. the grammar of the input language of the pass.
  2628. \index{subject}{intermediate language}
  2629. Our compiler for \LangVar{} consists of the following passes:
  2630. %
  2631. \begin{description}
  2632. {\if\edition\racketEd
  2633. \item[\key{uniquify}] deals with the shadowing of variables by
  2634. renaming every variable to a unique name.
  2635. \fi}
  2636. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2637. of a primitive operation or function call is a variable or integer,
  2638. that is, an \emph{atomic} expression. We refer to nonatomic
  2639. expressions as \emph{complex}. This pass introduces temporary
  2640. variables to hold the results of complex
  2641. subexpressions.\index{subject}{atomic
  2642. expression}\index{subject}{complex expression}%
  2643. {\if\edition\racketEd
  2644. \item[\key{explicate\_control}] makes the execution order of the
  2645. program explicit. It converts the abstract syntax tree
  2646. representation into a graph in which each node is a labeled sequence
  2647. of statements and the edges are \code{goto} statements.
  2648. \fi}
  2649. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2650. handles the difference between
  2651. \LangVar{} operations and x86 instructions. This pass converts each
  2652. \LangVar{} operation to a short sequence of instructions that
  2653. accomplishes the same task.
  2654. \item[\key{assign\_homes}] replaces variables with registers or stack
  2655. locations.
  2656. \end{description}
  2657. %
  2658. {\if\edition\racketEd
  2659. %
  2660. Our treatment of \code{remove\_complex\_operands} and
  2661. \code{explicate\_control} as separate passes is an example of the
  2662. nanopass approach.\footnote{For analogous decompositions of the
  2663. translation into continuation passing style, see the work of
  2664. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2665. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2666. %
  2667. \fi}
  2668. The next question is, in what order should we apply these passes? This
  2669. question can be challenging because it is difficult to know ahead of
  2670. time which orderings will be better (that is, will be easier to
  2671. implement, produce more efficient code, and so on), and therefore
  2672. ordering often involves trial and error. Nevertheless, we can plan
  2673. ahead and make educated choices regarding the ordering.
  2674. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2675. \key{uniquify}? The \key{uniquify} pass should come first because
  2676. \key{explicate\_control} changes all the \key{let}-bound variables to
  2677. become local variables whose scope is the entire program, which would
  2678. confuse variables with the same name.}
  2679. %
  2680. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2681. because the later removes the \key{let} form, but it is convenient to
  2682. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2683. %
  2684. \racket{The ordering of \key{uniquify} with respect to
  2685. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2686. \key{uniquify} to come first.}
  2687. The \key{select\_instructions} and \key{assign\_homes} passes are
  2688. intertwined.
  2689. %
  2690. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2691. passing arguments to functions and that it is preferable to assign
  2692. parameters to their corresponding registers. This suggests that it
  2693. would be better to start with the \key{select\_instructions} pass,
  2694. which generates the instructions for argument passing, before
  2695. performing register allocation.
  2696. %
  2697. On the other hand, by selecting instructions first we may run into a
  2698. dead end in \key{assign\_homes}. Recall that only one argument of an
  2699. x86 instruction may be a memory access, but \key{assign\_homes} might
  2700. be forced to assign both arguments to memory locations.
  2701. %
  2702. A sophisticated approach is to repeat the two passes until a solution
  2703. is found. However, to reduce implementation complexity we recommend
  2704. placing \key{select\_instructions} first, followed by the
  2705. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2706. that uses a reserved register to fix outstanding problems.
  2707. \begin{figure}[tbp]
  2708. \begin{tcolorbox}[colback=white]
  2709. {\if\edition\racketEd
  2710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2711. \node (Lvar) at (0,2) {\large \LangVar{}};
  2712. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2713. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2714. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2715. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2716. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2717. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2718. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2719. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2720. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2721. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2722. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2723. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2724. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2725. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2726. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2727. \end{tikzpicture}
  2728. \fi}
  2729. {\if\edition\pythonEd\pythonColor
  2730. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2731. \node (Lvar) at (0,2) {\large \LangVar{}};
  2732. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2733. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2734. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2735. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2736. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2737. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2738. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2739. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2740. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2741. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2742. \end{tikzpicture}
  2743. \fi}
  2744. \end{tcolorbox}
  2745. \caption{Diagram of the passes for compiling \LangVar{}. }
  2746. \label{fig:Lvar-passes}
  2747. \end{figure}
  2748. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2749. passes and identifies the input and output language of each pass.
  2750. %
  2751. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2752. language, which extends \LangXInt{} with an unbounded number of
  2753. program-scope variables and removes the restrictions regarding
  2754. instruction arguments.
  2755. %
  2756. The last pass, \key{prelude\_and\_conclusion}, places the program
  2757. instructions inside a \code{main} function with instructions for the
  2758. prelude and conclusion.
  2759. %
  2760. \racket{In the next section we discuss the \LangCVar{} intermediate
  2761. language that serves as the output of \code{explicate\_control}.}
  2762. %
  2763. The remainder of this chapter provides guidance on the implementation
  2764. of each of the compiler passes represented in
  2765. figure~\ref{fig:Lvar-passes}.
  2766. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2767. %% are programs that are still in the \LangVar{} language, though the
  2768. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2769. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2770. %% %
  2771. %% The output of \code{explicate\_control} is in an intermediate language
  2772. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2773. %% syntax, which we introduce in the next section. The
  2774. %% \key{select-instruction} pass translates from \LangCVar{} to
  2775. %% \LangXVar{}. The \key{assign-homes} and
  2776. %% \key{patch-instructions}
  2777. %% passes input and output variants of x86 assembly.
  2778. \newcommand{\CvarGrammarRacket}{
  2779. \begin{array}{lcl}
  2780. \Atm &::=& \Int \MID \Var \\
  2781. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2782. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2783. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2784. \end{array}
  2785. }
  2786. \newcommand{\CvarASTRacket}{
  2787. \begin{array}{lcl}
  2788. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2789. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2790. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2791. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2792. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2793. \end{array}
  2794. }
  2795. {\if\edition\racketEd
  2796. \subsection{The \LangCVar{} Intermediate Language}
  2797. The output of \code{explicate\_control} is similar to the C
  2798. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2799. categories for expressions and statements, so we name it \LangCVar{}.
  2800. This style of intermediate language is also known as
  2801. \emph{three-address code}, to emphasize that the typical form of a
  2802. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2803. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2804. The concrete syntax for \LangCVar{} is shown in
  2805. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2806. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2807. %
  2808. The \LangCVar{} language supports the same operators as \LangVar{} but
  2809. the arguments of operators are restricted to atomic
  2810. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2811. assignment statements that can be executed in sequence using the
  2812. \key{Seq} form. A sequence of statements always ends with
  2813. \key{Return}, a guarantee that is baked into the grammar rules for
  2814. \itm{tail}. The naming of this nonterminal comes from the term
  2815. \emph{tail position}\index{subject}{tail position}, which refers to an
  2816. expression that is the last one to execute within a function or
  2817. program.
  2818. A \LangCVar{} program consists of an alist mapping labels to
  2819. tails. This is more general than necessary for the present chapter, as
  2820. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2821. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2822. there is just one label, \key{start}, and the whole program is
  2823. its tail.
  2824. %
  2825. The $\itm{info}$ field of the \key{CProgram} form, after the
  2826. \code{explicate\_control} pass, contains an alist that associates the
  2827. symbol \key{locals} with a list of all the variables used in the
  2828. program. At the start of the program, these variables are
  2829. uninitialized; they become initialized on their first assignment.
  2830. \begin{figure}[tbp]
  2831. \begin{tcolorbox}[colback=white]
  2832. \[
  2833. \begin{array}{l}
  2834. \CvarGrammarRacket \\
  2835. \begin{array}{lcl}
  2836. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2837. \end{array}
  2838. \end{array}
  2839. \]
  2840. \end{tcolorbox}
  2841. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2842. \label{fig:c0-concrete-syntax}
  2843. \end{figure}
  2844. \begin{figure}[tbp]
  2845. \begin{tcolorbox}[colback=white]
  2846. \[
  2847. \begin{array}{l}
  2848. \CvarASTRacket \\
  2849. \begin{array}{lcl}
  2850. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2851. \end{array}
  2852. \end{array}
  2853. \]
  2854. \end{tcolorbox}
  2855. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2856. \label{fig:c0-syntax}
  2857. \end{figure}
  2858. The definitional interpreter for \LangCVar{} is in the support code,
  2859. in the file \code{interp-Cvar.rkt}.
  2860. \fi}
  2861. {\if\edition\racketEd
  2862. \section{Uniquify Variables}
  2863. \label{sec:uniquify-Lvar}
  2864. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2865. with a unique name. Both the input and output of the \code{uniquify}
  2866. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2867. should translate the program on the left into the program on the
  2868. right.
  2869. \begin{transformation}
  2870. \begin{lstlisting}
  2871. (let ([x 32])
  2872. (+ (let ([x 10]) x) x))
  2873. \end{lstlisting}
  2874. \compilesto
  2875. \begin{lstlisting}
  2876. (let ([x.1 32])
  2877. (+ (let ([x.2 10]) x.2) x.1))
  2878. \end{lstlisting}
  2879. \end{transformation}
  2880. The following is another example translation, this time of a program
  2881. with a \key{let} nested inside the initializing expression of another
  2882. \key{let}.
  2883. \begin{transformation}
  2884. \begin{lstlisting}
  2885. (let ([x (let ([x 4])
  2886. (+ x 1))])
  2887. (+ x 2))
  2888. \end{lstlisting}
  2889. \compilesto
  2890. \begin{lstlisting}
  2891. (let ([x.2 (let ([x.1 4])
  2892. (+ x.1 1))])
  2893. (+ x.2 2))
  2894. \end{lstlisting}
  2895. \end{transformation}
  2896. We recommend implementing \code{uniquify} by creating a structurally
  2897. recursive function named \code{uniquify\_exp} that does little other
  2898. than copy an expression. However, when encountering a \key{let}, it
  2899. should generate a unique name for the variable and associate the old
  2900. name with the new name in an alist.\footnote{The Racket function
  2901. \code{gensym} is handy for generating unique variable names.} The
  2902. \code{uniquify\_exp} function needs to access this alist when it gets
  2903. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2904. for the alist.
  2905. The skeleton of the \code{uniquify\_exp} function is shown in
  2906. figure~\ref{fig:uniquify-Lvar}.
  2907. %% The function is curried so that it is
  2908. %% convenient to partially apply it to an alist and then apply it to
  2909. %% different expressions, as in the last case for primitive operations in
  2910. %% figure~\ref{fig:uniquify-Lvar}.
  2911. The
  2912. %
  2913. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2914. %
  2915. form of Racket is useful for transforming the element of a list to
  2916. produce a new list.\index{subject}{for/list}
  2917. \begin{figure}[tbp]
  2918. \begin{tcolorbox}[colback=white]
  2919. \begin{lstlisting}
  2920. (define (uniquify_exp env)
  2921. (lambda (e)
  2922. (match e
  2923. [(Var x) ___]
  2924. [(Int n) (Int n)]
  2925. [(Let x e body) ___]
  2926. [(Prim op es)
  2927. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2928. (define (uniquify p)
  2929. (match p
  2930. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2931. \end{lstlisting}
  2932. \end{tcolorbox}
  2933. \caption{Skeleton for the \key{uniquify} pass.}
  2934. \label{fig:uniquify-Lvar}
  2935. \end{figure}
  2936. \begin{exercise}
  2937. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2938. Complete the \code{uniquify} pass by filling in the blanks in
  2939. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2940. variables and for the \key{let} form in the file \code{compiler.rkt}
  2941. in the support code.
  2942. \end{exercise}
  2943. \begin{exercise}
  2944. \normalfont\normalsize
  2945. \label{ex:Lvar}
  2946. Create five \LangVar{} programs that exercise the most interesting
  2947. parts of the \key{uniquify} pass; that is, the programs should include
  2948. \key{let} forms, variables, and variables that shadow each other.
  2949. The five programs should be placed in the subdirectory named
  2950. \key{tests}, and the file names should start with \code{var\_test\_}
  2951. followed by a unique integer and end with the file extension
  2952. \key{.rkt}.
  2953. %
  2954. The \key{run-tests.rkt} script in the support code checks whether the
  2955. output programs produce the same result as the input programs. The
  2956. script uses the \key{interp-tests} function
  2957. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2958. your \key{uniquify} pass on the example programs. The \code{passes}
  2959. parameter of \key{interp-tests} is a list that should have one entry
  2960. for each pass in your compiler. For now, define \code{passes} to
  2961. contain just one entry for \code{uniquify} as follows:
  2962. \begin{lstlisting}
  2963. (define passes
  2964. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2965. \end{lstlisting}
  2966. Run the \key{run-tests.rkt} script in the support code to check
  2967. whether the output programs produce the same result as the input
  2968. programs.
  2969. \end{exercise}
  2970. \fi}
  2971. \section{Remove Complex Operands}
  2972. \label{sec:remove-complex-opera-Lvar}
  2973. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2974. into a restricted form in which the arguments of operations are atomic
  2975. expressions. Put another way, this pass removes complex
  2976. operands\index{subject}{complex operand}, such as the expression
  2977. \racket{\code{(- 10)}}\python{\code{-10}}
  2978. in the following program. This is accomplished by introducing a new
  2979. temporary variable, assigning the complex operand to the new
  2980. variable, and then using the new variable in place of the complex
  2981. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2982. right.
  2983. {\if\edition\racketEd
  2984. \begin{transformation}
  2985. % var_test_19.rkt
  2986. \begin{lstlisting}
  2987. (let ([x (+ 42 (- 10))])
  2988. (+ x 10))
  2989. \end{lstlisting}
  2990. \compilesto
  2991. \begin{lstlisting}
  2992. (let ([x (let ([tmp.1 (- 10)])
  2993. (+ 42 tmp.1))])
  2994. (+ x 10))
  2995. \end{lstlisting}
  2996. \end{transformation}
  2997. \fi}
  2998. {\if\edition\pythonEd\pythonColor
  2999. \begin{transformation}
  3000. \begin{lstlisting}
  3001. x = 42 + -10
  3002. print(x + 10)
  3003. \end{lstlisting}
  3004. \compilesto
  3005. \begin{lstlisting}
  3006. tmp_0 = -10
  3007. x = 42 + tmp_0
  3008. tmp_1 = x + 10
  3009. print(tmp_1)
  3010. \end{lstlisting}
  3011. \end{transformation}
  3012. \fi}
  3013. \newcommand{\LvarMonadASTRacket}{
  3014. \begin{array}{rcl}
  3015. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3016. \Exp &::=& \Atm \MID \READ{} \\
  3017. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3018. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3019. \end{array}
  3020. }
  3021. \newcommand{\LvarMonadASTPython}{
  3022. \begin{array}{rcl}
  3023. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3024. \Exp{} &::=& \Atm \MID \READ{} \\
  3025. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  3026. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3027. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3028. \end{array}
  3029. }
  3030. \begin{figure}[tp]
  3031. \centering
  3032. \begin{tcolorbox}[colback=white]
  3033. {\if\edition\racketEd
  3034. \[
  3035. \begin{array}{l}
  3036. \LvarMonadASTRacket \\
  3037. \begin{array}{rcl}
  3038. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3039. \end{array}
  3040. \end{array}
  3041. \]
  3042. \fi}
  3043. {\if\edition\pythonEd\pythonColor
  3044. \[
  3045. \begin{array}{l}
  3046. \LvarMonadASTPython \\
  3047. \begin{array}{rcl}
  3048. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3049. \end{array}
  3050. \end{array}
  3051. \]
  3052. \fi}
  3053. \end{tcolorbox}
  3054. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3055. atomic expressions.}
  3056. \label{fig:Lvar-anf-syntax}
  3057. \end{figure}
  3058. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3059. of this pass, the language \LangVarANF{}. The only difference is that
  3060. operator arguments are restricted to be atomic expressions that are
  3061. defined by the \Atm{} nonterminal. In particular, integer constants
  3062. and variables are atomic.
  3063. The atomic expressions are pure (they do not cause or depend on side
  3064. effects) whereas complex expressions may have side effects, such as
  3065. \READ{}. A language with this separation between pure expressions
  3066. versus expressions with side effects is said to be in monadic normal
  3067. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3068. in the name \LangVarANF{}. An important invariant of the
  3069. \code{remove\_complex\_operands} pass is that the relative ordering
  3070. among complex expressions is not changed, but the relative ordering
  3071. between atomic expressions and complex expressions can change and
  3072. often does. The reason that these changes are behavior preserving is
  3073. that the atomic expressions are pure.
  3074. {\if\edition\racketEd
  3075. Another well-known form for intermediate languages is the
  3076. \emph{administrative normal form}
  3077. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3078. \index{subject}{administrative normal form} \index{subject}{ANF}
  3079. %
  3080. The \LangVarANF{} language is not quite in ANF because it allows the
  3081. right-hand side of a \code{let} to be a complex expression, such as
  3082. another \code{let}. The flattening of nested \code{let} expressions is
  3083. instead one of the responsibilities of the \code{explicate\_control}
  3084. pass.
  3085. \fi}
  3086. {\if\edition\racketEd
  3087. We recommend implementing this pass with two mutually recursive
  3088. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3089. \code{rco\_atom} to subexpressions that need to become atomic and to
  3090. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3091. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3092. returns an expression. The \code{rco\_atom} function returns two
  3093. things: an atomic expression and an alist mapping temporary variables to
  3094. complex subexpressions. You can return multiple things from a function
  3095. using Racket's \key{values} form, and you can receive multiple things
  3096. from a function call using the \key{define-values} form.
  3097. \fi}
  3098. %
  3099. {\if\edition\pythonEd\pythonColor
  3100. %
  3101. We recommend implementing this pass with an auxiliary method named
  3102. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3103. Boolean that specifies whether the expression needs to become atomic
  3104. or not. The \code{rco\_exp} method should return a pair consisting of
  3105. the new expression and a list of pairs, associating new temporary
  3106. variables with their initializing expressions.
  3107. %
  3108. \fi}
  3109. {\if\edition\racketEd
  3110. %
  3111. In the example program with the expression \code{(+ 42 (-
  3112. 10))}, the subexpression \code{(- 10)} should be processed using the
  3113. \code{rco\_atom} function because it is an argument of the \code{+}
  3114. operator and therefore needs to become atomic. The output of
  3115. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3116. \begin{transformation}
  3117. \begin{lstlisting}
  3118. (- 10)
  3119. \end{lstlisting}
  3120. \compilesto
  3121. \begin{lstlisting}
  3122. tmp.1
  3123. ((tmp.1 . (- 10)))
  3124. \end{lstlisting}
  3125. \end{transformation}
  3126. \fi}
  3127. %
  3128. {\if\edition\pythonEd\pythonColor
  3129. %
  3130. Returning to the example program with the expression \code{42 + -10},
  3131. the subexpression \code{-10} should be processed using the
  3132. \code{rco\_exp} function with \code{True} as the second argument,
  3133. because \code{-10} is an argument of the \code{+} operator and
  3134. therefore needs to become atomic. The output of \code{rco\_exp}
  3135. applied to \code{-10} is as follows.
  3136. \begin{transformation}
  3137. \begin{lstlisting}
  3138. -10
  3139. \end{lstlisting}
  3140. \compilesto
  3141. \begin{lstlisting}
  3142. tmp_1
  3143. [(tmp_1, -10)]
  3144. \end{lstlisting}
  3145. \end{transformation}
  3146. %
  3147. \fi}
  3148. Take special care of programs, such as the following, that
  3149. %
  3150. \racket{bind a variable to an atomic expression.}
  3151. %
  3152. \python{assign an atomic expression to a variable.}
  3153. %
  3154. You should leave such \racket{variable bindings}\python{assignments}
  3155. unchanged, as shown in the program on the right:\\
  3156. %
  3157. {\if\edition\racketEd
  3158. \begin{transformation}
  3159. % var_test_20.rkt
  3160. \begin{lstlisting}
  3161. (let ([a 42])
  3162. (let ([b a])
  3163. b))
  3164. \end{lstlisting}
  3165. \compilesto
  3166. \begin{lstlisting}
  3167. (let ([a 42])
  3168. (let ([b a])
  3169. b))
  3170. \end{lstlisting}
  3171. \end{transformation}
  3172. \fi}
  3173. {\if\edition\pythonEd\pythonColor
  3174. \begin{transformation}
  3175. \begin{lstlisting}
  3176. a = 42
  3177. b = a
  3178. print(b)
  3179. \end{lstlisting}
  3180. \compilesto
  3181. \begin{lstlisting}
  3182. a = 42
  3183. b = a
  3184. print(b)
  3185. \end{lstlisting}
  3186. \end{transformation}
  3187. \fi}
  3188. %
  3189. \noindent A careless implementation might produce the following output with
  3190. unnecessary temporary variables.
  3191. \begin{center}
  3192. \begin{minipage}{0.4\textwidth}
  3193. {\if\edition\racketEd
  3194. \begin{lstlisting}
  3195. (let ([tmp.1 42])
  3196. (let ([a tmp.1])
  3197. (let ([tmp.2 a])
  3198. (let ([b tmp.2])
  3199. b))))
  3200. \end{lstlisting}
  3201. \fi}
  3202. {\if\edition\pythonEd\pythonColor
  3203. \begin{lstlisting}
  3204. tmp_1 = 42
  3205. a = tmp_1
  3206. tmp_2 = a
  3207. b = tmp_2
  3208. print(b)
  3209. \end{lstlisting}
  3210. \fi}
  3211. \end{minipage}
  3212. \end{center}
  3213. \begin{exercise}
  3214. \normalfont\normalsize
  3215. {\if\edition\racketEd
  3216. Implement the \code{remove\_complex\_operands} function in
  3217. \code{compiler.rkt}.
  3218. %
  3219. Create three new \LangVar{} programs that exercise the interesting
  3220. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3221. regarding file names described in exercise~\ref{ex:Lvar}.
  3222. %
  3223. In the \code{run-tests.rkt} script, add the following entry to the
  3224. list of \code{passes}, and then run the script to test your compiler.
  3225. \begin{lstlisting}
  3226. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3227. \end{lstlisting}
  3228. In debugging your compiler, it is often useful to see the intermediate
  3229. programs that are output from each pass. To print the intermediate
  3230. programs, place \lstinline{(debug-level 1)} before the call to
  3231. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3232. %
  3233. {\if\edition\pythonEd\pythonColor
  3234. Implement the \code{remove\_complex\_operands} pass in
  3235. \code{compiler.py}, creating auxiliary functions for each
  3236. nonterminal in the grammar, that is, \code{rco\_exp}
  3237. and \code{rco\_stmt}. We recommend that you use the function
  3238. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3239. \fi}
  3240. \end{exercise}
  3241. {\if\edition\pythonEd\pythonColor
  3242. \begin{exercise}
  3243. \normalfont\normalsize
  3244. \label{ex:Lvar}
  3245. Create five \LangVar{} programs that exercise the most interesting
  3246. parts of the \code{remove\_complex\_operands} pass. The five programs
  3247. should be placed in the subdirectory named \key{tests}, and the file
  3248. names should start with \code{var\_test\_} followed by a unique
  3249. integer and end with the file extension \key{.py}.
  3250. %% The \key{run-tests.rkt} script in the support code checks whether the
  3251. %% output programs produce the same result as the input programs. The
  3252. %% script uses the \key{interp-tests} function
  3253. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3254. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3255. %% parameter of \key{interp-tests} is a list that should have one entry
  3256. %% for each pass in your compiler. For now, define \code{passes} to
  3257. %% contain just one entry for \code{uniquify} as shown below.
  3258. %% \begin{lstlisting}
  3259. %% (define passes
  3260. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3261. %% \end{lstlisting}
  3262. Run the \key{run-tests.py} script in the support code to check
  3263. whether the output programs produce the same result as the input
  3264. programs.
  3265. \end{exercise}
  3266. \fi}
  3267. {\if\edition\racketEd
  3268. \section{Explicate Control}
  3269. \label{sec:explicate-control-Lvar}
  3270. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3271. programs that make the order of execution explicit in their
  3272. syntax. For now this amounts to flattening \key{let} constructs into a
  3273. sequence of assignment statements. For example, consider the following
  3274. \LangVar{} program:\\
  3275. % var_test_11.rkt
  3276. \begin{minipage}{0.96\textwidth}
  3277. \begin{lstlisting}
  3278. (let ([y (let ([x 20])
  3279. (+ x (let ([x 22]) x)))])
  3280. y)
  3281. \end{lstlisting}
  3282. \end{minipage}\\
  3283. %
  3284. The output of the previous pass is shown next, on the left, and the
  3285. output of \code{explicate\_control} is on the right. Recall that the
  3286. right-hand side of a \key{let} executes before its body, so that the order
  3287. of evaluation for this program is to assign \code{20} to \code{x.1},
  3288. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3289. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3290. this ordering explicit.
  3291. \begin{transformation}
  3292. \begin{lstlisting}
  3293. (let ([y (let ([x.1 20])
  3294. (let ([x.2 22])
  3295. (+ x.1 x.2)))])
  3296. y)
  3297. \end{lstlisting}
  3298. \compilesto
  3299. \begin{lstlisting}[language=C]
  3300. start:
  3301. x.1 = 20;
  3302. x.2 = 22;
  3303. y = (+ x.1 x.2);
  3304. return y;
  3305. \end{lstlisting}
  3306. \end{transformation}
  3307. \begin{figure}[tbp]
  3308. \begin{tcolorbox}[colback=white]
  3309. \begin{lstlisting}
  3310. (define (explicate_tail e)
  3311. (match e
  3312. [(Var x) ___]
  3313. [(Int n) (Return (Int n))]
  3314. [(Let x rhs body) ___]
  3315. [(Prim op es) ___]
  3316. [else (error "explicate_tail unhandled case" e)]))
  3317. (define (explicate_assign e x cont)
  3318. (match e
  3319. [(Var x) ___]
  3320. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3321. [(Let y rhs body) ___]
  3322. [(Prim op es) ___]
  3323. [else (error "explicate_assign unhandled case" e)]))
  3324. (define (explicate_control p)
  3325. (match p
  3326. [(Program info body) ___]))
  3327. \end{lstlisting}
  3328. \end{tcolorbox}
  3329. \caption{Skeleton for the \code{explicate\_control} pass.}
  3330. \label{fig:explicate-control-Lvar}
  3331. \end{figure}
  3332. The organization of this pass depends on the notion of tail position
  3333. to which we have alluded. Here is the definition.
  3334. \begin{definition}\normalfont
  3335. The following rules define when an expression is in \emph{tail
  3336. position}\index{subject}{tail position} for the language \LangVar{}.
  3337. \begin{enumerate}
  3338. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3339. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3340. \end{enumerate}
  3341. \end{definition}
  3342. We recommend implementing \code{explicate\_control} using two
  3343. recursive functions, \code{explicate\_tail} and
  3344. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3345. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3346. function should be applied to expressions in tail position, whereas the
  3347. \code{explicate\_assign} should be applied to expressions that occur on
  3348. the right-hand side of a \key{let}.
  3349. %
  3350. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3351. input and produces a \Tail{} in \LangCVar{} (see
  3352. figure~\ref{fig:c0-syntax}).
  3353. %
  3354. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3355. the variable to which it is to be assigned, and a \Tail{} in
  3356. \LangCVar{} for the code that comes after the assignment. The
  3357. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3358. The \code{explicate\_assign} function is in accumulator-passing style:
  3359. the \code{cont} parameter is used for accumulating the output. This
  3360. accumulator-passing style plays an important role in the way that we
  3361. generate high-quality code for conditional expressions in
  3362. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3363. continuation because it contains the generated code that should come
  3364. after the current assignment. This code organization is also related
  3365. to continuation-passing style, except that \code{cont} is not what
  3366. happens next during compilation but is what happens next in the
  3367. generated code.
  3368. \begin{exercise}\normalfont\normalsize
  3369. %
  3370. Implement the \code{explicate\_control} function in
  3371. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3372. exercise the code in \code{explicate\_control}.
  3373. %
  3374. In the \code{run-tests.rkt} script, add the following entry to the
  3375. list of \code{passes} and then run the script to test your compiler.
  3376. \begin{lstlisting}
  3377. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3378. \end{lstlisting}
  3379. \end{exercise}
  3380. \fi}
  3381. \section{Select Instructions}
  3382. \label{sec:select-Lvar}
  3383. \index{subject}{select instructions}
  3384. In the \code{select\_instructions} pass we begin the work of
  3385. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3386. language of this pass is a variant of x86 that still uses variables,
  3387. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3388. nonterminal of the \LangXInt{} abstract syntax
  3389. (figure~\ref{fig:x86-int-ast}).
  3390. \racket{We recommend implementing the
  3391. \code{select\_instructions} with three auxiliary functions, one for
  3392. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3393. $\Tail$.}
  3394. \python{We recommend implementing an auxiliary function
  3395. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3396. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3397. same and integer constants change to immediates; that is, $\INT{n}$
  3398. changes to $\IMM{n}$.}
  3399. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3400. arithmetic operations. For example, consider the following addition
  3401. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3402. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3403. \key{addq} instruction in x86, but it performs an in-place update.
  3404. %
  3405. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3406. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into the
  3407. left-hand \itm{var}.
  3408. \begin{transformation}
  3409. {\if\edition\racketEd
  3410. \begin{lstlisting}
  3411. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3412. \end{lstlisting}
  3413. \fi}
  3414. {\if\edition\pythonEd\pythonColor
  3415. \begin{lstlisting}
  3416. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3417. \end{lstlisting}
  3418. \fi}
  3419. \compilesto
  3420. \begin{lstlisting}
  3421. movq |$\Arg_1$|, %rax
  3422. addq |$\Arg_2$|, %rax
  3423. movq %rax, |$\itm{var}$|
  3424. \end{lstlisting}
  3425. \end{transformation}
  3426. %
  3427. However, with some care we can generate shorter sequences of
  3428. instructions. Suppose that one or more of the arguments of the
  3429. addition is the same variable as the left-hand side of the assignment.
  3430. Then the assignment statement can be translated into a single
  3431. \key{addq} instruction, as follows.
  3432. \begin{transformation}
  3433. {\if\edition\racketEd
  3434. \begin{lstlisting}
  3435. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3436. \end{lstlisting}
  3437. \fi}
  3438. {\if\edition\pythonEd\pythonColor
  3439. \begin{lstlisting}
  3440. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3441. \end{lstlisting}
  3442. \fi}
  3443. \compilesto
  3444. \begin{lstlisting}
  3445. addq |$\Arg_1$|, |$\itm{var}$|
  3446. \end{lstlisting}
  3447. \end{transformation}
  3448. %
  3449. On the other hand, if $\Atm_1$ is not the same variable as the
  3450. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3451. and then add $\Arg_2$ to \itm{var}.
  3452. %
  3453. \begin{transformation}
  3454. {\if\edition\racketEd
  3455. \begin{lstlisting}
  3456. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3457. \end{lstlisting}
  3458. \fi}
  3459. {\if\edition\pythonEd\pythonColor
  3460. \begin{lstlisting}
  3461. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3462. \end{lstlisting}
  3463. \fi}
  3464. \compilesto
  3465. \begin{lstlisting}
  3466. movq |$\Arg_1$|, |$\itm{var}$|
  3467. addq |$\Arg_2$|, |$\itm{var}$|
  3468. \end{lstlisting}
  3469. \end{transformation}
  3470. The \READOP{} operation does not have a direct counterpart in x86
  3471. assembly, so we provide this functionality with the function
  3472. \code{read\_int} in the file \code{runtime.c}, written in
  3473. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3474. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3475. system}, or simply the \emph{runtime} for short. When compiling your
  3476. generated x86 assembly code, you need to compile \code{runtime.c} to
  3477. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3478. \code{-c}) and link it into the executable. For our purposes of code
  3479. generation, all you need to do is translate an assignment of
  3480. \READOP{} into a call to the \code{read\_int} function followed by a
  3481. move from \code{rax} to the left-hand side variable. (Recall that the
  3482. return value of a function goes into \code{rax}.)
  3483. \begin{transformation}
  3484. {\if\edition\racketEd
  3485. \begin{lstlisting}
  3486. |$\itm{var}$| = (read);
  3487. \end{lstlisting}
  3488. \fi}
  3489. {\if\edition\pythonEd\pythonColor
  3490. \begin{lstlisting}
  3491. |$\itm{var}$| = input_int();
  3492. \end{lstlisting}
  3493. \fi}
  3494. \compilesto
  3495. \begin{lstlisting}
  3496. callq read_int
  3497. movq %rax, |$\itm{var}$|
  3498. \end{lstlisting}
  3499. \end{transformation}
  3500. {\if\edition\pythonEd\pythonColor
  3501. %
  3502. Similarly, we translate the \code{print} operation, shown below, into
  3503. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3504. In x86, the first six arguments to functions are passed in registers,
  3505. with the first argument passed in register \code{rdi}. So we move the
  3506. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3507. \code{callq} instruction.
  3508. \begin{transformation}
  3509. \begin{lstlisting}
  3510. print(|$\Atm$|)
  3511. \end{lstlisting}
  3512. \compilesto
  3513. \begin{lstlisting}
  3514. movq |$\Arg$|, %rdi
  3515. callq print_int
  3516. \end{lstlisting}
  3517. \end{transformation}
  3518. %
  3519. \fi}
  3520. {\if\edition\racketEd
  3521. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3522. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3523. assignment to the \key{rax} register followed by a jump to the
  3524. conclusion of the program (so the conclusion needs to be labeled).
  3525. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3526. recursively and then append the resulting instructions.
  3527. \fi}
  3528. {\if\edition\pythonEd\pythonColor
  3529. We recommend that you use the function \code{utils.label\_name()} to
  3530. transform strings into labels, for example, in
  3531. the target of the \code{callq} instruction. This practice makes your
  3532. compiler portable across Linux and Mac OS X, which requires an underscore
  3533. prefixed to all labels.
  3534. \fi}
  3535. \begin{exercise}
  3536. \normalfont\normalsize
  3537. {\if\edition\racketEd
  3538. Implement the \code{select\_instructions} pass in
  3539. \code{compiler.rkt}. Create three new example programs that are
  3540. designed to exercise all the interesting cases in this pass.
  3541. %
  3542. In the \code{run-tests.rkt} script, add the following entry to the
  3543. list of \code{passes} and then run the script to test your compiler.
  3544. \begin{lstlisting}
  3545. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3546. \end{lstlisting}
  3547. \fi}
  3548. {\if\edition\pythonEd\pythonColor
  3549. Implement the \key{select\_instructions} pass in
  3550. \code{compiler.py}. Create three new example programs that are
  3551. designed to exercise all the interesting cases in this pass.
  3552. Run the \code{run-tests.py} script to check
  3553. whether the output programs produce the same result as the input
  3554. programs.
  3555. \fi}
  3556. \end{exercise}
  3557. \section{Assign Homes}
  3558. \label{sec:assign-Lvar}
  3559. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3560. \LangXVar{} programs that no longer use program variables. Thus, the
  3561. \code{assign\_homes} pass is responsible for placing all the program
  3562. variables in registers or on the stack. For runtime efficiency, it is
  3563. better to place variables in registers, but because there are only
  3564. sixteen registers, some programs must necessarily resort to placing
  3565. some variables on the stack. In this chapter we focus on the mechanics
  3566. of placing variables on the stack. We study an algorithm for placing
  3567. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3568. Consider again the following \LangVar{} program from
  3569. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3570. % var_test_20.rkt
  3571. \begin{minipage}{0.96\textwidth}
  3572. {\if\edition\racketEd
  3573. \begin{lstlisting}
  3574. (let ([a 42])
  3575. (let ([b a])
  3576. b))
  3577. \end{lstlisting}
  3578. \fi}
  3579. {\if\edition\pythonEd\pythonColor
  3580. \begin{lstlisting}
  3581. a = 42
  3582. b = a
  3583. print(b)
  3584. \end{lstlisting}
  3585. \fi}
  3586. \end{minipage}\\
  3587. %
  3588. The output of \code{select\_instructions} is shown next, on the left,
  3589. and the output of \code{assign\_homes} is on the right. In this
  3590. example, we assign variable \code{a} to stack location
  3591. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3592. \begin{transformation}
  3593. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3594. movq $42, a
  3595. movq a, b
  3596. movq b, %rax
  3597. \end{lstlisting}
  3598. \compilesto
  3599. %stack-space: 16
  3600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3601. movq $42, -8(%rbp)
  3602. movq -8(%rbp), -16(%rbp)
  3603. movq -16(%rbp), %rax
  3604. \end{lstlisting}
  3605. \end{transformation}
  3606. \racket{
  3607. The \code{assign\_homes} pass should replace all variables
  3608. with stack locations.
  3609. The list of variables can be obtained from
  3610. the \code{locals-types} entry in the $\itm{info}$ of the
  3611. \code{X86Program} node. The \code{locals-types} entry is an alist
  3612. mapping all the variables in the program to their types
  3613. (for now, just \code{Integer}).
  3614. As an aside, the \code{locals-types} entry is
  3615. computed by \code{type-check-Cvar} in the support code, which
  3616. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3617. which you should propagate to the \code{X86Program} node.}
  3618. %
  3619. \python{The \code{assign\_homes} pass should replace all uses of
  3620. variables with stack locations.}
  3621. %
  3622. In the process of assigning variables to stack locations, it is
  3623. convenient for you to compute and store the size of the frame (in
  3624. bytes) in
  3625. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3626. %
  3627. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3628. %
  3629. which is needed later to generate the conclusion of the \code{main}
  3630. procedure. The x86-64 standard requires the frame size to be a
  3631. multiple of 16 bytes.\index{subject}{frame}
  3632. % TODO: store the number of variables instead? -Jeremy
  3633. \begin{exercise}\normalfont\normalsize
  3634. Implement the \code{assign\_homes} pass in
  3635. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3636. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3637. grammar. We recommend that the auxiliary functions take an extra
  3638. parameter that maps variable names to homes (stack locations for now).
  3639. %
  3640. {\if\edition\racketEd
  3641. In the \code{run-tests.rkt} script, add the following entry to the
  3642. list of \code{passes} and then run the script to test your compiler.
  3643. \begin{lstlisting}
  3644. (list "assign homes" assign-homes interp_x86-0)
  3645. \end{lstlisting}
  3646. \fi}
  3647. {\if\edition\pythonEd\pythonColor
  3648. Run the \code{run-tests.py} script to check
  3649. whether the output programs produce the same result as the input
  3650. programs.
  3651. \fi}
  3652. \end{exercise}
  3653. \section{Patch Instructions}
  3654. \label{sec:patch-s0}
  3655. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3656. \LangXInt{} by making sure that each instruction adheres to the
  3657. restriction that at most one argument of an instruction may be a
  3658. memory reference.
  3659. We return to the following example.\\
  3660. \begin{minipage}{0.5\textwidth}
  3661. % var_test_20.rkt
  3662. {\if\edition\racketEd
  3663. \begin{lstlisting}
  3664. (let ([a 42])
  3665. (let ([b a])
  3666. b))
  3667. \end{lstlisting}
  3668. \fi}
  3669. {\if\edition\pythonEd\pythonColor
  3670. \begin{lstlisting}
  3671. a = 42
  3672. b = a
  3673. print(b)
  3674. \end{lstlisting}
  3675. \fi}
  3676. \end{minipage}\\
  3677. The \code{assign\_homes} pass produces the following translation. \\
  3678. \begin{minipage}{0.5\textwidth}
  3679. {\if\edition\racketEd
  3680. \begin{lstlisting}
  3681. movq $42, -8(%rbp)
  3682. movq -8(%rbp), -16(%rbp)
  3683. movq -16(%rbp), %rax
  3684. \end{lstlisting}
  3685. \fi}
  3686. {\if\edition\pythonEd\pythonColor
  3687. \begin{lstlisting}
  3688. movq $42, -8(%rbp)
  3689. movq -8(%rbp), -16(%rbp)
  3690. movq -16(%rbp), %rdi
  3691. callq print_int
  3692. \end{lstlisting}
  3693. \fi}
  3694. \end{minipage}\\
  3695. The second \key{movq} instruction is problematic because both
  3696. arguments are stack locations. We suggest fixing this problem by
  3697. moving from the source location to the register \key{rax} and then
  3698. from \key{rax} to the destination location, as follows.
  3699. \begin{lstlisting}
  3700. movq -8(%rbp), %rax
  3701. movq %rax, -16(%rbp)
  3702. \end{lstlisting}
  3703. There is a similar corner case that also needs to be dealt with. If
  3704. one argument is an immediate integer larger than $2^{16}$ and the
  3705. other is a memory reference, then the instruction is invalid. One can
  3706. fix this, for example, by first moving the immediate integer into
  3707. \key{rax} and then using \key{rax} in place of the integer.
  3708. \begin{exercise}
  3709. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3710. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3711. Create three new example programs that are
  3712. designed to exercise all the interesting cases in this pass.
  3713. %
  3714. {\if\edition\racketEd
  3715. In the \code{run-tests.rkt} script, add the following entry to the
  3716. list of \code{passes} and then run the script to test your compiler.
  3717. \begin{lstlisting}
  3718. (list "patch instructions" patch_instructions interp_x86-0)
  3719. \end{lstlisting}
  3720. \fi}
  3721. {\if\edition\pythonEd\pythonColor
  3722. Run the \code{run-tests.py} script to check
  3723. whether the output programs produce the same result as the input
  3724. programs.
  3725. \fi}
  3726. \end{exercise}
  3727. \section{Generate Prelude and Conclusion}
  3728. \label{sec:print-x86}
  3729. \index{subject}{prelude}\index{subject}{conclusion}
  3730. The last step of the compiler from \LangVar{} to x86 is to generate
  3731. the \code{main} function with a prelude and conclusion wrapped around
  3732. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3733. discussed in section~\ref{sec:x86}.
  3734. When running on Mac OS X, your compiler should prefix an underscore to
  3735. all labels (for example, changing \key{main} to \key{\_main}).
  3736. %
  3737. \racket{The Racket call \code{(system-type 'os)} is useful for
  3738. determining which operating system the compiler is running on. It
  3739. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3740. %
  3741. \python{The Python \code{platform} library includes a \code{system()}
  3742. function that returns \code{\textquotesingle Linux\textquotesingle},
  3743. \code{\textquotesingle Windows\textquotesingle}, or
  3744. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3745. \begin{exercise}\normalfont\normalsize
  3746. %
  3747. Implement the \key{prelude\_and\_conclusion} pass in
  3748. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3749. %
  3750. {\if\edition\racketEd
  3751. In the \code{run-tests.rkt} script, add the following entry to the
  3752. list of \code{passes} and then run the script to test your compiler.
  3753. \begin{lstlisting}
  3754. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3755. \end{lstlisting}
  3756. %
  3757. Uncomment the call to the \key{compiler-tests} function
  3758. (appendix~\ref{appendix:utilities}), which tests your complete
  3759. compiler by executing the generated x86 code. It translates the x86
  3760. AST that you produce into a string by invoking the \code{print-x86}
  3761. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3762. the provided \key{runtime.c} file to \key{runtime.o} using
  3763. \key{gcc}. Run the script to test your compiler.
  3764. %
  3765. \fi}
  3766. {\if\edition\pythonEd\pythonColor
  3767. %
  3768. Run the \code{run-tests.py} script to check whether the output
  3769. programs produce the same result as the input programs. That script
  3770. translates the x86 AST that you produce into a string by invoking the
  3771. \code{repr} method that is implemented by the x86 AST classes in
  3772. \code{x86\_ast.py}.
  3773. %
  3774. \fi}
  3775. \end{exercise}
  3776. \section{Challenge: Partial Evaluator for \LangVar{}}
  3777. \label{sec:pe-Lvar}
  3778. \index{subject}{partialevaluation@partial evaluation}
  3779. This section describes two optional challenge exercises that involve
  3780. adapting and improving the partial evaluator for \LangInt{} that was
  3781. introduced in section~\ref{sec:partial-evaluation}.
  3782. \begin{exercise}\label{ex:pe-Lvar}
  3783. \normalfont\normalsize
  3784. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3785. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3786. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3787. %
  3788. \racket{\key{let} binding}\python{assignment}
  3789. %
  3790. to the \LangInt{} language, so you will need to add cases for them in
  3791. the \code{pe\_exp}
  3792. %
  3793. \racket{function.}
  3794. %
  3795. \python{and \code{pe\_stmt} functions.}
  3796. %
  3797. Once complete, add the partial evaluation pass to the front of your
  3798. compiler, and make sure that your compiler still passes all the
  3799. tests.
  3800. \end{exercise}
  3801. \begin{exercise}
  3802. \normalfont\normalsize
  3803. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3804. \code{pe\_add} auxiliary functions with functions that know more about
  3805. arithmetic. For example, your partial evaluator should translate
  3806. {\if\edition\racketEd
  3807. \[
  3808. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3809. \code{(+ 2 (read))}
  3810. \]
  3811. \fi}
  3812. {\if\edition\pythonEd\pythonColor
  3813. \[
  3814. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3815. \code{2 + input\_int()}
  3816. \]
  3817. \fi}
  3818. %
  3819. To accomplish this, the \code{pe\_exp} function should produce output
  3820. in the form of the $\itm{residual}$ nonterminal of the following
  3821. grammar. The idea is that when processing an addition expression, we
  3822. can always produce one of the following: (1) an integer constant, (2)
  3823. an addition expression with an integer constant on the left-hand side
  3824. but not the right-hand side, or (3) an addition expression in which
  3825. neither subexpression is a constant.
  3826. %
  3827. {\if\edition\racketEd
  3828. \[
  3829. \begin{array}{lcl}
  3830. \itm{inert} &::=& \Var
  3831. \MID \LP\key{read}\RP
  3832. \MID \LP\key{-} ~\Var\RP
  3833. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3834. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3835. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3836. \itm{residual} &::=& \Int
  3837. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3838. \MID \itm{inert}
  3839. \end{array}
  3840. \]
  3841. \fi}
  3842. {\if\edition\pythonEd\pythonColor
  3843. \[
  3844. \begin{array}{lcl}
  3845. \itm{inert} &::=& \Var
  3846. \MID \key{input\_int}\LP\RP
  3847. \MID \key{-} \Var
  3848. \MID \key{-} \key{input\_int}\LP\RP
  3849. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3850. \itm{residual} &::=& \Int
  3851. \MID \Int ~ \key{+} ~ \itm{inert}
  3852. \MID \itm{inert}
  3853. \end{array}
  3854. \]
  3855. \fi}
  3856. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3857. inputs are $\itm{residual}$ expressions and they should return
  3858. $\itm{residual}$ expressions. Once the improvements are complete,
  3859. make sure that your compiler still passes all the tests. After
  3860. all, fast code is useless if it produces incorrect results!
  3861. \end{exercise}
  3862. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3863. {\if\edition\pythonEd\pythonColor
  3864. \chapter{Parsing}
  3865. \label{ch:parsing}
  3866. \setcounter{footnote}{0}
  3867. \index{subject}{parsing}
  3868. In this chapter we learn how to use the Lark parser
  3869. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3870. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3871. You will then be asked to use Lark to create a parser for \LangVar{}.
  3872. We also describe the parsing algorithms used inside Lark, studying the
  3873. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3874. A parser framework such as Lark takes in a specification of the
  3875. concrete syntax and an input program and produces a parse tree. Even
  3876. though a parser framework does most of the work for us, using one
  3877. properly requires some knowledge. In particular, we must learn about
  3878. its specification languages and we must learn how to deal with
  3879. ambiguity in our language specifications. Also, some algorithms, such
  3880. as LALR(1), place restrictions on the grammars they can handle, in
  3881. which case knowing the algorithm help with trying to decipher the
  3882. error messages.
  3883. The process of parsing is traditionally subdivided into two phases:
  3884. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3885. analysis} (also called parsing). The lexical analysis phase
  3886. translates the sequence of characters into a sequence of
  3887. \emph{tokens}, that is, words consisting of several characters. The
  3888. parsing phase organizes the tokens into a \emph{parse tree} that
  3889. captures how the tokens were matched by rules in the grammar of the
  3890. language. The reason for the subdivision into two phases is to enable
  3891. the use of a faster but less powerful algorithm for lexical analysis
  3892. and the use of a slower but more powerful algorithm for parsing.
  3893. %
  3894. %% Likewise, parser generators typical come in pairs, with separate
  3895. %% generators for the lexical analyzer (or lexer for short) and for the
  3896. %% parser. A particularly influential pair of generators were
  3897. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3898. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3899. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3900. %% Compiler Compiler.
  3901. %
  3902. The Lark parser framework that we use in this chapter includes both
  3903. lexical analyzers and parsers. The next section discusses lexical
  3904. analysis, and the remainder of the chapter discusses parsing.
  3905. \section{Lexical Analysis and Regular Expressions}
  3906. \label{sec:lex}
  3907. The lexical analyzers produced by Lark turn a sequence of characters
  3908. (a string) into a sequence of token objects. For example, a Lark
  3909. generated lexer for \LangInt{} converts the string
  3910. \begin{lstlisting}
  3911. 'print(1 + 3)'
  3912. \end{lstlisting}
  3913. \noindent into the following sequence of token objects:
  3914. \begin{center}
  3915. \begin{minipage}{0.95\textwidth}
  3916. \begin{lstlisting}
  3917. Token('PRINT', 'print')
  3918. Token('LPAR', '(')
  3919. Token('INT', '1')
  3920. Token('PLUS', '+')
  3921. Token('INT', '3')
  3922. Token('RPAR', ')')
  3923. Token('NEWLINE', '\n')
  3924. \end{lstlisting}
  3925. \end{minipage}
  3926. \end{center}
  3927. Each token includes a field for its \code{type}, such as \skey{INT},
  3928. and a field for its \code{value}, such as \skey{1}.
  3929. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3930. specification language for Lark's lexer is one regular expression for
  3931. each type of token. The term \emph{regular} comes from the term
  3932. \emph{regular languages}, which are the languages that can be
  3933. recognized by a finite state machine. A \emph{regular expression} is a
  3934. pattern formed of the following core elements:\index{subject}{regular
  3935. expression}\footnote{Regular expressions traditionally include the
  3936. empty regular expression that matches any zero-length part of a
  3937. string, but Lark does not support the empty regular expression.}
  3938. \begin{itemize}
  3939. \item A single character $c$ is a regular expression, and it matches
  3940. only itself. For example, the regular expression \code{a} matches
  3941. only the string \skey{a}.
  3942. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3943. R_2$ form a regular expression that matches any string that matches
  3944. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3945. matches the string \skey{a} and the string \skey{c}.
  3946. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3947. expression that matches any string that can be formed by
  3948. concatenating two strings, where the first string matches $R_1$ and
  3949. the second string matches $R_2$. For example, the regular expression
  3950. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3951. (Parentheses can be used to control the grouping of operators within
  3952. a regular expression.)
  3953. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3954. Kleene closure) is a regular expression that matches any string that
  3955. can be formed by concatenating zero or more strings that each match
  3956. the regular expression $R$. For example, the regular expression
  3957. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3958. \skey{abc}.
  3959. \end{itemize}
  3960. For our convenience, Lark also accepts the following extended set of
  3961. regular expressions that are automatically translated into the core
  3962. regular expressions.
  3963. \begin{itemize}
  3964. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3965. c_n]$ is a regular expression that matches any one of the
  3966. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3967. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3968. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3969. a regular expression that matches any character between $c_1$ and
  3970. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3971. letter in the alphabet.
  3972. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3973. is a regular expression that matches any string that can
  3974. be formed by concatenating one or more strings that each match $R$.
  3975. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3976. matches \skey{b} and \skey{bzca}.
  3977. \item A regular expression followed by a question mark $R\ttm{?}$
  3978. is a regular expression that matches any string that either
  3979. matches $R$ or is the empty string.
  3980. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3981. \end{itemize}
  3982. In a Lark grammar file, each kind of token is specified by a
  3983. \emph{terminal}\index{subject}{terminal} which is defined by a rule
  3984. that consists of the name of the terminal followed by a colon followed
  3985. by a sequence of literals. The literals include strings such as
  3986. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  3987. terminal names, and literals composed using the regular expression
  3988. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  3989. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  3990. \begin{center}
  3991. \begin{minipage}{0.95\textwidth}
  3992. \begin{lstlisting}
  3993. DIGIT: /[0-9]/
  3994. INT: "-"? DIGIT+
  3995. NEWLINE: (/\r/? /\n/)+
  3996. \end{lstlisting}
  3997. \end{minipage}
  3998. \end{center}
  3999. \section{Grammars and Parse Trees}
  4000. \label{sec:CFG}
  4001. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4002. specify the abstract syntax of a language. We now take a closer look
  4003. at using grammar rules to specify the concrete syntax. Recall that
  4004. each rule has a left-hand side and a right-hand side where the
  4005. left-hand side is a nonterminal and the right-hand side is a pattern
  4006. that defines what can be parsed as that nonterminal. For concrete
  4007. syntax, each right-hand side expresses a pattern for a string, instead
  4008. of a pattern for an abstract syntax tree. In particular, each
  4009. right-hand side is a sequence of
  4010. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4011. terminal or a nonterminal. The nonterminals play the same role as in
  4012. the abstract syntax, defining categories of syntax. The nonterminals
  4013. of a grammar include the tokens defined in the lexer and all the
  4014. nonterminals defined by the grammar rules.
  4015. As an example, let us take a closer look at the concrete syntax of the
  4016. \LangInt{} language, repeated here.
  4017. \[
  4018. \begin{array}{l}
  4019. \LintGrammarPython \\
  4020. \begin{array}{rcl}
  4021. \LangInt{} &::=& \Stmt^{*}
  4022. \end{array}
  4023. \end{array}
  4024. \]
  4025. The Lark syntax for grammar rules differs slightly from the variant of
  4026. BNF that we use in this book. In particular, the notation $::=$ is
  4027. replaced by a single colon, and the use of typewriter font for string
  4028. literals is replaced by quotation marks. The following grammar serves
  4029. as a first draft of a Lark grammar for \LangInt{}.
  4030. \begin{center}
  4031. \begin{minipage}{0.95\textwidth}
  4032. \begin{lstlisting}[escapechar=$]
  4033. exp: INT
  4034. | "input_int" "(" ")"
  4035. | "-" exp
  4036. | exp "+" exp
  4037. | exp "-" exp
  4038. | "(" exp ")"
  4039. stmt_list:
  4040. | stmt NEWLINE stmt_list
  4041. lang_int: stmt_list
  4042. \end{lstlisting}
  4043. \end{minipage}
  4044. \end{center}
  4045. Let us begin by discussing the rule \code{exp: INT}, which says that
  4046. if the lexer matches a string to \code{INT}, then the parser also
  4047. categorizes the string as an \code{exp}. Recall that in
  4048. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4049. nonterminal with a sentence in English. Here we specify \code{INT}
  4050. more formally using a type of token \code{INT} and its regular
  4051. expression \code{"-"? DIGIT+}.
  4052. The rule \code{exp: exp "+" exp} says that any string that matches
  4053. \code{exp}, followed by the \code{+} character, followed by another
  4054. string that matches \code{exp}, is itself an \code{exp}. For example,
  4055. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4056. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4057. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4058. \code{exp}. We can visualize the application of grammar rules to parse
  4059. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4060. internal node in the tree is an application of a grammar rule and is
  4061. labeled with its left-hand side nonterminal. Each leaf node is a
  4062. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4063. shown in figure~\ref{fig:simple-parse-tree}.
  4064. \begin{figure}[tbp]
  4065. \begin{tcolorbox}[colback=white]
  4066. \centering
  4067. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4068. \end{tcolorbox}
  4069. \caption{The parse tree for \lstinline{'1+3'}.}
  4070. \label{fig:simple-parse-tree}
  4071. \end{figure}
  4072. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4073. following parse tree as represented by \code{Tree} and \code{Token}
  4074. objects.
  4075. \begin{lstlisting}
  4076. Tree('lang_int',
  4077. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4078. Tree('exp', [Token('INT', '3')])])]),
  4079. Token('NEWLINE', '\n')])
  4080. \end{lstlisting}
  4081. The nodes that come from the lexer are \code{Token} objects, whereas
  4082. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4083. object has a \code{data} field containing the name of the nonterminal
  4084. for the grammar rule that was applied. Each \code{Tree} object also
  4085. has a \code{children} field that is a list containing trees and/or
  4086. tokens. Note that Lark does not produce nodes for string literals in
  4087. the grammar. For example, the \code{Tree} node for the addition
  4088. expression has only two children for the two integers but is missing
  4089. its middle child for the \code{"+"} terminal. This would be
  4090. problematic except that Lark provides a mechanism for customizing the
  4091. \code{data} field of each \code{Tree} node on the basis of which rule was
  4092. applied. Next to each alternative in a grammar rule, write \code{->}
  4093. followed by a string that you want to appear in the \code{data}
  4094. field. The following is a second draft of a Lark grammar for
  4095. \LangInt{}, this time with more specific labels on the \code{Tree}
  4096. nodes.
  4097. \begin{center}
  4098. \begin{minipage}{0.95\textwidth}
  4099. \begin{lstlisting}[escapechar=$]
  4100. exp: INT -> int
  4101. | "input_int" "(" ")" -> input_int
  4102. | "-" exp -> usub
  4103. | exp "+" exp -> add
  4104. | exp "-" exp -> sub
  4105. | "(" exp ")" -> paren
  4106. stmt: "print" "(" exp ")" -> print
  4107. | exp -> expr
  4108. stmt_list: -> empty_stmt
  4109. | stmt NEWLINE stmt_list -> add_stmt
  4110. lang_int: stmt_list -> module
  4111. \end{lstlisting}
  4112. \end{minipage}
  4113. \end{center}
  4114. Here is the resulting parse tree.
  4115. \begin{lstlisting}
  4116. Tree('module',
  4117. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4118. Tree('int', [Token('INT', '3')])])]),
  4119. Token('NEWLINE', '\n')])
  4120. \end{lstlisting}
  4121. \section{Ambiguous Grammars}
  4122. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4123. can be parsed in more than one way. For example, consider the string
  4124. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4125. our draft grammar, resulting in the two parse trees shown in
  4126. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4127. interpreting the second parse tree would yield \code{-4} even through
  4128. the correct answer is \code{2}.
  4129. \begin{figure}[tbp]
  4130. \begin{tcolorbox}[colback=white]
  4131. \centering
  4132. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4133. \end{tcolorbox}
  4134. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4135. \label{fig:ambig-parse-tree}
  4136. \end{figure}
  4137. To deal with this problem we can change the grammar by categorizing
  4138. the syntax in a more fine-grained fashion. In this case we want to
  4139. disallow the application of the rule \code{exp: exp "-" exp} when the
  4140. child on the right is an addition. To do this we can replace the
  4141. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4142. the expressions except for addition, as in the following.
  4143. \begin{center}
  4144. \begin{minipage}{0.95\textwidth}
  4145. \begin{lstlisting}[escapechar=$]
  4146. exp: exp "-" exp_no_add -> sub
  4147. | exp "+" exp -> add
  4148. | exp_no_add
  4149. exp_no_add: INT -> int
  4150. | "input_int" "(" ")" -> input_int
  4151. | "-" exp -> usub
  4152. | exp "-" exp_no_add -> sub
  4153. | "(" exp ")" -> paren
  4154. \end{lstlisting}
  4155. \end{minipage}
  4156. \end{center}
  4157. However, there remains some ambiguity in the grammar. For example, the
  4158. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4159. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4160. (incorrect). That is, subtraction is left associative. Likewise,
  4161. addition in Python is left associative. We also need to consider the
  4162. interaction of unary subtraction with both addition and
  4163. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4164. has higher \emph{precedence}\index{subject}{precedence} than addition
  4165. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4166. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4167. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4168. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4169. all the other expressions, and it uses \code{exp\_hi} for the second
  4170. child in the rules for addition and subtraction. Furthermore, unary
  4171. subtraction uses \code{exp\_hi} for its child.
  4172. For languages with more operators and more precedence levels, one must
  4173. refine the \code{exp} nonterminal into several nonterminals, one for
  4174. each precedence level.
  4175. \begin{figure}[tbp]
  4176. \begin{tcolorbox}[colback=white]
  4177. \centering
  4178. \begin{lstlisting}[escapechar=$]
  4179. exp: exp "+" exp_hi -> add
  4180. | exp "-" exp_hi -> sub
  4181. | exp_hi
  4182. exp_hi: INT -> int
  4183. | "input_int" "(" ")" -> input_int
  4184. | "-" exp_hi -> usub
  4185. | "(" exp ")" -> paren
  4186. stmt: "print" "(" exp ")" -> print
  4187. | exp -> expr
  4188. stmt_list: -> empty_stmt
  4189. | stmt NEWLINE stmt_list -> add_stmt
  4190. lang_int: stmt_list -> module
  4191. \end{lstlisting}
  4192. \end{tcolorbox}
  4193. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4194. \label{fig:Lint-lark-grammar}
  4195. \end{figure}
  4196. \section{From Parse Trees to Abstract Syntax Trees}
  4197. As we have seen, the output of a Lark parser is a parse tree, that is,
  4198. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4199. step is to convert the parse tree to an abstract syntax tree. This can
  4200. be accomplished with a recursive function that inspects the
  4201. \code{data} field of each node and then constructs the corresponding
  4202. AST node, using recursion to handle its children. The following is an
  4203. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4204. \begin{center}
  4205. \begin{minipage}{0.95\textwidth}
  4206. \begin{lstlisting}
  4207. def parse_tree_to_ast(e):
  4208. if e.data == 'int':
  4209. return Constant(int(e.children[0].value))
  4210. elif e.data == 'input_int':
  4211. return Call(Name('input_int'), [])
  4212. elif e.data == 'add':
  4213. e1, e2 = e.children
  4214. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4215. ...
  4216. else:
  4217. raise Exception('unhandled parse tree', e)
  4218. \end{lstlisting}
  4219. \end{minipage}
  4220. \end{center}
  4221. \begin{exercise}
  4222. \normalfont\normalsize
  4223. %
  4224. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4225. default parsing algorithm (Earley) with the \code{ambiguity} option
  4226. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4227. output will include multiple parse trees that will indicate to you
  4228. that there is a problem with your grammar. Your parser should ignore
  4229. white space, so we recommend using Lark's \code{\%ignore} directive
  4230. as follows.
  4231. \begin{lstlisting}
  4232. WS: /[ \t\f\r\n]/+
  4233. %ignore WS
  4234. \end{lstlisting}
  4235. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4236. Lark parser instead of using the \code{parse} function from
  4237. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4238. programs that you have created, and create four additional programs
  4239. that test for ambiguities in your grammar.
  4240. \end{exercise}
  4241. \section{Earley's Algorithm}
  4242. \label{sec:earley}
  4243. In this section we discuss the parsing algorithm of
  4244. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4245. algorithm is powerful in that it can handle any context-free grammar,
  4246. which makes it easy to use. However, it is not a particularly
  4247. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4248. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4249. the number of tokens in the input
  4250. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4251. learn about the LALR(1) algorithm, which is more efficient but cannot
  4252. handle all context-free grammars.
  4253. Earley's algorithm can be viewed as an interpreter; it treats the
  4254. grammar as the program being interpreted and it treats the concrete
  4255. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4256. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4257. keep track of its progress and to store its results. The chart is an
  4258. array with one slot for each position in the input string, where
  4259. position $0$ is before the first character and position $n$ is
  4260. immediately after the last character. So, the array has length $n+1$
  4261. for an input string of length $n$. Each slot in the chart contains a
  4262. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4263. with a period indicating how much of its right-hand side has already
  4264. been parsed. For example, the dotted rule
  4265. \begin{lstlisting}
  4266. exp: exp "+" . exp_hi
  4267. \end{lstlisting}
  4268. represents a partial parse that has matched an \code{exp} followed by
  4269. \code{+}, but has not yet parsed an \code{exp} to the right of
  4270. \code{+}.
  4271. %
  4272. Earley's algorithm starts with an initialization phase, and then
  4273. repeats three actions---prediction, scanning, and completion---for as
  4274. long as opportunities arise. We demonstrate Earley's algorithm on a
  4275. running example, parsing the following program:
  4276. \begin{lstlisting}
  4277. print(1 + 3)
  4278. \end{lstlisting}
  4279. The algorithm's initialization phase creates dotted rules for all the
  4280. grammar rules whose left-hand side is the start symbol and places them
  4281. in slot $0$ of the chart. We also record the starting position of the
  4282. dotted rule in parentheses on the right. For example, given the
  4283. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4284. \begin{lstlisting}
  4285. lang_int: . stmt_list (0)
  4286. \end{lstlisting}
  4287. in slot $0$ of the chart. The algorithm then proceeds with
  4288. \emph{prediction} actions in which it adds more dotted rules to the
  4289. chart based on the nonterminals that come immediately after a period. In
  4290. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4291. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4292. period at the beginning of their right-hand sides, as follows:
  4293. \begin{lstlisting}
  4294. stmt_list: . (0)
  4295. stmt_list: . stmt NEWLINE stmt_list (0)
  4296. \end{lstlisting}
  4297. We continue to perform prediction actions as more opportunities
  4298. arise. For example, the \code{stmt} nonterminal now appears after a
  4299. period, so we add all the rules for \code{stmt}.
  4300. \begin{lstlisting}
  4301. stmt: . "print" "(" exp ")" (0)
  4302. stmt: . exp (0)
  4303. \end{lstlisting}
  4304. This reveals yet more opportunities for prediction, so we add the grammar
  4305. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4306. \begin{lstlisting}[escapechar=$]
  4307. exp: . exp "+" exp_hi (0)
  4308. exp: . exp "-" exp_hi (0)
  4309. exp: . exp_hi (0)
  4310. exp_hi: . INT (0)
  4311. exp_hi: . "input_int" "(" ")" (0)
  4312. exp_hi: . "-" exp_hi (0)
  4313. exp_hi: . "(" exp ")" (0)
  4314. \end{lstlisting}
  4315. We have exhausted the opportunities for prediction, so the algorithm
  4316. proceeds to \emph{scanning}, in which we inspect the next input token
  4317. and look for a dotted rule at the current position that has a matching
  4318. terminal immediately following the period. In our running example, the
  4319. first input token is \code{"print"}, so we identify the rule in slot
  4320. $0$ of the chart where \code{"print"} follows the period:
  4321. \begin{lstlisting}
  4322. stmt: . "print" "(" exp ")" (0)
  4323. \end{lstlisting}
  4324. We advance the period past \code{"print"} and add the resulting rule
  4325. to slot $1$ of the chart:
  4326. \begin{lstlisting}
  4327. stmt: "print" . "(" exp ")" (0)
  4328. \end{lstlisting}
  4329. If the new dotted rule had a nonterminal after the period, we would
  4330. need to carry out a prediction action, adding more dotted rules to
  4331. slot $1$. That is not the case, so we continue scanning. The next
  4332. input token is \code{"("}, so we add the following to slot $2$ of the
  4333. chart.
  4334. \begin{lstlisting}
  4335. stmt: "print" "(" . exp ")" (0)
  4336. \end{lstlisting}
  4337. Now we have a nonterminal after the period, so we carry out several
  4338. prediction actions, adding dotted rules for \code{exp} and
  4339. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4340. starting position $2$.
  4341. \begin{lstlisting}[escapechar=$]
  4342. exp: . exp "+" exp_hi (2)
  4343. exp: . exp "-" exp_hi (2)
  4344. exp: . exp_hi (2)
  4345. exp_hi: . INT (2)
  4346. exp_hi: . "input_int" "(" ")" (2)
  4347. exp_hi: . "-" exp_hi (2)
  4348. exp_hi: . "(" exp ")" (2)
  4349. \end{lstlisting}
  4350. With this prediction complete, we return to scanning, noting that the
  4351. next input token is \code{"1"}, which the lexer parses as an
  4352. \code{INT}. There is a matching rule in slot $2$:
  4353. \begin{lstlisting}
  4354. exp_hi: . INT (2)
  4355. \end{lstlisting}
  4356. so we advance the period and put the following rule into slot $3$.
  4357. \begin{lstlisting}
  4358. exp_hi: INT . (2)
  4359. \end{lstlisting}
  4360. This brings us to \emph{completion} actions. When the period reaches
  4361. the end of a dotted rule, we recognize that the substring
  4362. has matched the nonterminal on the left-hand side of the rule, in this case
  4363. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4364. rules into slot $2$ (the starting position for the finished rule) if
  4365. the period is immediately followed by \code{exp\_hi}. So we identify
  4366. \begin{lstlisting}
  4367. exp: . exp_hi (2)
  4368. \end{lstlisting}
  4369. and add the following dotted rule to slot $3$
  4370. \begin{lstlisting}
  4371. exp: exp_hi . (2)
  4372. \end{lstlisting}
  4373. This triggers another completion step for the nonterminal \code{exp},
  4374. adding two more dotted rules to slot $3$.
  4375. \begin{lstlisting}[escapechar=$]
  4376. exp: exp . "+" exp_hi (2)
  4377. exp: exp . "-" exp_hi (2)
  4378. \end{lstlisting}
  4379. Returning to scanning, the next input token is \code{"+"}, so
  4380. we add the following to slot $4$.
  4381. \begin{lstlisting}[escapechar=$]
  4382. exp: exp "+" . exp_hi (2)
  4383. \end{lstlisting}
  4384. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4385. the following dotted rules to slot $4$ of the chart.
  4386. \begin{lstlisting}[escapechar=$]
  4387. exp_hi: . INT (4)
  4388. exp_hi: . "input_int" "(" ")" (4)
  4389. exp_hi: . "-" exp_hi (4)
  4390. exp_hi: . "(" exp ")" (4)
  4391. \end{lstlisting}
  4392. The next input token is \code{"3"} which the lexer categorized as an
  4393. \code{INT}, so we advance the period past \code{INT} for the rules in
  4394. slot $4$, of which there is just one, and put the following into slot $5$.
  4395. \begin{lstlisting}[escapechar=$]
  4396. exp_hi: INT . (4)
  4397. \end{lstlisting}
  4398. The period at the end of the rule triggers a completion action for the
  4399. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4400. So we advance the period and put the following into slot $5$.
  4401. \begin{lstlisting}[escapechar=$]
  4402. exp: exp "+" exp_hi . (2)
  4403. \end{lstlisting}
  4404. This triggers another completion action for the rules in slot $2$ that
  4405. have a period before \code{exp}.
  4406. \begin{lstlisting}[escapechar=$]
  4407. stmt: "print" "(" exp . ")" (0)
  4408. exp: exp . "+" exp_hi (2)
  4409. exp: exp . "-" exp_hi (2)
  4410. \end{lstlisting}
  4411. We scan the next input token \code{")"}, placing the following dotted
  4412. rule into slot $6$.
  4413. \begin{lstlisting}[escapechar=$]
  4414. stmt: "print" "(" exp ")" . (0)
  4415. \end{lstlisting}
  4416. This triggers the completion of \code{stmt} in slot $0$
  4417. \begin{lstlisting}
  4418. stmt_list: stmt . NEWLINE stmt_list (0)
  4419. \end{lstlisting}
  4420. The last input token is a \code{NEWLINE}, so we advance the period
  4421. and place the new dotted rule into slot $7$.
  4422. \begin{lstlisting}
  4423. stmt_list: stmt NEWLINE . stmt_list (0)
  4424. \end{lstlisting}
  4425. We are close to the end of parsing the input!
  4426. The period is before the \code{stmt\_list} nonterminal, so we
  4427. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4428. \begin{lstlisting}
  4429. stmt_list: . (7)
  4430. stmt_list: . stmt NEWLINE stmt_list (7)
  4431. stmt: . "print" "(" exp ")" (7)
  4432. stmt: . exp (7)
  4433. \end{lstlisting}
  4434. There is immediately an opportunity for completion of \code{stmt\_list},
  4435. so we add the following to slot $7$.
  4436. \begin{lstlisting}
  4437. stmt_list: stmt NEWLINE stmt_list . (0)
  4438. \end{lstlisting}
  4439. This triggers another completion action for \code{stmt\_list} in slot $0$
  4440. \begin{lstlisting}
  4441. lang_int: stmt_list . (0)
  4442. \end{lstlisting}
  4443. which in turn completes \code{lang\_int}, the start symbol of the
  4444. grammar, so the parsing of the input is complete.
  4445. For reference, we now give a general description of Earley's
  4446. algorithm.
  4447. \begin{enumerate}
  4448. \item The algorithm begins by initializing slot $0$ of the chart with the
  4449. grammar rule for the start symbol, placing a period at the beginning
  4450. of the right-hand side, and recording its starting position as $0$.
  4451. \item The algorithm repeatedly applies the following three kinds of
  4452. actions for as long as there are opportunities to do so.
  4453. \begin{itemize}
  4454. \item Prediction: If there is a rule in slot $k$ whose period comes
  4455. before a nonterminal, add the rules for that nonterminal into slot
  4456. $k$, placing a period at the beginning of their right-hand sides
  4457. and recording their starting position as $k$.
  4458. \item Scanning: If the token at position $k$ of the input string
  4459. matches the symbol after the period in a dotted rule in slot $k$
  4460. of the chart, advance the period in the dotted rule, adding
  4461. the result to slot $k+1$.
  4462. \item Completion: If a dotted rule in slot $k$ has a period at the
  4463. end, inspect the rules in the slot corresponding to the starting
  4464. position of the completed rule. If any of those rules have a
  4465. nonterminal following their period that matches the left-hand side
  4466. of the completed rule, then advance their period, placing the new
  4467. dotted rule in slot $k$.
  4468. \end{itemize}
  4469. While repeating these three actions, take care never to add
  4470. duplicate dotted rules to the chart.
  4471. \end{enumerate}
  4472. We have described how Earley's algorithm recognizes that an input
  4473. string matches a grammar, but we have not described how it builds a
  4474. parse tree. The basic idea is simple, but building parse trees in an
  4475. efficient way is more complex, requiring a data structure called a
  4476. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4477. to attach a partial parse tree to every dotted rule in the chart.
  4478. Initially, the tree node associated with a dotted rule has no
  4479. children. As the period moves to the right, the nodes from the
  4480. subparses are added as children to the tree node.
  4481. As mentioned at the beginning of this section, Earley's algorithm is
  4482. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4483. files that contain thousands of tokens in a reasonable amount of time,
  4484. but not millions.
  4485. %
  4486. In the next section we discuss the LALR(1) parsing algorithm, which is
  4487. efficient enough to use with even the largest of input files.
  4488. \section{The LALR(1) Algorithm}
  4489. \label{sec:lalr}
  4490. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4491. two-phase approach in which it first compiles the grammar into a state
  4492. machine and then runs the state machine to parse an input string. The
  4493. second phase has time complexity $O(n)$ where $n$ is the number of
  4494. tokens in the input, so LALR(1) is the best one could hope for with
  4495. respect to efficiency.
  4496. %
  4497. A particularly influential implementation of LALR(1) is the
  4498. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4499. \texttt{yacc} stands for ``yet another compiler compiler''.
  4500. %
  4501. The LALR(1) state machine uses a stack to record its progress in
  4502. parsing the input string. Each element of the stack is a pair: a
  4503. state number and a grammar symbol (a terminal or a nonterminal). The
  4504. symbol characterizes the input that has been parsed so far, and the
  4505. state number is used to remember how to proceed once the next
  4506. symbol's worth of input has been parsed. Each state in the machine
  4507. represents where the parser stands in the parsing process with respect
  4508. to certain grammar rules. In particular, each state is associated with
  4509. a set of dotted rules.
  4510. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4511. (also called parse table) for the following simple but ambiguous
  4512. grammar:
  4513. \begin{lstlisting}[escapechar=$]
  4514. exp: INT
  4515. | exp "+" exp
  4516. stmt: "print" exp
  4517. start: stmt
  4518. \end{lstlisting}
  4519. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4520. read in a \lstinline{"print"} token, so the top of the stack is
  4521. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4522. the input according to grammar rule 1, which is signified by showing
  4523. rule 1 with a period after the \code{"print"} token and before the
  4524. \code{exp} nonterminal. There are two rules that could apply next,
  4525. rules 2 and 3, so state 1 also shows those rules with a period at
  4526. the beginning of their right-hand sides. The edges between states
  4527. indicate which transitions the machine should make depending on the
  4528. next input token. So, for example, if the next input token is
  4529. \code{INT} then the parser will push \code{INT} and the target state 4
  4530. on the stack and transition to state 4. Suppose that we are now at the end
  4531. of the input. State 4 says that we should reduce by rule 3, so we pop
  4532. from the stack the same number of items as the number of symbols in
  4533. the right-hand side of the rule, in this case just one. We then
  4534. momentarily jump to the state at the top of the stack (state 1) and
  4535. then follow the goto edge that corresponds to the left-hand side of
  4536. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4537. state 3. (A slightly longer example parse is shown in
  4538. figure~\ref{fig:shift-reduce}.)
  4539. \begin{figure}[htbp]
  4540. \centering
  4541. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4542. \caption{An LALR(1) parse table and a trace of an example run.}
  4543. \label{fig:shift-reduce}
  4544. \end{figure}
  4545. In general, the algorithm works as follows. First, set the current state to
  4546. state $0$. Then repeat the following, looking at the next input token.
  4547. \begin{itemize}
  4548. \item If there there is a shift edge for the input token in the
  4549. current state, push the edge's target state and the input token onto
  4550. the stack and proceed to the edge's target state.
  4551. \item If there is a reduce action for the input token in the current
  4552. state, pop $k$ elements from the stack, where $k$ is the number of
  4553. symbols in the right-hand side of the rule being reduced. Jump to
  4554. the state at the top of the stack and then follow the goto edge for
  4555. the nonterminal that matches the left-hand side of the rule that we
  4556. are reducing by. Push the edge's target state and the nonterminal on the
  4557. stack.
  4558. \end{itemize}
  4559. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4560. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4561. algorithm does not know which action to take in this case. When a
  4562. state has both a shift and a reduce action for the same token, we say
  4563. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4564. will arise, for example, in trying to parse the input
  4565. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4566. the parser will be in state 6 and will not know whether to
  4567. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4568. to proceed by shifting the next \lstinline{+} from the input.
  4569. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4570. arises when there are two reduce actions in a state for the same
  4571. token. To understand which grammars give rise to shift/reduce and
  4572. reduce/reduce conflicts, it helps to know how the parse table is
  4573. generated from the grammar, which we discuss next.
  4574. The parse table is generated one state at a time. State 0 represents
  4575. the start of the parser. We add the grammar rule for the start symbol
  4576. to this state with a period at the beginning of the right-hand side,
  4577. similarly to the initialization phase of the Earley parser. If the
  4578. period appears immediately before another nonterminal, we add all the
  4579. rules with that nonterminal on the left-hand side. Again, we place a
  4580. period at the beginning of the right-hand side of each new
  4581. rule. This process, called \emph{state closure}, is continued
  4582. until there are no more rules to add (similarly to the prediction
  4583. actions of an Earley parser). We then examine each dotted rule in the
  4584. current state $I$. Suppose that a dotted rule has the form $A ::=
  4585. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4586. are sequences of symbols. We create a new state and call it $J$. If $X$
  4587. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4588. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4589. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4590. state $J$. We start by adding all dotted rules from state $I$ that
  4591. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4592. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4593. the period moved past the $X$. (This is analogous to completion in
  4594. Earley's algorithm.) We then perform state closure on $J$. This
  4595. process repeats until there are no more states or edges to add.
  4596. We then mark states as accepting states if they have a dotted rule
  4597. that is the start rule with a period at the end. Also, to add
  4598. the reduce actions, we look for any state containing a dotted rule
  4599. with a period at the end. Let $n$ be the rule number for this dotted
  4600. rule. We then put a reduce $n$ action into that state for every token
  4601. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4602. dotted rule with a period at the end. We therefore put a reduce by
  4603. rule 3 action into state 4 for every
  4604. token.
  4605. When inserting reduce actions, take care to spot any shift/reduce or
  4606. reduce/reduce conflicts. If there are any, abort the construction of
  4607. the parse table.
  4608. \begin{exercise}
  4609. \normalfont\normalsize
  4610. %
  4611. Working on paper, walk through the parse table generation process for
  4612. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4613. your results against the parse table shown in
  4614. figure~\ref{fig:shift-reduce}.
  4615. \end{exercise}
  4616. \begin{exercise}
  4617. \normalfont\normalsize
  4618. %
  4619. Change the parser in your compiler for \LangVar{} to set the
  4620. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4621. all the \LangVar{} programs that you have created. In doing so, Lark
  4622. may signal an error due to shift/reduce or reduce/reduce conflicts
  4623. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4624. remove those conflicts.
  4625. \end{exercise}
  4626. \section{Further Reading}
  4627. In this chapter we have just scratched the surface of the field of
  4628. parsing, with the study of a very general but less efficient algorithm
  4629. (Earley) and with a more limited but highly efficient algorithm
  4630. (LALR). There are many more algorithms and classes of grammars that
  4631. fall between these two ends of the spectrum. We recommend to the reader
  4632. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4633. Regarding lexical analysis, we have described the specification
  4634. language, which are the regular expressions, but not the algorithms
  4635. for recognizing them. In short, regular expressions can be translated
  4636. to nondeterministic finite automata, which in turn are translated to
  4637. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4638. all the details on lexical analysis.
  4639. \fi}
  4640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4641. \chapter{Register Allocation}
  4642. \label{ch:register-allocation-Lvar}
  4643. \setcounter{footnote}{0}
  4644. \index{subject}{register allocation}
  4645. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4646. storing variables on the procedure call stack. The CPU may require tens
  4647. to hundreds of cycles to access a location on the stack, whereas
  4648. accessing a register takes only a single cycle. In this chapter we
  4649. improve the efficiency of our generated code by storing some variables
  4650. in registers. The goal of register allocation is to fit as many
  4651. variables into registers as possible. Some programs have more
  4652. variables than registers, so we cannot always map each variable to a
  4653. different register. Fortunately, it is common for different variables
  4654. to be in use during different periods of time during program
  4655. execution, and in those cases we can map multiple variables to the
  4656. same register.
  4657. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4658. example. The source program is on the left and the output of
  4659. instruction selection\index{subject}{instruction selection}
  4660. is on the right. The program is almost
  4661. completely in the x86 assembly language, but it still uses variables.
  4662. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4663. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4664. the other hand, is used only after this point, so \code{x} and
  4665. \code{z} could share the same register.
  4666. \begin{figure}
  4667. \begin{tcolorbox}[colback=white]
  4668. \begin{minipage}{0.45\textwidth}
  4669. Example \LangVar{} program:
  4670. % var_test_28.rkt
  4671. {\if\edition\racketEd
  4672. \begin{lstlisting}
  4673. (let ([v 1])
  4674. (let ([w 42])
  4675. (let ([x (+ v 7)])
  4676. (let ([y x])
  4677. (let ([z (+ x w)])
  4678. (+ z (- y)))))))
  4679. \end{lstlisting}
  4680. \fi}
  4681. {\if\edition\pythonEd\pythonColor
  4682. \begin{lstlisting}
  4683. v = 1
  4684. w = 42
  4685. x = v + 7
  4686. y = x
  4687. z = x + w
  4688. print(z + (- y))
  4689. \end{lstlisting}
  4690. \fi}
  4691. \end{minipage}
  4692. \begin{minipage}{0.45\textwidth}
  4693. After instruction selection:
  4694. {\if\edition\racketEd
  4695. \begin{lstlisting}
  4696. locals-types:
  4697. x : Integer, y : Integer,
  4698. z : Integer, t : Integer,
  4699. v : Integer, w : Integer
  4700. start:
  4701. movq $1, v
  4702. movq $42, w
  4703. movq v, x
  4704. addq $7, x
  4705. movq x, y
  4706. movq x, z
  4707. addq w, z
  4708. movq y, t
  4709. negq t
  4710. movq z, %rax
  4711. addq t, %rax
  4712. jmp conclusion
  4713. \end{lstlisting}
  4714. \fi}
  4715. {\if\edition\pythonEd\pythonColor
  4716. \begin{lstlisting}
  4717. movq $1, v
  4718. movq $42, w
  4719. movq v, x
  4720. addq $7, x
  4721. movq x, y
  4722. movq x, z
  4723. addq w, z
  4724. movq y, tmp_0
  4725. negq tmp_0
  4726. movq z, tmp_1
  4727. addq tmp_0, tmp_1
  4728. movq tmp_1, %rdi
  4729. callq print_int
  4730. \end{lstlisting}
  4731. \fi}
  4732. \end{minipage}
  4733. \end{tcolorbox}
  4734. \caption{A running example for register allocation.}
  4735. \label{fig:reg-eg}
  4736. \end{figure}
  4737. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4738. compute where a variable is in use. Once we have that information, we
  4739. compute which variables are in use at the same time, that is, which ones
  4740. \emph{interfere}\index{subject}{interfere} with each other, and
  4741. represent this relation as an undirected graph whose vertices are
  4742. variables and edges indicate when two variables interfere
  4743. (section~\ref{sec:build-interference}). We then model register
  4744. allocation as a graph coloring problem
  4745. (section~\ref{sec:graph-coloring}).
  4746. If we run out of registers despite these efforts, we place the
  4747. remaining variables on the stack, similarly to how we handled
  4748. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4749. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4750. location. The decision to spill a variable is handled as part of the
  4751. graph coloring process.
  4752. We make the simplifying assumption that each variable is assigned to
  4753. one location (a register or stack address). A more sophisticated
  4754. approach is to assign a variable to one or more locations in different
  4755. regions of the program. For example, if a variable is used many times
  4756. in short sequence and then used again only after many other
  4757. instructions, it could be more efficient to assign the variable to a
  4758. register during the initial sequence and then move it to the stack for
  4759. the rest of its lifetime. We refer the interested reader to
  4760. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4761. approach.
  4762. % discuss prioritizing variables based on how much they are used.
  4763. \section{Registers and Calling Conventions}
  4764. \label{sec:calling-conventions}
  4765. \index{subject}{calling conventions}
  4766. As we perform register allocation, we must be aware of the
  4767. \emph{calling conventions} \index{subject}{calling conventions} that
  4768. govern how function calls are performed in x86.
  4769. %
  4770. Even though \LangVar{} does not include programmer-defined functions,
  4771. our generated code includes a \code{main} function that is called by
  4772. the operating system and our generated code contains calls to the
  4773. \code{read\_int} function.
  4774. Function calls require coordination between two pieces of code that
  4775. may be written by different programmers or generated by different
  4776. compilers. Here we follow the System V calling conventions that are
  4777. used by the GNU C compiler on Linux and
  4778. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4779. %
  4780. The calling conventions include rules about how functions share the
  4781. use of registers. In particular, the caller is responsible for freeing
  4782. some registers prior to the function call for use by the callee.
  4783. These are called the \emph{caller-saved registers}
  4784. \index{subject}{caller-saved registers}
  4785. and they are
  4786. \begin{lstlisting}
  4787. rax rcx rdx rsi rdi r8 r9 r10 r11
  4788. \end{lstlisting}
  4789. On the other hand, the callee is responsible for preserving the values
  4790. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4791. which are
  4792. \begin{lstlisting}
  4793. rsp rbp rbx r12 r13 r14 r15
  4794. \end{lstlisting}
  4795. We can think about this caller/callee convention from two points of
  4796. view, the caller view and the callee view, as follows:
  4797. \begin{itemize}
  4798. \item The caller should assume that all the caller-saved registers get
  4799. overwritten with arbitrary values by the callee. On the other hand,
  4800. the caller can safely assume that all the callee-saved registers
  4801. retain their original values.
  4802. \item The callee can freely use any of the caller-saved registers.
  4803. However, if the callee wants to use a callee-saved register, the
  4804. callee must arrange to put the original value back in the register
  4805. prior to returning to the caller. This can be accomplished by saving
  4806. the value to the stack in the prelude of the function and restoring
  4807. the value in the conclusion of the function.
  4808. \end{itemize}
  4809. In x86, registers are also used for passing arguments to a function
  4810. and for the return value. In particular, the first six arguments of a
  4811. function are passed in the following six registers, in this order.
  4812. \begin{lstlisting}
  4813. rdi rsi rdx rcx r8 r9
  4814. \end{lstlisting}
  4815. We refer to these six registers are the argument-passing registers
  4816. \index{subject}{argument-passing registers}.
  4817. If there are more than six arguments, the convention is to use space
  4818. on the frame of the caller for the rest of the arguments. In
  4819. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4820. argument and the rest of the arguments, which simplifies the treatment
  4821. of efficient tail calls.
  4822. %
  4823. \racket{For now, the only function we care about is \code{read\_int},
  4824. which takes zero arguments.}
  4825. %
  4826. \python{For now, the only functions we care about are \code{read\_int}
  4827. and \code{print\_int}, which take zero and one argument, respectively.}
  4828. %
  4829. The register \code{rax} is used for the return value of a function.
  4830. The next question is how these calling conventions impact register
  4831. allocation. Consider the \LangVar{} program presented in
  4832. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4833. example from the caller point of view and then from the callee point
  4834. of view. We refer to a variable that is in use during a function call
  4835. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4836. The program makes two calls to \READOP{}. The variable \code{x} is
  4837. call-live because it is in use during the second call to \READOP{}; we
  4838. must ensure that the value in \code{x} does not get overwritten during
  4839. the call to \READOP{}. One obvious approach is to save all the values
  4840. that reside in caller-saved registers to the stack prior to each
  4841. function call and to restore them after each call. That way, if the
  4842. register allocator chooses to assign \code{x} to a caller-saved
  4843. register, its value will be preserved across the call to \READOP{}.
  4844. However, saving and restoring to the stack is relatively slow. If
  4845. \code{x} is not used many times, it may be better to assign \code{x}
  4846. to a stack location in the first place. Or better yet, if we can
  4847. arrange for \code{x} to be placed in a callee-saved register, then it
  4848. won't need to be saved and restored during function calls.
  4849. We recommend an approach that captures these issues in the
  4850. interference graph, without complicating the graph coloring algorithm.
  4851. During liveness analysis we know which variables are call-live because
  4852. we compute which variables are in use at every instruction
  4853. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4854. interference graph (section~\ref{sec:build-interference}), we can
  4855. place an edge in the interference graph between each call-live
  4856. variable and the caller-saved registers. This will prevent the graph
  4857. coloring algorithm from assigning call-live variables to caller-saved
  4858. registers.
  4859. On the other hand, for variables that are not call-live, we prefer
  4860. placing them in caller-saved registers to leave more room for
  4861. call-live variables in the callee-saved registers. This can also be
  4862. implemented without complicating the graph coloring algorithm. We
  4863. recommend that the graph coloring algorithm assign variables to
  4864. natural numbers, choosing the lowest number for which there is no
  4865. interference. After the coloring is complete, we map the numbers to
  4866. registers and stack locations: mapping the lowest numbers to
  4867. caller-saved registers, the next lowest to callee-saved registers, and
  4868. the largest numbers to stack locations. This ordering gives preference
  4869. to registers over stack locations and to caller-saved registers over
  4870. callee-saved registers.
  4871. Returning to the example in
  4872. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4873. generated x86 code on the right-hand side. Variable \code{x} is
  4874. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4875. in a safe place during the second call to \code{read\_int}. Next,
  4876. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4877. because \code{y} is not a call-live variable.
  4878. We have completed the analysis from the caller point of view, so now
  4879. we switch to the callee point of view, focusing on the prelude and
  4880. conclusion of the \code{main} function. As usual, the prelude begins
  4881. with saving the \code{rbp} register to the stack and setting the
  4882. \code{rbp} to the current stack pointer. We now know why it is
  4883. necessary to save the \code{rbp}: it is a callee-saved register. The
  4884. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4885. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4886. (\code{x}). The other callee-saved registers are not saved in the
  4887. prelude because they are not used. The prelude subtracts 8 bytes from
  4888. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4889. conclusion, we see that \code{rbx} is restored from the stack with a
  4890. \code{popq} instruction.
  4891. \index{subject}{prelude}\index{subject}{conclusion}
  4892. \begin{figure}[tp]
  4893. \begin{tcolorbox}[colback=white]
  4894. \begin{minipage}{0.45\textwidth}
  4895. Example \LangVar{} program:
  4896. %var_test_14.rkt
  4897. {\if\edition\racketEd
  4898. \begin{lstlisting}
  4899. (let ([x (read)])
  4900. (let ([y (read)])
  4901. (+ (+ x y) 42)))
  4902. \end{lstlisting}
  4903. \fi}
  4904. {\if\edition\pythonEd\pythonColor
  4905. \begin{lstlisting}
  4906. x = input_int()
  4907. y = input_int()
  4908. print((x + y) + 42)
  4909. \end{lstlisting}
  4910. \fi}
  4911. \end{minipage}
  4912. \begin{minipage}{0.45\textwidth}
  4913. Generated x86 assembly:
  4914. {\if\edition\racketEd
  4915. \begin{lstlisting}
  4916. start:
  4917. callq read_int
  4918. movq %rax, %rbx
  4919. callq read_int
  4920. movq %rax, %rcx
  4921. addq %rcx, %rbx
  4922. movq %rbx, %rax
  4923. addq $42, %rax
  4924. jmp _conclusion
  4925. .globl main
  4926. main:
  4927. pushq %rbp
  4928. movq %rsp, %rbp
  4929. pushq %rbx
  4930. subq $8, %rsp
  4931. jmp start
  4932. conclusion:
  4933. addq $8, %rsp
  4934. popq %rbx
  4935. popq %rbp
  4936. retq
  4937. \end{lstlisting}
  4938. \fi}
  4939. {\if\edition\pythonEd\pythonColor
  4940. \begin{lstlisting}
  4941. .globl main
  4942. main:
  4943. pushq %rbp
  4944. movq %rsp, %rbp
  4945. pushq %rbx
  4946. subq $8, %rsp
  4947. callq read_int
  4948. movq %rax, %rbx
  4949. callq read_int
  4950. movq %rax, %rcx
  4951. movq %rbx, %rdx
  4952. addq %rcx, %rdx
  4953. movq %rdx, %rcx
  4954. addq $42, %rcx
  4955. movq %rcx, %rdi
  4956. callq print_int
  4957. addq $8, %rsp
  4958. popq %rbx
  4959. popq %rbp
  4960. retq
  4961. \end{lstlisting}
  4962. \fi}
  4963. \end{minipage}
  4964. \end{tcolorbox}
  4965. \caption{An example with function calls.}
  4966. \label{fig:example-calling-conventions}
  4967. \end{figure}
  4968. %\clearpage
  4969. \section{Liveness Analysis}
  4970. \label{sec:liveness-analysis-Lvar}
  4971. \index{subject}{liveness analysis}
  4972. The \code{uncover\_live} \racket{pass}\python{function} performs
  4973. \emph{liveness analysis}; that is, it discovers which variables are
  4974. in use in different regions of a program.
  4975. %
  4976. A variable or register is \emph{live} at a program point if its
  4977. current value is used at some later point in the program. We refer to
  4978. variables, stack locations, and registers collectively as
  4979. \emph{locations}.
  4980. %
  4981. Consider the following code fragment in which there are two writes to
  4982. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4983. time?
  4984. \begin{center}
  4985. \begin{minipage}{0.85\textwidth}
  4986. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4987. movq $5, a
  4988. movq $30, b
  4989. movq a, c
  4990. movq $10, b
  4991. addq b, c
  4992. \end{lstlisting}
  4993. \end{minipage}
  4994. \end{center}
  4995. The answer is no, because \code{a} is live from line 1 to 3 and
  4996. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4997. line 2 is never used because it is overwritten (line 4) before the
  4998. next read (line 5).
  4999. The live locations for each instruction can be computed by traversing
  5000. the instruction sequence back to front (i.e., backward in execution
  5001. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5002. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5003. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5004. locations before instruction $I_k$. \racket{We recommend representing
  5005. these sets with the Racket \code{set} data structure described in
  5006. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5007. with the Python
  5008. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5009. data structure.}
  5010. {\if\edition\racketEd
  5011. \begin{figure}[tp]
  5012. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5013. \small
  5014. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5015. A \emph{set} is an unordered collection of elements without duplicates.
  5016. Here are some of the operations defined on sets.
  5017. \index{subject}{set}
  5018. \begin{description}
  5019. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5020. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5021. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5022. difference of the two sets.
  5023. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5024. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5025. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5026. \end{description}
  5027. \end{tcolorbox}
  5028. %\end{wrapfigure}
  5029. \caption{The \code{set} data structure.}
  5030. \label{fig:set}
  5031. \end{figure}
  5032. \fi}
  5033. The locations that are live after an instruction are its
  5034. \emph{live-after}\index{subject}{live-after} set, and the locations
  5035. that are live before an instruction are its
  5036. \emph{live-before}\index{subject}{live-before} set. The live-after
  5037. set of an instruction is always the same as the live-before set of the
  5038. next instruction.
  5039. \begin{equation} \label{eq:live-after-before-next}
  5040. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5041. \end{equation}
  5042. To start things off, there are no live locations after the last
  5043. instruction, so
  5044. \begin{equation}\label{eq:live-last-empty}
  5045. L_{\mathsf{after}}(n) = \emptyset
  5046. \end{equation}
  5047. We then apply the following rule repeatedly, traversing the
  5048. instruction sequence back to front.
  5049. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5050. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5051. \end{equation}
  5052. where $W(k)$ are the locations written to by instruction $I_k$, and
  5053. $R(k)$ are the locations read by instruction $I_k$.
  5054. {\if\edition\racketEd
  5055. %
  5056. There is a special case for \code{jmp} instructions. The locations
  5057. that are live before a \code{jmp} should be the locations in
  5058. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5059. maintaining an alist named \code{label->live} that maps each label to
  5060. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5061. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5062. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5063. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5064. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5065. %
  5066. \fi}
  5067. Let us walk through the previous example, applying these formulas
  5068. starting with the instruction on line 5 of the code fragment. We
  5069. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5070. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5071. $\emptyset$ because it is the last instruction
  5072. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5073. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5074. variables \code{b} and \code{c}
  5075. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5076. \[
  5077. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5078. \]
  5079. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5080. the live-before set from line 5 to be the live-after set for this
  5081. instruction (formula~\eqref{eq:live-after-before-next}).
  5082. \[
  5083. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5084. \]
  5085. This move instruction writes to \code{b} and does not read from any
  5086. variables, so we have the following live-before set
  5087. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5088. \[
  5089. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5090. \]
  5091. The live-before for instruction \code{movq a, c}
  5092. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5093. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5094. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5095. variable that is not live and does not read from a variable.
  5096. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5097. because it writes to variable \code{a}.
  5098. \begin{figure}[tbp]
  5099. \centering
  5100. \begin{tcolorbox}[colback=white]
  5101. \hspace{10pt}
  5102. \begin{minipage}{0.4\textwidth}
  5103. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5104. movq $5, a
  5105. movq $30, b
  5106. movq a, c
  5107. movq $10, b
  5108. addq b, c
  5109. \end{lstlisting}
  5110. \end{minipage}
  5111. \vrule\hspace{10pt}
  5112. \begin{minipage}{0.45\textwidth}
  5113. \begin{align*}
  5114. L_{\mathsf{before}}(1)= \emptyset,
  5115. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5116. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5117. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5118. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5119. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5120. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5121. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5122. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5123. L_{\mathsf{after}}(5)= \emptyset
  5124. \end{align*}
  5125. \end{minipage}
  5126. \end{tcolorbox}
  5127. \caption{Example output of liveness analysis on a short example.}
  5128. \label{fig:liveness-example-0}
  5129. \end{figure}
  5130. \begin{exercise}\normalfont\normalsize
  5131. Perform liveness analysis by hand on the running example in
  5132. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5133. sets for each instruction. Compare your answers to the solution
  5134. shown in figure~\ref{fig:live-eg}.
  5135. \end{exercise}
  5136. \begin{figure}[tp]
  5137. \hspace{20pt}
  5138. \begin{minipage}{0.55\textwidth}
  5139. \begin{tcolorbox}[colback=white]
  5140. {\if\edition\racketEd
  5141. \begin{lstlisting}
  5142. |$\{\ttm{rsp}\}$|
  5143. movq $1, v
  5144. |$\{\ttm{v},\ttm{rsp}\}$|
  5145. movq $42, w
  5146. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5147. movq v, x
  5148. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5149. addq $7, x
  5150. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5151. movq x, y
  5152. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5153. movq x, z
  5154. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5155. addq w, z
  5156. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5157. movq y, t
  5158. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5159. negq t
  5160. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5161. movq z, %rax
  5162. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5163. addq t, %rax
  5164. |$\{\ttm{rax},\ttm{rsp}\}$|
  5165. jmp conclusion
  5166. \end{lstlisting}
  5167. \fi}
  5168. {\if\edition\pythonEd\pythonColor
  5169. \begin{lstlisting}
  5170. movq $1, v
  5171. |$\{\ttm{v}\}$|
  5172. movq $42, w
  5173. |$\{\ttm{w}, \ttm{v}\}$|
  5174. movq v, x
  5175. |$\{\ttm{w}, \ttm{x}\}$|
  5176. addq $7, x
  5177. |$\{\ttm{w}, \ttm{x}\}$|
  5178. movq x, y
  5179. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5180. movq x, z
  5181. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5182. addq w, z
  5183. |$\{\ttm{y}, \ttm{z}\}$|
  5184. movq y, tmp_0
  5185. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5186. negq tmp_0
  5187. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5188. movq z, tmp_1
  5189. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5190. addq tmp_0, tmp_1
  5191. |$\{\ttm{tmp\_1}\}$|
  5192. movq tmp_1, %rdi
  5193. |$\{\ttm{rdi}\}$|
  5194. callq print_int
  5195. |$\{\}$|
  5196. \end{lstlisting}
  5197. \fi}
  5198. \end{tcolorbox}
  5199. \end{minipage}
  5200. \caption{The running example annotated with live-after sets.}
  5201. \label{fig:live-eg}
  5202. \end{figure}
  5203. \begin{exercise}\normalfont\normalsize
  5204. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5205. %
  5206. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5207. field of the \code{Block} structure.}
  5208. %
  5209. \python{Return a dictionary that maps each instruction to its
  5210. live-after set.}
  5211. %
  5212. \racket{We recommend creating an auxiliary function that takes a list
  5213. of instructions and an initial live-after set (typically empty) and
  5214. returns the list of live-after sets.}
  5215. %
  5216. We recommend creating auxiliary functions to (1) compute the set
  5217. of locations that appear in an \Arg{}, (2) compute the locations read
  5218. by an instruction (the $R$ function), and (3) the locations written by
  5219. an instruction (the $W$ function). The \code{callq} instruction should
  5220. include all the caller-saved registers in its write set $W$ because
  5221. the calling convention says that those registers may be written to
  5222. during the function call. Likewise, the \code{callq} instruction
  5223. should include the appropriate argument-passing registers in its
  5224. read set $R$, depending on the arity of the function being
  5225. called. (This is why the abstract syntax for \code{callq} includes the
  5226. arity.)
  5227. \end{exercise}
  5228. %\clearpage
  5229. \section{Build the Interference Graph}
  5230. \label{sec:build-interference}
  5231. {\if\edition\racketEd
  5232. \begin{figure}[tp]
  5233. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5234. \small
  5235. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5236. A \emph{graph} is a collection of vertices and edges where each
  5237. edge connects two vertices. A graph is \emph{directed} if each
  5238. edge points from a source to a target. Otherwise the graph is
  5239. \emph{undirected}.
  5240. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5241. \begin{description}
  5242. %% We currently don't use directed graphs. We instead use
  5243. %% directed multi-graphs. -Jeremy
  5244. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5245. directed graph from a list of edges. Each edge is a list
  5246. containing the source and target vertex.
  5247. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5248. undirected graph from a list of edges. Each edge is represented by
  5249. a list containing two vertices.
  5250. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5251. inserts a vertex into the graph.
  5252. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5253. inserts an edge between the two vertices.
  5254. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5255. returns a sequence of vertices adjacent to the vertex.
  5256. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5257. returns a sequence of all vertices in the graph.
  5258. \end{description}
  5259. \end{tcolorbox}
  5260. %\end{wrapfigure}
  5261. \caption{The Racket \code{graph} package.}
  5262. \label{fig:graph}
  5263. \end{figure}
  5264. \fi}
  5265. On the basis of the liveness analysis, we know where each location is
  5266. live. However, during register allocation, we need to answer
  5267. questions of the specific form: are locations $u$ and $v$ live at the
  5268. same time? (If so, they cannot be assigned to the same register.) To
  5269. make this question more efficient to answer, we create an explicit
  5270. data structure, an \emph{interference
  5271. graph}\index{subject}{interference graph}. An interference graph is
  5272. an undirected graph that has a node for every variable and register
  5273. and has an edge between two nodes if they are
  5274. live at the same time, that is, if they interfere with each other.
  5275. %
  5276. \racket{We recommend using the Racket \code{graph} package
  5277. (figure~\ref{fig:graph}) to represent the interference graph.}
  5278. %
  5279. \python{We provide implementations of directed and undirected graph
  5280. data structures in the file \code{graph.py} of the support code.}
  5281. A straightforward way to compute the interference graph is to look at
  5282. the set of live locations between each instruction and add an edge to
  5283. the graph for every pair of variables in the same set. This approach
  5284. is less than ideal for two reasons. First, it can be expensive because
  5285. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5286. locations. Second, in the special case in which two locations hold the
  5287. same value (because one was assigned to the other), they can be live
  5288. at the same time without interfering with each other.
  5289. A better way to compute the interference graph is to focus on
  5290. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5291. must not overwrite something in a live location. So for each
  5292. instruction, we create an edge between the locations being written to
  5293. and the live locations. (However, a location never interferes with
  5294. itself.) For the \key{callq} instruction, we consider all the
  5295. caller-saved registers to have been written to, so an edge is added
  5296. between every live variable and every caller-saved register. Also, for
  5297. \key{movq} there is the special case of two variables holding the same
  5298. value. If a live variable $v$ is the same as the source of the
  5299. \key{movq}, then there is no need to add an edge between $v$ and the
  5300. destination, because they both hold the same value.
  5301. %
  5302. Hence we have the following two rules:
  5303. \begin{enumerate}
  5304. \item If instruction $I_k$ is a move instruction of the form
  5305. \key{movq} $s$\key{,} $d$, then for every $v \in
  5306. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5307. $(d,v)$.
  5308. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5309. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5310. $(d,v)$.
  5311. \end{enumerate}
  5312. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5313. these rules to each instruction. We highlight a few of the
  5314. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5315. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5316. so \code{v} interferes with \code{rsp}.}
  5317. %
  5318. \python{The first instruction is \lstinline{movq $1, v}, and the
  5319. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5320. no interference because $\ttm{v}$ is the destination of the move.}
  5321. %
  5322. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5323. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5324. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5325. %
  5326. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5327. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5328. $\ttm{x}$ interferes with \ttm{w}.}
  5329. %
  5330. \racket{The next instruction is \lstinline{movq x, y}, and the
  5331. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5332. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5333. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5334. \ttm{x} and \ttm{y} hold the same value.}
  5335. %
  5336. \python{The next instruction is \lstinline{movq x, y}, and the
  5337. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5338. applies, so \ttm{y} interferes with \ttm{w} but not
  5339. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5340. \ttm{x} and \ttm{y} hold the same value.}
  5341. %
  5342. Figure~\ref{fig:interference-results} lists the interference results
  5343. for all the instructions, and the resulting interference graph is
  5344. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5345. the interference graph in figure~\ref{fig:interfere} because there
  5346. were no interference edges involving registers and we did not wish to
  5347. clutter the graph, but in general one needs to include all the
  5348. registers in the interference graph.
  5349. \begin{figure}[tbp]
  5350. \begin{tcolorbox}[colback=white]
  5351. \begin{quote}
  5352. {\if\edition\racketEd
  5353. \begin{tabular}{ll}
  5354. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5355. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5356. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5357. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5358. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5359. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5360. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5361. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5362. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5363. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5364. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5365. \lstinline!jmp conclusion!& no interference.
  5366. \end{tabular}
  5367. \fi}
  5368. {\if\edition\pythonEd\pythonColor
  5369. \begin{tabular}{ll}
  5370. \lstinline!movq $1, v!& no interference\\
  5371. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5372. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5373. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5374. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5375. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5376. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5377. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5378. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5379. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5380. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5381. \lstinline!movq tmp_1, %rdi! & no interference \\
  5382. \lstinline!callq print_int!& no interference.
  5383. \end{tabular}
  5384. \fi}
  5385. \end{quote}
  5386. \end{tcolorbox}
  5387. \caption{Interference results for the running example.}
  5388. \label{fig:interference-results}
  5389. \end{figure}
  5390. \begin{figure}[tbp]
  5391. \begin{tcolorbox}[colback=white]
  5392. \large
  5393. {\if\edition\racketEd
  5394. \[
  5395. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5396. \node (rax) at (0,0) {$\ttm{rax}$};
  5397. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5398. \node (t1) at (0,2) {$\ttm{t}$};
  5399. \node (z) at (3,2) {$\ttm{z}$};
  5400. \node (x) at (6,2) {$\ttm{x}$};
  5401. \node (y) at (3,0) {$\ttm{y}$};
  5402. \node (w) at (6,0) {$\ttm{w}$};
  5403. \node (v) at (9,0) {$\ttm{v}$};
  5404. \draw (t1) to (rax);
  5405. \draw (t1) to (z);
  5406. \draw (z) to (y);
  5407. \draw (z) to (w);
  5408. \draw (x) to (w);
  5409. \draw (y) to (w);
  5410. \draw (v) to (w);
  5411. \draw (v) to (rsp);
  5412. \draw (w) to (rsp);
  5413. \draw (x) to (rsp);
  5414. \draw (y) to (rsp);
  5415. \path[-.,bend left=15] (z) edge node {} (rsp);
  5416. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5417. \draw (rax) to (rsp);
  5418. \end{tikzpicture}
  5419. \]
  5420. \fi}
  5421. {\if\edition\pythonEd\pythonColor
  5422. \[
  5423. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5424. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5425. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5426. \node (z) at (3,2) {$\ttm{z}$};
  5427. \node (x) at (6,2) {$\ttm{x}$};
  5428. \node (y) at (3,0) {$\ttm{y}$};
  5429. \node (w) at (6,0) {$\ttm{w}$};
  5430. \node (v) at (9,0) {$\ttm{v}$};
  5431. \draw (t0) to (t1);
  5432. \draw (t0) to (z);
  5433. \draw (z) to (y);
  5434. \draw (z) to (w);
  5435. \draw (x) to (w);
  5436. \draw (y) to (w);
  5437. \draw (v) to (w);
  5438. \end{tikzpicture}
  5439. \]
  5440. \fi}
  5441. \end{tcolorbox}
  5442. \caption{The interference graph of the example program.}
  5443. \label{fig:interfere}
  5444. \end{figure}
  5445. \begin{exercise}\normalfont\normalsize
  5446. \racket{Implement the compiler pass named \code{build\_interference} according
  5447. to the algorithm suggested here. We recommend using the Racket
  5448. \code{graph} package to create and inspect the interference graph.
  5449. The output graph of this pass should be stored in the $\itm{info}$ field of
  5450. the program, under the key \code{conflicts}.}
  5451. %
  5452. \python{Implement a function named \code{build\_interference}
  5453. according to the algorithm suggested above that
  5454. returns the interference graph.}
  5455. \end{exercise}
  5456. \section{Graph Coloring via Sudoku}
  5457. \label{sec:graph-coloring}
  5458. \index{subject}{graph coloring}
  5459. \index{subject}{sudoku}
  5460. \index{subject}{color}
  5461. We come to the main event discussed in this chapter, mapping variables
  5462. to registers and stack locations. Variables that interfere with each
  5463. other must be mapped to different locations. In terms of the
  5464. interference graph, this means that adjacent vertices must be mapped
  5465. to different locations. If we think of locations as colors, the
  5466. register allocation problem becomes the graph coloring
  5467. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5468. The reader may be more familiar with the graph coloring problem than he
  5469. or she realizes; the popular game of sudoku is an instance of the
  5470. graph coloring problem. The following describes how to build a graph
  5471. out of an initial sudoku board.
  5472. \begin{itemize}
  5473. \item There is one vertex in the graph for each sudoku square.
  5474. \item There is an edge between two vertices if the corresponding squares
  5475. are in the same row, in the same column, or in the same $3\times 3$ region.
  5476. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5477. \item On the basis of the initial assignment of numbers to squares on the
  5478. sudoku board, assign the corresponding colors to the corresponding
  5479. vertices in the graph.
  5480. \end{itemize}
  5481. If you can color the remaining vertices in the graph with the nine
  5482. colors, then you have also solved the corresponding game of sudoku.
  5483. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5484. the corresponding graph with colored vertices. Here we use a
  5485. monochrome representation of colors, mapping the sudoku number 1 to
  5486. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5487. of the vertices (the colored ones) because showing edges for all the
  5488. vertices would make the graph unreadable.
  5489. \begin{figure}[tbp]
  5490. \begin{tcolorbox}[colback=white]
  5491. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5492. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5493. \end{tcolorbox}
  5494. \caption{A sudoku game board and the corresponding colored graph.}
  5495. \label{fig:sudoku-graph}
  5496. \end{figure}
  5497. Some techniques for playing sudoku correspond to heuristics used in
  5498. graph coloring algorithms. For example, one of the basic techniques
  5499. for sudoku is called Pencil Marks. The idea is to use a process of
  5500. elimination to determine what numbers are no longer available for a
  5501. square and to write those numbers in the square (writing very
  5502. small). For example, if the number $1$ is assigned to a square, then
  5503. write the pencil mark $1$ in all the squares in the same row, column,
  5504. and region to indicate that $1$ is no longer an option for those other
  5505. squares.
  5506. %
  5507. The Pencil Marks technique corresponds to the notion of
  5508. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5509. saturation of a vertex, in sudoku terms, is the set of numbers that
  5510. are no longer available. In graph terminology, we have the following
  5511. definition:
  5512. \begin{equation*}
  5513. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5514. \text{ and } \mathrm{color}(v) = c \}
  5515. \end{equation*}
  5516. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5517. edge with $u$.
  5518. The Pencil Marks technique leads to a simple strategy for filling in
  5519. numbers: if there is a square with only one possible number left, then
  5520. choose that number! But what if there are no squares with only one
  5521. possibility left? One brute-force approach is to try them all: choose
  5522. the first one, and if that ultimately leads to a solution, great. If
  5523. not, backtrack and choose the next possibility. One good thing about
  5524. Pencil Marks is that it reduces the degree of branching in the search
  5525. tree. Nevertheless, backtracking can be terribly time consuming. One
  5526. way to reduce the amount of backtracking is to use the
  5527. most-constrained-first heuristic (aka minimum remaining
  5528. values)~\citep{Russell2003}. That is, in choosing a square, always
  5529. choose one with the fewest possibilities left (the vertex with the
  5530. highest saturation). The idea is that choosing highly constrained
  5531. squares earlier rather than later is better, because later on there may
  5532. not be any possibilities left in the highly saturated squares.
  5533. However, register allocation is easier than sudoku, because the
  5534. register allocator can fall back to assigning variables to stack
  5535. locations when the registers run out. Thus, it makes sense to replace
  5536. backtracking with greedy search: make the best choice at the time and
  5537. keep going. We still wish to minimize the number of colors needed, so
  5538. we use the most-constrained-first heuristic in the greedy search.
  5539. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5540. algorithm for register allocation based on saturation and the
  5541. most-constrained-first heuristic. It is roughly equivalent to the
  5542. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5543. sudoku, the algorithm represents colors with integers. The integers
  5544. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5545. register allocation. In particular, we recommend the following
  5546. correspondence, with $k=11$.
  5547. \begin{lstlisting}
  5548. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5549. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5550. \end{lstlisting}
  5551. The integers $k$ and larger correspond to stack locations. The
  5552. registers that are not used for register allocation, such as
  5553. \code{rax}, are assigned to negative integers. In particular, we
  5554. recommend the following correspondence.
  5555. \begin{lstlisting}
  5556. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5557. \end{lstlisting}
  5558. %% One might wonder why we include registers at all in the liveness
  5559. %% analysis and interference graph. For example, we never allocate a
  5560. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5561. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5562. %% to use register for passing arguments to functions, it will be
  5563. %% necessary for those registers to appear in the interference graph
  5564. %% because those registers will also be assigned to variables, and we
  5565. %% don't want those two uses to encroach on each other. Regarding
  5566. %% registers such as \code{rax} and \code{rsp} that are not used for
  5567. %% variables, we could omit them from the interference graph but that
  5568. %% would require adding special cases to our algorithm, which would
  5569. %% complicate the logic for little gain.
  5570. \begin{figure}[btp]
  5571. \begin{tcolorbox}[colback=white]
  5572. \centering
  5573. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5574. Algorithm: DSATUR
  5575. Input: A graph |$G$|
  5576. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5577. |$W \gets \mathrm{vertices}(G)$|
  5578. while |$W \neq \emptyset$| do
  5579. pick a vertex |$u$| from |$W$| with the highest saturation,
  5580. breaking ties randomly
  5581. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5582. |$\mathrm{color}[u] \gets c$|
  5583. |$W \gets W - \{u\}$|
  5584. \end{lstlisting}
  5585. \end{tcolorbox}
  5586. \caption{The saturation-based greedy graph coloring algorithm.}
  5587. \label{fig:satur-algo}
  5588. \end{figure}
  5589. {\if\edition\racketEd
  5590. With the DSATUR algorithm in hand, let us return to the running
  5591. example and consider how to color the interference graph shown in
  5592. figure~\ref{fig:interfere}.
  5593. %
  5594. We start by assigning each register node to its own color. For
  5595. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5596. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5597. (To reduce clutter in the interference graph, we elide nodes
  5598. that do not have interference edges, such as \code{rcx}.)
  5599. The variables are not yet colored, so they are annotated with a dash. We
  5600. then update the saturation for vertices that are adjacent to a
  5601. register, obtaining the following annotated graph. For example, the
  5602. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5603. \code{rax} and \code{rsp}.
  5604. \[
  5605. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5606. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5607. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5608. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5609. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5610. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5611. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5612. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5613. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5614. \draw (t1) to (rax);
  5615. \draw (t1) to (z);
  5616. \draw (z) to (y);
  5617. \draw (z) to (w);
  5618. \draw (x) to (w);
  5619. \draw (y) to (w);
  5620. \draw (v) to (w);
  5621. \draw (v) to (rsp);
  5622. \draw (w) to (rsp);
  5623. \draw (x) to (rsp);
  5624. \draw (y) to (rsp);
  5625. \path[-.,bend left=15] (z) edge node {} (rsp);
  5626. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5627. \draw (rax) to (rsp);
  5628. \end{tikzpicture}
  5629. \]
  5630. The algorithm says to select a maximally saturated vertex. So, we pick
  5631. $\ttm{t}$ and color it with the first available integer, which is
  5632. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5633. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5634. \[
  5635. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5636. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5637. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5638. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5639. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5640. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5641. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5642. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5643. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5644. \draw (t1) to (rax);
  5645. \draw (t1) to (z);
  5646. \draw (z) to (y);
  5647. \draw (z) to (w);
  5648. \draw (x) to (w);
  5649. \draw (y) to (w);
  5650. \draw (v) to (w);
  5651. \draw (v) to (rsp);
  5652. \draw (w) to (rsp);
  5653. \draw (x) to (rsp);
  5654. \draw (y) to (rsp);
  5655. \path[-.,bend left=15] (z) edge node {} (rsp);
  5656. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5657. \draw (rax) to (rsp);
  5658. \end{tikzpicture}
  5659. \]
  5660. We repeat the process, selecting a maximally saturated vertex,
  5661. choosing \code{z}, and coloring it with the first available number, which
  5662. is $1$. We add $1$ to the saturation for the neighboring vertices
  5663. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5664. \[
  5665. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5666. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5667. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5668. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5669. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5670. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5671. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5672. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5673. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5674. \draw (t1) to (rax);
  5675. \draw (t1) to (z);
  5676. \draw (z) to (y);
  5677. \draw (z) to (w);
  5678. \draw (x) to (w);
  5679. \draw (y) to (w);
  5680. \draw (v) to (w);
  5681. \draw (v) to (rsp);
  5682. \draw (w) to (rsp);
  5683. \draw (x) to (rsp);
  5684. \draw (y) to (rsp);
  5685. \path[-.,bend left=15] (z) edge node {} (rsp);
  5686. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5687. \draw (rax) to (rsp);
  5688. \end{tikzpicture}
  5689. \]
  5690. The most saturated vertices are now \code{w} and \code{y}. We color
  5691. \code{w} with the first available color, which is $0$.
  5692. \[
  5693. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5694. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5695. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5696. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5697. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5698. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5699. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5700. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5701. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5702. \draw (t1) to (rax);
  5703. \draw (t1) to (z);
  5704. \draw (z) to (y);
  5705. \draw (z) to (w);
  5706. \draw (x) to (w);
  5707. \draw (y) to (w);
  5708. \draw (v) to (w);
  5709. \draw (v) to (rsp);
  5710. \draw (w) to (rsp);
  5711. \draw (x) to (rsp);
  5712. \draw (y) to (rsp);
  5713. \path[-.,bend left=15] (z) edge node {} (rsp);
  5714. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5715. \draw (rax) to (rsp);
  5716. \end{tikzpicture}
  5717. \]
  5718. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5719. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5720. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5721. and \code{z}, whose colors are $0$ and $1$ respectively.
  5722. \[
  5723. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5724. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5725. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5726. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5727. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5728. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5729. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5730. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5731. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5732. \draw (t1) to (rax);
  5733. \draw (t1) to (z);
  5734. \draw (z) to (y);
  5735. \draw (z) to (w);
  5736. \draw (x) to (w);
  5737. \draw (y) to (w);
  5738. \draw (v) to (w);
  5739. \draw (v) to (rsp);
  5740. \draw (w) to (rsp);
  5741. \draw (x) to (rsp);
  5742. \draw (y) to (rsp);
  5743. \path[-.,bend left=15] (z) edge node {} (rsp);
  5744. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5745. \draw (rax) to (rsp);
  5746. \end{tikzpicture}
  5747. \]
  5748. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5749. \[
  5750. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5751. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5752. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5753. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5754. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5755. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5756. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5757. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5758. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5759. \draw (t1) to (rax);
  5760. \draw (t1) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \draw (v) to (rsp);
  5767. \draw (w) to (rsp);
  5768. \draw (x) to (rsp);
  5769. \draw (y) to (rsp);
  5770. \path[-.,bend left=15] (z) edge node {} (rsp);
  5771. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5772. \draw (rax) to (rsp);
  5773. \end{tikzpicture}
  5774. \]
  5775. In the last step of the algorithm, we color \code{x} with $1$.
  5776. \[
  5777. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5778. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5779. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5780. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5781. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5782. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5783. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5784. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5785. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5786. \draw (t1) to (rax);
  5787. \draw (t1) to (z);
  5788. \draw (z) to (y);
  5789. \draw (z) to (w);
  5790. \draw (x) to (w);
  5791. \draw (y) to (w);
  5792. \draw (v) to (w);
  5793. \draw (v) to (rsp);
  5794. \draw (w) to (rsp);
  5795. \draw (x) to (rsp);
  5796. \draw (y) to (rsp);
  5797. \path[-.,bend left=15] (z) edge node {} (rsp);
  5798. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5799. \draw (rax) to (rsp);
  5800. \end{tikzpicture}
  5801. \]
  5802. So, we obtain the following coloring:
  5803. \[
  5804. \{
  5805. \ttm{rax} \mapsto -1,
  5806. \ttm{rsp} \mapsto -2,
  5807. \ttm{t} \mapsto 0,
  5808. \ttm{z} \mapsto 1,
  5809. \ttm{x} \mapsto 1,
  5810. \ttm{y} \mapsto 2,
  5811. \ttm{w} \mapsto 0,
  5812. \ttm{v} \mapsto 1
  5813. \}
  5814. \]
  5815. \fi}
  5816. %
  5817. {\if\edition\pythonEd\pythonColor
  5818. %
  5819. With the DSATUR algorithm in hand, let us return to the running
  5820. example and consider how to color the interference graph shown in
  5821. figure~\ref{fig:interfere}, again mapping 1 to blank, 2 to white, and
  5822. 3 to gray. We annotate each variable node with a dash to indicate that
  5823. it has not yet been assigned a color. Each register node (not shown)
  5824. should be assigned the number that the register corresponds to, for
  5825. example, color \code{rcx} with the number \code{0} and \code{rdx} with
  5826. \code{1}. The saturation sets are also shown for each node; all of
  5827. them start as the empty set. We do not show the register nodes in the
  5828. following graph because there were no interference edges involving
  5829. registers in this program; however, in general there can be inference
  5830. edges that involve registers.
  5831. %
  5832. \[
  5833. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5834. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5835. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5836. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5837. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5838. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5839. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5840. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5841. \draw (t0) to (t1);
  5842. \draw (t0) to (z);
  5843. \draw (z) to (y);
  5844. \draw (z) to (w);
  5845. \draw (x) to (w);
  5846. \draw (y) to (w);
  5847. \draw (v) to (w);
  5848. \end{tikzpicture}
  5849. \]
  5850. The algorithm says to select a maximally saturated vertex, but they
  5851. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5852. and then we color it with the first available integer, which is $0$. We mark
  5853. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5854. they interfere with $\ttm{tmp\_0}$.
  5855. \[
  5856. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5857. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5858. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5859. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5860. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5861. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5862. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5863. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5864. \draw (t0) to (t1);
  5865. \draw (t0) to (z);
  5866. \draw (z) to (y);
  5867. \draw (z) to (w);
  5868. \draw (x) to (w);
  5869. \draw (y) to (w);
  5870. \draw (v) to (w);
  5871. \end{tikzpicture}
  5872. \]
  5873. We repeat the process. The most saturated vertices are \code{z} and
  5874. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5875. available number, which is $1$. We add $1$ to the saturation for the
  5876. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5877. \[
  5878. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5879. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5880. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5881. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5882. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5883. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5884. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5885. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5886. \draw (t0) to (t1);
  5887. \draw (t0) to (z);
  5888. \draw (z) to (y);
  5889. \draw (z) to (w);
  5890. \draw (x) to (w);
  5891. \draw (y) to (w);
  5892. \draw (v) to (w);
  5893. \end{tikzpicture}
  5894. \]
  5895. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5896. \code{y}. We color \code{w} with the first available color, which
  5897. is $0$.
  5898. \[
  5899. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5900. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5901. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5902. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5903. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5904. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5905. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5906. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5907. \draw (t0) to (t1);
  5908. \draw (t0) to (z);
  5909. \draw (z) to (y);
  5910. \draw (z) to (w);
  5911. \draw (x) to (w);
  5912. \draw (y) to (w);
  5913. \draw (v) to (w);
  5914. \end{tikzpicture}
  5915. \]
  5916. Now \code{y} is the most saturated, so we color it with $2$.
  5917. \[
  5918. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5919. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5920. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5921. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5922. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5923. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5924. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5925. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5926. \draw (t0) to (t1);
  5927. \draw (t0) to (z);
  5928. \draw (z) to (y);
  5929. \draw (z) to (w);
  5930. \draw (x) to (w);
  5931. \draw (y) to (w);
  5932. \draw (v) to (w);
  5933. \end{tikzpicture}
  5934. \]
  5935. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5936. We choose to color \code{v} with $1$.
  5937. \[
  5938. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5939. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5940. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5941. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5942. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5943. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5944. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5945. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5946. \draw (t0) to (t1);
  5947. \draw (t0) to (z);
  5948. \draw (z) to (y);
  5949. \draw (z) to (w);
  5950. \draw (x) to (w);
  5951. \draw (y) to (w);
  5952. \draw (v) to (w);
  5953. \end{tikzpicture}
  5954. \]
  5955. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5956. \[
  5957. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5958. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5959. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5960. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5961. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5962. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5963. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5964. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5965. \draw (t0) to (t1);
  5966. \draw (t0) to (z);
  5967. \draw (z) to (y);
  5968. \draw (z) to (w);
  5969. \draw (x) to (w);
  5970. \draw (y) to (w);
  5971. \draw (v) to (w);
  5972. \end{tikzpicture}
  5973. \]
  5974. So, we obtain the following coloring:
  5975. \[
  5976. \{ \ttm{tmp\_0} \mapsto 0,
  5977. \ttm{tmp\_1} \mapsto 1,
  5978. \ttm{z} \mapsto 1,
  5979. \ttm{x} \mapsto 1,
  5980. \ttm{y} \mapsto 2,
  5981. \ttm{w} \mapsto 0,
  5982. \ttm{v} \mapsto 1 \}
  5983. \]
  5984. \fi}
  5985. We recommend creating an auxiliary function named \code{color\_graph}
  5986. that takes an interference graph and a list of all the variables in
  5987. the program. This function should return a mapping of variables to
  5988. their colors (represented as natural numbers). By creating this helper
  5989. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5990. when we add support for functions.
  5991. To prioritize the processing of highly saturated nodes inside the
  5992. \code{color\_graph} function, we recommend using the priority queue
  5993. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5994. addition, you will need to maintain a mapping from variables to their
  5995. handles in the priority queue so that you can notify the priority
  5996. queue when their saturation changes.}
  5997. {\if\edition\racketEd
  5998. \begin{figure}[tp]
  5999. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6000. \small
  6001. \begin{tcolorbox}[title=Priority Queue]
  6002. A \emph{priority queue}\index{subject}{priority queue}
  6003. is a collection of items in which the
  6004. removal of items is governed by priority. In a \emph{min} queue,
  6005. lower priority items are removed first. An implementation is in
  6006. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6007. \begin{description}
  6008. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6009. priority queue that uses the $\itm{cmp}$ predicate to determine
  6010. whether its first argument has lower or equal priority to its
  6011. second argument.
  6012. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6013. items in the queue.
  6014. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6015. the item into the queue and returns a handle for the item in the
  6016. queue.
  6017. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6018. the lowest priority.
  6019. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6020. notifies the queue that the priority has decreased for the item
  6021. associated with the given handle.
  6022. \end{description}
  6023. \end{tcolorbox}
  6024. %\end{wrapfigure}
  6025. \caption{The priority queue data structure.}
  6026. \label{fig:priority-queue}
  6027. \end{figure}
  6028. \fi}
  6029. With the coloring complete, we finalize the assignment of variables to
  6030. registers and stack locations. We map the first $k$ colors to the $k$
  6031. registers and the rest of the colors to stack locations. Suppose for
  6032. the moment that we have just one register to use for register
  6033. allocation, \key{rcx}. Then we have the following map from colors to
  6034. locations.
  6035. \[
  6036. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6037. \]
  6038. Composing this mapping with the coloring, we arrive at the following
  6039. assignment of variables to locations.
  6040. {\if\edition\racketEd
  6041. \begin{gather*}
  6042. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6043. \ttm{w} \mapsto \key{\%rcx}, \,
  6044. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6045. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6046. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6047. \ttm{t} \mapsto \key{\%rcx} \}
  6048. \end{gather*}
  6049. \fi}
  6050. {\if\edition\pythonEd\pythonColor
  6051. \begin{gather*}
  6052. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6053. \ttm{w} \mapsto \key{\%rcx}, \,
  6054. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6055. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6056. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6057. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6058. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6059. \end{gather*}
  6060. \fi}
  6061. Adapt the code from the \code{assign\_homes} pass
  6062. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6063. assigned location. Applying this assignment to our running
  6064. example shown next, on the left, yields the program on the right.
  6065. % why frame size of 32? -JGS
  6066. \begin{center}
  6067. {\if\edition\racketEd
  6068. \begin{minipage}{0.35\textwidth}
  6069. \begin{lstlisting}
  6070. movq $1, v
  6071. movq $42, w
  6072. movq v, x
  6073. addq $7, x
  6074. movq x, y
  6075. movq x, z
  6076. addq w, z
  6077. movq y, t
  6078. negq t
  6079. movq z, %rax
  6080. addq t, %rax
  6081. jmp conclusion
  6082. \end{lstlisting}
  6083. \end{minipage}
  6084. $\Rightarrow\qquad$
  6085. \begin{minipage}{0.45\textwidth}
  6086. \begin{lstlisting}
  6087. movq $1, -8(%rbp)
  6088. movq $42, %rcx
  6089. movq -8(%rbp), -8(%rbp)
  6090. addq $7, -8(%rbp)
  6091. movq -8(%rbp), -16(%rbp)
  6092. movq -8(%rbp), -8(%rbp)
  6093. addq %rcx, -8(%rbp)
  6094. movq -16(%rbp), %rcx
  6095. negq %rcx
  6096. movq -8(%rbp), %rax
  6097. addq %rcx, %rax
  6098. jmp conclusion
  6099. \end{lstlisting}
  6100. \end{minipage}
  6101. \fi}
  6102. {\if\edition\pythonEd\pythonColor
  6103. \begin{minipage}{0.35\textwidth}
  6104. \begin{lstlisting}
  6105. movq $1, v
  6106. movq $42, w
  6107. movq v, x
  6108. addq $7, x
  6109. movq x, y
  6110. movq x, z
  6111. addq w, z
  6112. movq y, tmp_0
  6113. negq tmp_0
  6114. movq z, tmp_1
  6115. addq tmp_0, tmp_1
  6116. movq tmp_1, %rdi
  6117. callq print_int
  6118. \end{lstlisting}
  6119. \end{minipage}
  6120. $\Rightarrow\qquad$
  6121. \begin{minipage}{0.45\textwidth}
  6122. \begin{lstlisting}
  6123. movq $1, -8(%rbp)
  6124. movq $42, %rcx
  6125. movq -8(%rbp), -8(%rbp)
  6126. addq $7, -8(%rbp)
  6127. movq -8(%rbp), -16(%rbp)
  6128. movq -8(%rbp), -8(%rbp)
  6129. addq %rcx, -8(%rbp)
  6130. movq -16(%rbp), %rcx
  6131. negq %rcx
  6132. movq -8(%rbp), -8(%rbp)
  6133. addq %rcx, -8(%rbp)
  6134. movq -8(%rbp), %rdi
  6135. callq print_int
  6136. \end{lstlisting}
  6137. \end{minipage}
  6138. \fi}
  6139. \end{center}
  6140. \begin{exercise}\normalfont\normalsize
  6141. Implement the \code{allocate\_registers} pass.
  6142. Create five programs that exercise all aspects of the register
  6143. allocation algorithm, including spilling variables to the stack.
  6144. %
  6145. {\if\edition\racketEd
  6146. Replace \code{assign\_homes} in the list of \code{passes} in the
  6147. \code{run-tests.rkt} script with the three new passes:
  6148. \code{uncover\_live}, \code{build\_interference}, and
  6149. \code{allocate\_registers}.
  6150. Temporarily remove the call to \code{compiler-tests}.
  6151. Run the script to test the register allocator.
  6152. \fi}
  6153. %
  6154. {\if\edition\pythonEd\pythonColor
  6155. Run the \code{run-tests.py} script to check whether the
  6156. output programs produce the same result as the input programs.
  6157. \fi}
  6158. \end{exercise}
  6159. \section{Patch Instructions}
  6160. \label{sec:patch-instructions}
  6161. The remaining step in the compilation to x86 is to ensure that the
  6162. instructions have at most one argument that is a memory access.
  6163. %
  6164. In the running example, the instruction \code{movq -8(\%rbp),
  6165. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6166. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6167. then move \code{rax} into \code{-16(\%rbp)}.
  6168. %
  6169. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6170. problematic, but they can simply be deleted. In general, we recommend
  6171. deleting all the trivial moves whose source and destination are the
  6172. same location.
  6173. %
  6174. The following is the output of \code{patch\_instructions} on the
  6175. running example.
  6176. \begin{center}
  6177. {\if\edition\racketEd
  6178. \begin{minipage}{0.35\textwidth}
  6179. \begin{lstlisting}
  6180. movq $1, -8(%rbp)
  6181. movq $42, %rcx
  6182. movq -8(%rbp), -8(%rbp)
  6183. addq $7, -8(%rbp)
  6184. movq -8(%rbp), -16(%rbp)
  6185. movq -8(%rbp), -8(%rbp)
  6186. addq %rcx, -8(%rbp)
  6187. movq -16(%rbp), %rcx
  6188. negq %rcx
  6189. movq -8(%rbp), %rax
  6190. addq %rcx, %rax
  6191. jmp conclusion
  6192. \end{lstlisting}
  6193. \end{minipage}
  6194. $\Rightarrow\qquad$
  6195. \begin{minipage}{0.45\textwidth}
  6196. \begin{lstlisting}
  6197. movq $1, -8(%rbp)
  6198. movq $42, %rcx
  6199. addq $7, -8(%rbp)
  6200. movq -8(%rbp), %rax
  6201. movq %rax, -16(%rbp)
  6202. addq %rcx, -8(%rbp)
  6203. movq -16(%rbp), %rcx
  6204. negq %rcx
  6205. movq -8(%rbp), %rax
  6206. addq %rcx, %rax
  6207. jmp conclusion
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. \fi}
  6211. {\if\edition\pythonEd\pythonColor
  6212. \begin{minipage}{0.35\textwidth}
  6213. \begin{lstlisting}
  6214. movq $1, -8(%rbp)
  6215. movq $42, %rcx
  6216. movq -8(%rbp), -8(%rbp)
  6217. addq $7, -8(%rbp)
  6218. movq -8(%rbp), -16(%rbp)
  6219. movq -8(%rbp), -8(%rbp)
  6220. addq %rcx, -8(%rbp)
  6221. movq -16(%rbp), %rcx
  6222. negq %rcx
  6223. movq -8(%rbp), -8(%rbp)
  6224. addq %rcx, -8(%rbp)
  6225. movq -8(%rbp), %rdi
  6226. callq print_int
  6227. \end{lstlisting}
  6228. \end{minipage}
  6229. $\Rightarrow\qquad$
  6230. \begin{minipage}{0.45\textwidth}
  6231. \begin{lstlisting}
  6232. movq $1, -8(%rbp)
  6233. movq $42, %rcx
  6234. addq $7, -8(%rbp)
  6235. movq -8(%rbp), %rax
  6236. movq %rax, -16(%rbp)
  6237. addq %rcx, -8(%rbp)
  6238. movq -16(%rbp), %rcx
  6239. negq %rcx
  6240. addq %rcx, -8(%rbp)
  6241. movq -8(%rbp), %rdi
  6242. callq print_int
  6243. \end{lstlisting}
  6244. \end{minipage}
  6245. \fi}
  6246. \end{center}
  6247. \begin{exercise}\normalfont\normalsize
  6248. %
  6249. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6250. %
  6251. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6252. %in the \code{run-tests.rkt} script.
  6253. %
  6254. Run the script to test the \code{patch\_instructions} pass.
  6255. \end{exercise}
  6256. \section{Prelude and Conclusion}
  6257. \label{sec:print-x86-reg-alloc}
  6258. \index{subject}{calling conventions}
  6259. \index{subject}{prelude}\index{subject}{conclusion}
  6260. Recall that this pass generates the prelude and conclusion
  6261. instructions to satisfy the x86 calling conventions
  6262. (section~\ref{sec:calling-conventions}). With the addition of the
  6263. register allocator, the callee-saved registers used by the register
  6264. allocator must be saved in the prelude and restored in the conclusion.
  6265. In the \code{allocate\_registers} pass,
  6266. %
  6267. \racket{add an entry to the \itm{info}
  6268. of \code{X86Program} named \code{used\_callee}}
  6269. %
  6270. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6271. %
  6272. that stores the set of callee-saved registers that were assigned to
  6273. variables. The \code{prelude\_and\_conclusion} pass can then access
  6274. this information to decide which callee-saved registers need to be
  6275. saved and restored.
  6276. %
  6277. When calculating the amount to adjust the \code{rsp} in the prelude,
  6278. make sure to take into account the space used for saving the
  6279. callee-saved registers. Also, remember that the frame needs to be a
  6280. multiple of 16 bytes! We recommend using the following equation for
  6281. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6282. of stack locations used by spilled variables\footnote{Sometimes two or
  6283. more spilled variables are assigned to the same stack location, so
  6284. $S$ can be less than the number of spilled variables.} and $C$ be
  6285. the number of callee-saved registers that were
  6286. allocated\index{subject}{allocate} to
  6287. variables. The $\itm{align}$ function rounds a number up to the
  6288. nearest 16 bytes.
  6289. \[
  6290. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6291. \]
  6292. The reason we subtract $8\itm{C}$ in this equation is that the
  6293. prelude uses \code{pushq} to save each of the callee-saved registers,
  6294. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6295. \racket{An overview of all the passes involved in register
  6296. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6297. {\if\edition\racketEd
  6298. \begin{figure}[tbp]
  6299. \begin{tcolorbox}[colback=white]
  6300. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6301. \node (Lvar) at (0,2) {\large \LangVar{}};
  6302. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6303. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6304. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6305. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6306. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6307. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6308. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6309. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6310. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6311. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6312. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6313. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6314. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6315. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6316. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6317. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6318. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6319. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6320. \end{tikzpicture}
  6321. \end{tcolorbox}
  6322. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6323. \label{fig:reg-alloc-passes}
  6324. \end{figure}
  6325. \fi}
  6326. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6327. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6328. use of registers and the stack, we limit the register allocator for
  6329. this example to use just two registers: \code{rcx} (color $0$) and
  6330. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6331. \code{main} function, we push \code{rbx} onto the stack because it is
  6332. a callee-saved register and it was assigned to a variable by the
  6333. register allocator. We subtract \code{8} from the \code{rsp} at the
  6334. end of the prelude to reserve space for the one spilled variable.
  6335. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6336. Moving on to the program proper, we see how the registers were
  6337. allocated.
  6338. %
  6339. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6340. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6341. %
  6342. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6343. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6344. were assigned to \code{rbx}.}
  6345. %
  6346. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6347. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6348. callee-save register \code{rbx} onto the stack. The spilled variables
  6349. must be placed lower on the stack than the saved callee-save
  6350. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6351. \code{-16(\%rbp)}.
  6352. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6353. done in the prelude. We move the stack pointer up by \code{8} bytes
  6354. (the room for spilled variables), then pop the old values of
  6355. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6356. \code{retq} to return control to the operating system.
  6357. \begin{figure}[tbp]
  6358. \begin{minipage}{0.55\textwidth}
  6359. \begin{tcolorbox}[colback=white]
  6360. % var_test_28.rkt
  6361. % (use-minimal-set-of-registers! #t)
  6362. % 0 -> rcx
  6363. % 1 -> rbx
  6364. %
  6365. % t 0 rcx
  6366. % z 1 rbx
  6367. % w 0 rcx
  6368. % y 2 rbp -16
  6369. % v 1 rbx
  6370. % x 1 rbx
  6371. {\if\edition\racketEd
  6372. \begin{lstlisting}
  6373. start:
  6374. movq $1, %rbx
  6375. movq $42, %rcx
  6376. addq $7, %rbx
  6377. movq %rbx, -16(%rbp)
  6378. addq %rcx, %rbx
  6379. movq -16(%rbp), %rcx
  6380. negq %rcx
  6381. movq %rbx, %rax
  6382. addq %rcx, %rax
  6383. jmp conclusion
  6384. .globl main
  6385. main:
  6386. pushq %rbp
  6387. movq %rsp, %rbp
  6388. pushq %rbx
  6389. subq $8, %rsp
  6390. jmp start
  6391. conclusion:
  6392. addq $8, %rsp
  6393. popq %rbx
  6394. popq %rbp
  6395. retq
  6396. \end{lstlisting}
  6397. \fi}
  6398. {\if\edition\pythonEd\pythonColor
  6399. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6400. \begin{lstlisting}
  6401. .globl main
  6402. main:
  6403. pushq %rbp
  6404. movq %rsp, %rbp
  6405. pushq %rbx
  6406. subq $8, %rsp
  6407. movq $1, %rcx
  6408. movq $42, %rbx
  6409. addq $7, %rcx
  6410. movq %rcx, -16(%rbp)
  6411. addq %rbx, -16(%rbp)
  6412. negq %rcx
  6413. movq -16(%rbp), %rbx
  6414. addq %rcx, %rbx
  6415. movq %rbx, %rdi
  6416. callq print_int
  6417. addq $8, %rsp
  6418. popq %rbx
  6419. popq %rbp
  6420. retq
  6421. \end{lstlisting}
  6422. \fi}
  6423. \end{tcolorbox}
  6424. \end{minipage}
  6425. \caption{The x86 output from the running example
  6426. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6427. and \code{rcx}.}
  6428. \label{fig:running-example-x86}
  6429. \end{figure}
  6430. \begin{exercise}\normalfont\normalsize
  6431. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6432. %
  6433. \racket{
  6434. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6435. list of passes and the call to \code{compiler-tests}.}
  6436. %
  6437. Run the script to test the complete compiler for \LangVar{} that
  6438. performs register allocation.
  6439. \end{exercise}
  6440. \section{Challenge: Move Biasing}
  6441. \label{sec:move-biasing}
  6442. \index{subject}{move biasing}
  6443. This section describes an enhancement to the register allocator,
  6444. called move biasing, for students who are looking for an extra
  6445. challenge.
  6446. {\if\edition\racketEd
  6447. To motivate the need for move biasing we return to the running example,
  6448. but this time we use all the general purpose registers. So, we have
  6449. the following mapping of color numbers to registers.
  6450. \[
  6451. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6452. \]
  6453. Using the same assignment of variables to color numbers that was
  6454. produced by the register allocator described in the last section, we
  6455. get the following program.
  6456. \begin{center}
  6457. \begin{minipage}{0.35\textwidth}
  6458. \begin{lstlisting}
  6459. movq $1, v
  6460. movq $42, w
  6461. movq v, x
  6462. addq $7, x
  6463. movq x, y
  6464. movq x, z
  6465. addq w, z
  6466. movq y, t
  6467. negq t
  6468. movq z, %rax
  6469. addq t, %rax
  6470. jmp conclusion
  6471. \end{lstlisting}
  6472. \end{minipage}
  6473. $\Rightarrow\qquad$
  6474. \begin{minipage}{0.45\textwidth}
  6475. \begin{lstlisting}
  6476. movq $1, %rdx
  6477. movq $42, %rcx
  6478. movq %rdx, %rdx
  6479. addq $7, %rdx
  6480. movq %rdx, %rsi
  6481. movq %rdx, %rdx
  6482. addq %rcx, %rdx
  6483. movq %rsi, %rcx
  6484. negq %rcx
  6485. movq %rdx, %rax
  6486. addq %rcx, %rax
  6487. jmp conclusion
  6488. \end{lstlisting}
  6489. \end{minipage}
  6490. \end{center}
  6491. In this output code there are two \key{movq} instructions that
  6492. can be removed because their source and target are the same. However,
  6493. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6494. register, we could instead remove three \key{movq} instructions. We
  6495. can accomplish this by taking into account which variables appear in
  6496. \key{movq} instructions with which other variables.
  6497. \fi}
  6498. {\if\edition\pythonEd\pythonColor
  6499. %
  6500. To motivate the need for move biasing we return to the running example
  6501. and recall that in section~\ref{sec:patch-instructions} we were able to
  6502. remove three trivial move instructions from the running
  6503. example. However, we could remove another trivial move if we were able
  6504. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6505. We say that two variables $p$ and $q$ are \emph{move
  6506. related}\index{subject}{move related} if they participate together in
  6507. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6508. \key{movq} $q$\key{,} $p$.
  6509. %
  6510. Recall that we color variables that are more saturated before coloring
  6511. variables that are less saturated, and in the case of equally
  6512. saturated variables, we choose randomly. Now we break such ties by
  6513. giving preference to variables that have an available color that is
  6514. the same as the color of a move-related variable.
  6515. %
  6516. Furthermore, when the register allocator chooses a color for a
  6517. variable, it should prefer a color that has already been used for a
  6518. move-related variable if one exists (and assuming that they do not
  6519. interfere). This preference should not override the preference for
  6520. registers over stack locations. So, this preference should be used as
  6521. a tie breaker in choosing between two registers or in choosing between
  6522. two stack locations.
  6523. We recommend representing the move relationships in a graph, similarly
  6524. to how we represented interference. The following is the \emph{move
  6525. graph} for our running example.
  6526. {\if\edition\racketEd
  6527. \[
  6528. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6529. \node (rax) at (0,0) {$\ttm{rax}$};
  6530. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6531. \node (t) at (0,2) {$\ttm{t}$};
  6532. \node (z) at (3,2) {$\ttm{z}$};
  6533. \node (x) at (6,2) {$\ttm{x}$};
  6534. \node (y) at (3,0) {$\ttm{y}$};
  6535. \node (w) at (6,0) {$\ttm{w}$};
  6536. \node (v) at (9,0) {$\ttm{v}$};
  6537. \draw (v) to (x);
  6538. \draw (x) to (y);
  6539. \draw (x) to (z);
  6540. \draw (y) to (t);
  6541. \end{tikzpicture}
  6542. \]
  6543. \fi}
  6544. %
  6545. {\if\edition\pythonEd\pythonColor
  6546. \[
  6547. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6548. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6549. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6550. \node (z) at (3,2) {$\ttm{z}$};
  6551. \node (x) at (6,2) {$\ttm{x}$};
  6552. \node (y) at (3,0) {$\ttm{y}$};
  6553. \node (w) at (6,0) {$\ttm{w}$};
  6554. \node (v) at (9,0) {$\ttm{v}$};
  6555. \draw (y) to (t0);
  6556. \draw (z) to (x);
  6557. \draw (z) to (t1);
  6558. \draw (x) to (y);
  6559. \draw (x) to (v);
  6560. \end{tikzpicture}
  6561. \]
  6562. \fi}
  6563. {\if\edition\racketEd
  6564. Now we replay the graph coloring, pausing to see the coloring of
  6565. \code{y}. Recall the following configuration. The most saturated vertices
  6566. were \code{w} and \code{y}.
  6567. \[
  6568. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6569. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6570. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6571. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6572. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6573. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6574. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6575. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6576. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6577. \draw (t1) to (rax);
  6578. \draw (t1) to (z);
  6579. \draw (z) to (y);
  6580. \draw (z) to (w);
  6581. \draw (x) to (w);
  6582. \draw (y) to (w);
  6583. \draw (v) to (w);
  6584. \draw (v) to (rsp);
  6585. \draw (w) to (rsp);
  6586. \draw (x) to (rsp);
  6587. \draw (y) to (rsp);
  6588. \path[-.,bend left=15] (z) edge node {} (rsp);
  6589. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6590. \draw (rax) to (rsp);
  6591. \end{tikzpicture}
  6592. \]
  6593. %
  6594. The last time, we chose to color \code{w} with $0$. This time, we see
  6595. that \code{w} is not move-related to any vertex, but \code{y} is
  6596. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6597. the same color as \code{t}.
  6598. \[
  6599. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6601. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6602. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6603. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6604. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6605. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6606. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6607. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6608. \draw (t1) to (rax);
  6609. \draw (t1) to (z);
  6610. \draw (z) to (y);
  6611. \draw (z) to (w);
  6612. \draw (x) to (w);
  6613. \draw (y) to (w);
  6614. \draw (v) to (w);
  6615. \draw (v) to (rsp);
  6616. \draw (w) to (rsp);
  6617. \draw (x) to (rsp);
  6618. \draw (y) to (rsp);
  6619. \path[-.,bend left=15] (z) edge node {} (rsp);
  6620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6621. \draw (rax) to (rsp);
  6622. \end{tikzpicture}
  6623. \]
  6624. Now \code{w} is the most saturated, so we color it $2$.
  6625. \[
  6626. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6627. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6628. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6629. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6630. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6631. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6632. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6633. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6634. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6635. \draw (t1) to (rax);
  6636. \draw (t1) to (z);
  6637. \draw (z) to (y);
  6638. \draw (z) to (w);
  6639. \draw (x) to (w);
  6640. \draw (y) to (w);
  6641. \draw (v) to (w);
  6642. \draw (v) to (rsp);
  6643. \draw (w) to (rsp);
  6644. \draw (x) to (rsp);
  6645. \draw (y) to (rsp);
  6646. \path[-.,bend left=15] (z) edge node {} (rsp);
  6647. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6648. \draw (rax) to (rsp);
  6649. \end{tikzpicture}
  6650. \]
  6651. At this point, vertices \code{x} and \code{v} are most saturated, but
  6652. \code{x} is move related to \code{y} and \code{z}, so we color
  6653. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6654. \[
  6655. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6656. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6657. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6658. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6659. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6660. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6661. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6662. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6663. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6664. \draw (t1) to (rax);
  6665. \draw (t) to (z);
  6666. \draw (z) to (y);
  6667. \draw (z) to (w);
  6668. \draw (x) to (w);
  6669. \draw (y) to (w);
  6670. \draw (v) to (w);
  6671. \draw (v) to (rsp);
  6672. \draw (w) to (rsp);
  6673. \draw (x) to (rsp);
  6674. \draw (y) to (rsp);
  6675. \path[-.,bend left=15] (z) edge node {} (rsp);
  6676. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6677. \draw (rax) to (rsp);
  6678. \end{tikzpicture}
  6679. \]
  6680. \fi}
  6681. %
  6682. {\if\edition\pythonEd\pythonColor
  6683. Now we replay the graph coloring, pausing before the coloring of
  6684. \code{w}. Recall the following configuration. The most saturated vertices
  6685. were \code{tmp\_1}, \code{w}, and \code{y}.
  6686. \[
  6687. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6688. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6689. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6690. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6691. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6692. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6693. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6694. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6695. \draw (t0) to (t1);
  6696. \draw (t0) to (z);
  6697. \draw (z) to (y);
  6698. \draw (z) to (w);
  6699. \draw (x) to (w);
  6700. \draw (y) to (w);
  6701. \draw (v) to (w);
  6702. \end{tikzpicture}
  6703. \]
  6704. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6705. or \code{y}. Note, however, that \code{w} is not move related to any
  6706. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6707. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6708. \code{y} and color it $0$, we can delete another move instruction.
  6709. \[
  6710. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6711. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6712. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6713. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6714. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6715. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6716. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6717. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6718. \draw (t0) to (t1);
  6719. \draw (t0) to (z);
  6720. \draw (z) to (y);
  6721. \draw (z) to (w);
  6722. \draw (x) to (w);
  6723. \draw (y) to (w);
  6724. \draw (v) to (w);
  6725. \end{tikzpicture}
  6726. \]
  6727. Now \code{w} is the most saturated, so we color it $2$.
  6728. \[
  6729. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6730. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6731. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6732. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6733. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6734. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6735. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6736. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6737. \draw (t0) to (t1);
  6738. \draw (t0) to (z);
  6739. \draw (z) to (y);
  6740. \draw (z) to (w);
  6741. \draw (x) to (w);
  6742. \draw (y) to (w);
  6743. \draw (v) to (w);
  6744. \end{tikzpicture}
  6745. \]
  6746. To finish the coloring, \code{x} and \code{v} get $0$ and
  6747. \code{tmp\_1} gets $1$.
  6748. \[
  6749. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6750. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6751. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6752. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6753. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6754. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6755. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6756. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6757. \draw (t0) to (t1);
  6758. \draw (t0) to (z);
  6759. \draw (z) to (y);
  6760. \draw (z) to (w);
  6761. \draw (x) to (w);
  6762. \draw (y) to (w);
  6763. \draw (v) to (w);
  6764. \end{tikzpicture}
  6765. \]
  6766. \fi}
  6767. So, we have the following assignment of variables to registers.
  6768. {\if\edition\racketEd
  6769. \begin{gather*}
  6770. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6771. \ttm{w} \mapsto \key{\%rsi}, \,
  6772. \ttm{x} \mapsto \key{\%rcx}, \,
  6773. \ttm{y} \mapsto \key{\%rcx}, \,
  6774. \ttm{z} \mapsto \key{\%rdx}, \,
  6775. \ttm{t} \mapsto \key{\%rcx} \}
  6776. \end{gather*}
  6777. \fi}
  6778. {\if\edition\pythonEd\pythonColor
  6779. \begin{gather*}
  6780. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6781. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6782. \ttm{x} \mapsto \key{\%rcx}, \,
  6783. \ttm{y} \mapsto \key{\%rcx}, \\
  6784. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6785. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6786. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6787. \end{gather*}
  6788. \fi}
  6789. %
  6790. We apply this register assignment to the running example shown next,
  6791. on the left, to obtain the code in the middle. The
  6792. \code{patch\_instructions} then deletes the trivial moves to obtain
  6793. the code on the right.
  6794. {\if\edition\racketEd
  6795. \begin{center}
  6796. \begin{minipage}{0.2\textwidth}
  6797. \begin{lstlisting}
  6798. movq $1, v
  6799. movq $42, w
  6800. movq v, x
  6801. addq $7, x
  6802. movq x, y
  6803. movq x, z
  6804. addq w, z
  6805. movq y, t
  6806. negq t
  6807. movq z, %rax
  6808. addq t, %rax
  6809. jmp conclusion
  6810. \end{lstlisting}
  6811. \end{minipage}
  6812. $\Rightarrow\qquad$
  6813. \begin{minipage}{0.25\textwidth}
  6814. \begin{lstlisting}
  6815. movq $1, %rcx
  6816. movq $42, %rsi
  6817. movq %rcx, %rcx
  6818. addq $7, %rcx
  6819. movq %rcx, %rcx
  6820. movq %rcx, %rdx
  6821. addq %rsi, %rdx
  6822. movq %rcx, %rcx
  6823. negq %rcx
  6824. movq %rdx, %rax
  6825. addq %rcx, %rax
  6826. jmp conclusion
  6827. \end{lstlisting}
  6828. \end{minipage}
  6829. $\Rightarrow\qquad$
  6830. \begin{minipage}{0.23\textwidth}
  6831. \begin{lstlisting}
  6832. movq $1, %rcx
  6833. movq $42, %rsi
  6834. addq $7, %rcx
  6835. movq %rcx, %rdx
  6836. addq %rsi, %rdx
  6837. negq %rcx
  6838. movq %rdx, %rax
  6839. addq %rcx, %rax
  6840. jmp conclusion
  6841. \end{lstlisting}
  6842. \end{minipage}
  6843. \end{center}
  6844. \fi}
  6845. {\if\edition\pythonEd\pythonColor
  6846. \begin{center}
  6847. \begin{minipage}{0.20\textwidth}
  6848. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6849. movq $1, v
  6850. movq $42, w
  6851. movq v, x
  6852. addq $7, x
  6853. movq x, y
  6854. movq x, z
  6855. addq w, z
  6856. movq y, tmp_0
  6857. negq tmp_0
  6858. movq z, tmp_1
  6859. addq tmp_0, tmp_1
  6860. movq tmp_1, %rdi
  6861. callq _print_int
  6862. \end{lstlisting}
  6863. \end{minipage}
  6864. ${\Rightarrow\qquad}$
  6865. \begin{minipage}{0.35\textwidth}
  6866. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6867. movq $1, %rcx
  6868. movq $42, -16(%rbp)
  6869. movq %rcx, %rcx
  6870. addq $7, %rcx
  6871. movq %rcx, %rcx
  6872. movq %rcx, -8(%rbp)
  6873. addq -16(%rbp), -8(%rbp)
  6874. movq %rcx, %rcx
  6875. negq %rcx
  6876. movq -8(%rbp), -8(%rbp)
  6877. addq %rcx, -8(%rbp)
  6878. movq -8(%rbp), %rdi
  6879. callq _print_int
  6880. \end{lstlisting}
  6881. \end{minipage}
  6882. ${\Rightarrow\qquad}$
  6883. \begin{minipage}{0.20\textwidth}
  6884. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6885. movq $1, %rcx
  6886. movq $42, -16(%rbp)
  6887. addq $7, %rcx
  6888. movq %rcx, -8(%rbp)
  6889. movq -16(%rbp), %rax
  6890. addq %rax, -8(%rbp)
  6891. negq %rcx
  6892. addq %rcx, -8(%rbp)
  6893. movq -8(%rbp), %rdi
  6894. callq print_int
  6895. \end{lstlisting}
  6896. \end{minipage}
  6897. \end{center}
  6898. \fi}
  6899. \begin{exercise}\normalfont\normalsize
  6900. Change your implementation of \code{allocate\_registers} to take move
  6901. biasing into account. Create two new tests that include at least one
  6902. opportunity for move biasing, and visually inspect the output x86
  6903. programs to make sure that your move biasing is working properly. Make
  6904. sure that your compiler still passes all the tests.
  6905. \end{exercise}
  6906. %To do: another neat challenge would be to do
  6907. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6908. %% \subsection{Output of the Running Example}
  6909. %% \label{sec:reg-alloc-output}
  6910. % challenge: prioritize variables based on execution frequencies
  6911. % and the number of uses of a variable
  6912. % challenge: enhance the coloring algorithm using Chaitin's
  6913. % approach of prioritizing high-degree variables
  6914. % by removing low-degree variables (coloring them later)
  6915. % from the interference graph
  6916. \section{Further Reading}
  6917. \label{sec:register-allocation-further-reading}
  6918. Early register allocation algorithms were developed for Fortran
  6919. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6920. of graph coloring began in the late 1970s and early 1980s with the
  6921. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6922. algorithm is based on the following observation of
  6923. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6924. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6925. $v$ removed is also $k$ colorable. To see why, suppose that the
  6926. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6927. different colors, but because there are fewer than $k$ neighbors, there
  6928. will be one or more colors left over to use for coloring $v$ in $G$.
  6929. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6930. less than $k$ from the graph and recursively colors the rest of the
  6931. graph. Upon returning from the recursion, it colors $v$ with one of
  6932. the available colors and returns. \citet{Chaitin:1982vn} augments
  6933. this algorithm to handle spilling as follows. If there are no vertices
  6934. of degree lower than $k$ then pick a vertex at random, spill it,
  6935. remove it from the graph, and proceed recursively to color the rest of
  6936. the graph.
  6937. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6938. move-related and that don't interfere with each other, in a process
  6939. called \emph{coalescing}. Although coalescing decreases the number of
  6940. moves, it can make the graph more difficult to
  6941. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6942. which two variables are merged only if they have fewer than $k$
  6943. neighbors of high degree. \citet{George:1996aa} observes that
  6944. conservative coalescing is sometimes too conservative and made it more
  6945. aggressive by iterating the coalescing with the removal of low-degree
  6946. vertices.
  6947. %
  6948. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6949. also proposed \emph{biased coloring}, in which a variable is assigned to
  6950. the same color as another move-related variable if possible, as
  6951. discussed in section~\ref{sec:move-biasing}.
  6952. %
  6953. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6954. performs coalescing, graph coloring, and spill code insertion until
  6955. all variables have been assigned a location.
  6956. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6957. spilled variables that don't have to be: a high-degree variable can be
  6958. colorable if many of its neighbors are assigned the same color.
  6959. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6960. high-degree vertex is not immediately spilled. Instead the decision is
  6961. deferred until after the recursive call, when it is apparent whether
  6962. there is an available color or not. We observe that this algorithm is
  6963. equivalent to the smallest-last ordering
  6964. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6965. be registers and the rest to be stack locations.
  6966. %% biased coloring
  6967. Earlier editions of the compiler course at Indiana University
  6968. \citep{Dybvig:2010aa} were based on the algorithm of
  6969. \citet{Briggs:1994kx}.
  6970. The smallest-last ordering algorithm is one of many \emph{greedy}
  6971. coloring algorithms. A greedy coloring algorithm visits all the
  6972. vertices in a particular order and assigns each one the first
  6973. available color. An \emph{offline} greedy algorithm chooses the
  6974. ordering up front, prior to assigning colors. The algorithm of
  6975. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6976. ordering does not depend on the colors assigned. Other orderings are
  6977. possible. For example, \citet{Chow:1984ys} ordered variables according
  6978. to an estimate of runtime cost.
  6979. An \emph{online} greedy coloring algorithm uses information about the
  6980. current assignment of colors to influence the order in which the
  6981. remaining vertices are colored. The saturation-based algorithm
  6982. described in this chapter is one such algorithm. We choose to use
  6983. saturation-based coloring because it is fun to introduce graph
  6984. coloring via sudoku!
  6985. A register allocator may choose to map each variable to just one
  6986. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6987. variable to one or more locations. The latter can be achieved by
  6988. \emph{live range splitting}, where a variable is replaced by several
  6989. variables that each handle part of its live
  6990. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6991. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6992. %% replacement algorithm, bottom-up local
  6993. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6994. %% Cooper: top-down (priority bassed), bottom-up
  6995. %% top-down
  6996. %% order variables by priority (estimated cost)
  6997. %% caveat: split variables into two groups:
  6998. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6999. %% color the constrained ones first
  7000. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7001. %% cite J. Cocke for an algorithm that colors variables
  7002. %% in a high-degree first ordering
  7003. %Register Allocation via Usage Counts, Freiburghouse CACM
  7004. \citet{Palsberg:2007si} observes that many of the interference graphs
  7005. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7006. that is, every cycle with four or more edges has an edge that is not
  7007. part of the cycle but that connects two vertices on the cycle. Such
  7008. graphs can be optimally colored by the greedy algorithm with a vertex
  7009. ordering determined by maximum cardinality search.
  7010. In situations in which compile time is of utmost importance, such as
  7011. in just-in-time compilers, graph coloring algorithms can be too
  7012. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7013. be more appropriate.
  7014. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7015. {\if\edition\racketEd
  7016. \addtocontents{toc}{\newpage}
  7017. \fi}
  7018. \chapter{Booleans and Conditionals}
  7019. \label{ch:Lif}
  7020. \setcounter{footnote}{0}
  7021. The \LangVar{} language has only a single kind of value, the
  7022. integers. In this chapter we add a second kind of value, the Booleans,
  7023. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7024. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7025. are written
  7026. \TRUE{}\index{subject}{True@\TRUE{}} and
  7027. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7028. language includes several operations that involve Booleans
  7029. (\key{and}\index{subject}{and@\ANDNAME{}},
  7030. \key{or}\index{subject}{or@\ORNAME{}},
  7031. \key{not}\index{subject}{not@\NOTNAME{}},
  7032. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7033. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7034. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7035. conditional expression\index{subject}{conditional expression}
  7036. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7037. With the addition of \key{if}, programs can have
  7038. nontrivial control flow\index{subject}{control flow}, which
  7039. %
  7040. \racket{impacts \code{explicate\_control} and liveness analysis.}
  7041. %
  7042. \python{impacts liveness analysis and motivates a new pass named
  7043. \code{explicate\_control}.}
  7044. %
  7045. Also, because we now have two kinds of values, we need to handle
  7046. programs that apply an operation to the wrong kind of value, such as
  7047. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7048. There are two language design options for such situations. One option
  7049. is to signal an error and the other is to provide a wider
  7050. interpretation of the operation. \racket{The Racket
  7051. language}\python{Python} uses a mixture of these two options,
  7052. depending on the operation and the kind of value. For example, the
  7053. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7054. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7055. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7056. %
  7057. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7058. in Racket because \code{car} expects a pair.}
  7059. %
  7060. \python{On the other hand, \code{1[0]} results in a runtime error
  7061. in Python because an ``\code{int} object is not subscriptable.''}
  7062. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7063. design choices as \racket{Racket}\python{Python}, except that much of the
  7064. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7065. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7066. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7067. \python{MyPy} reports a compile-time error
  7068. %
  7069. \racket{because Racket expects the type of the argument to be of the form
  7070. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7071. %
  7072. \python{stating that a ``value of type \code{int} is not indexable.''}
  7073. The \LangIf{} language performs type checking during compilation just as
  7074. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7075. the alternative choice, that is, a dynamically typed language like
  7076. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7077. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7078. restrictive, for example, rejecting \racket{\code{(not
  7079. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7080. fairly simple because the focus of this book is on compilation and not
  7081. type systems, about which there are already several excellent
  7082. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7083. This chapter is organized as follows. We begin by defining the syntax
  7084. and interpreter for the \LangIf{} language
  7085. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7086. checking (aka semantic analysis\index{subject}{semantic analysis})
  7087. and define a type checker for \LangIf{}
  7088. (section~\ref{sec:type-check-Lif}).
  7089. %
  7090. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7091. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7092. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7093. %
  7094. The remaining sections of this chapter discuss how Booleans and
  7095. conditional control flow require changes to the existing compiler
  7096. passes and the addition of new ones. We introduce the \code{shrink}
  7097. pass to translate some operators into others, thereby reducing the
  7098. number of operators that need to be handled in later passes.
  7099. %
  7100. The main event of this chapter is the \code{explicate\_control} pass
  7101. that is responsible for translating \code{if}s into conditional
  7102. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7103. %
  7104. Regarding register allocation, there is the interesting question of
  7105. how to handle conditional \code{goto}s during liveness analysis.
  7106. \section{The \LangIf{} Language}
  7107. \label{sec:lang-if}
  7108. Definitions of the concrete syntax and abstract syntax of the
  7109. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7110. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7111. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7112. literals\index{subject}{literals}
  7113. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7114. \python{, and the \code{if} statement}. We expand the set of
  7115. operators to include
  7116. \begin{enumerate}
  7117. \item the logical operators \key{and}, \key{or}, and \key{not},
  7118. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7119. for comparing integers or Booleans for equality, and
  7120. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7121. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7122. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7123. comparing integers.
  7124. \end{enumerate}
  7125. \racket{We reorganize the abstract syntax for the primitive
  7126. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7127. rule for all of them. This means that the grammar no longer checks
  7128. whether the arity of an operator matches the number of
  7129. arguments. That responsibility is moved to the type checker for
  7130. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7131. \newcommand{\LifGrammarRacket}{
  7132. \begin{array}{lcl}
  7133. \Type &::=& \key{Boolean} \\
  7134. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7135. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7136. \Exp &::=& \itm{bool}
  7137. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7138. \MID (\key{not}\;\Exp) \\
  7139. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7140. \end{array}
  7141. }
  7142. \newcommand{\LifASTRacket}{
  7143. \begin{array}{lcl}
  7144. \Type &::=& \key{Boolean} \\
  7145. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7146. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7147. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7148. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7149. \end{array}
  7150. }
  7151. \newcommand{\LintOpAST}{
  7152. \begin{array}{rcl}
  7153. \Type &::=& \key{Integer} \\
  7154. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7155. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7156. \end{array}
  7157. }
  7158. \newcommand{\LifGrammarPython}{
  7159. \begin{array}{rcl}
  7160. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7161. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7162. \MID \key{not}~\Exp \\
  7163. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7164. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7165. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7166. \end{array}
  7167. }
  7168. \newcommand{\LifASTPython}{
  7169. \begin{array}{lcl}
  7170. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7171. \itm{unaryop} &::=& \code{Not()} \\
  7172. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7173. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7174. \Exp &::=& \BOOL{\itm{bool}}
  7175. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7176. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7177. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7178. \end{array}
  7179. }
  7180. \begin{figure}[tp]
  7181. \centering
  7182. \begin{tcolorbox}[colback=white]
  7183. {\if\edition\racketEd
  7184. \[
  7185. \begin{array}{l}
  7186. \gray{\LintGrammarRacket{}} \\ \hline
  7187. \gray{\LvarGrammarRacket{}} \\ \hline
  7188. \LifGrammarRacket{} \\
  7189. \begin{array}{lcl}
  7190. \LangIfM{} &::=& \Exp
  7191. \end{array}
  7192. \end{array}
  7193. \]
  7194. \fi}
  7195. {\if\edition\pythonEd\pythonColor
  7196. \[
  7197. \begin{array}{l}
  7198. \gray{\LintGrammarPython} \\ \hline
  7199. \gray{\LvarGrammarPython} \\ \hline
  7200. \LifGrammarPython \\
  7201. \begin{array}{rcl}
  7202. \LangIfM{} &::=& \Stmt^{*}
  7203. \end{array}
  7204. \end{array}
  7205. \]
  7206. \fi}
  7207. \end{tcolorbox}
  7208. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7209. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7210. \label{fig:Lif-concrete-syntax}
  7211. \end{figure}
  7212. \begin{figure}[tp]
  7213. %\begin{minipage}{0.66\textwidth}
  7214. \begin{tcolorbox}[colback=white]
  7215. \centering
  7216. {\if\edition\racketEd
  7217. \[
  7218. \begin{array}{l}
  7219. \gray{\LintOpAST} \\ \hline
  7220. \gray{\LvarASTRacket{}} \\ \hline
  7221. \LifASTRacket{} \\
  7222. \begin{array}{lcl}
  7223. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7224. \end{array}
  7225. \end{array}
  7226. \]
  7227. \fi}
  7228. {\if\edition\pythonEd\pythonColor
  7229. \[
  7230. \begin{array}{l}
  7231. \gray{\LintASTPython} \\ \hline
  7232. \gray{\LvarASTPython} \\ \hline
  7233. \LifASTPython \\
  7234. \begin{array}{lcl}
  7235. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7236. \end{array}
  7237. \end{array}
  7238. \]
  7239. \fi}
  7240. \end{tcolorbox}
  7241. %\end{minipage}
  7242. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7243. \python{
  7244. \index{subject}{BoolOp@\texttt{BoolOp}}
  7245. \index{subject}{Compare@\texttt{Compare}}
  7246. \index{subject}{Lt@\texttt{Lt}}
  7247. \index{subject}{LtE@\texttt{LtE}}
  7248. \index{subject}{Gt@\texttt{Gt}}
  7249. \index{subject}{GtE@\texttt{GtE}}
  7250. }
  7251. \caption{The abstract syntax of \LangIf{}.}
  7252. \label{fig:Lif-syntax}
  7253. \end{figure}
  7254. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7255. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7256. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7257. evaluate to the corresponding Boolean values. The conditional
  7258. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7259. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7260. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7261. \code{or}, and \code{not} behave according to propositional logic. In
  7262. addition, the \code{and} and \code{or} operations perform
  7263. \emph{short-circuit evaluation}.
  7264. %
  7265. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7266. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7267. %
  7268. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7269. evaluated if $e_1$ evaluates to \TRUE{}.
  7270. \racket{With the increase in the number of primitive operations, the
  7271. interpreter would become repetitive without some care. We refactor
  7272. the case for \code{Prim}, moving the code that differs with each
  7273. operation into the \code{interp\_op} method shown in
  7274. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7275. \code{or} operations separately because of their short-circuiting
  7276. behavior.}
  7277. \begin{figure}[tbp]
  7278. \begin{tcolorbox}[colback=white]
  7279. {\if\edition\racketEd
  7280. \begin{lstlisting}
  7281. (define interp-Lif-class
  7282. (class interp-Lvar-class
  7283. (super-new)
  7284. (define/public (interp_op op) ...)
  7285. (define/override ((interp_exp env) e)
  7286. (define recur (interp_exp env))
  7287. (match e
  7288. [(Bool b) b]
  7289. [(If cnd thn els)
  7290. (match (recur cnd)
  7291. [#t (recur thn)]
  7292. [#f (recur els)])]
  7293. [(Prim 'and (list e1 e2))
  7294. (match (recur e1)
  7295. [#t (match (recur e2) [#t #t] [#f #f])]
  7296. [#f #f])]
  7297. [(Prim 'or (list e1 e2))
  7298. (define v1 (recur e1))
  7299. (match v1
  7300. [#t #t]
  7301. [#f (match (recur e2) [#t #t] [#f #f])])]
  7302. [(Prim op args)
  7303. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7304. [else ((super interp_exp env) e)]))
  7305. ))
  7306. (define (interp_Lif p)
  7307. (send (new interp-Lif-class) interp_program p))
  7308. \end{lstlisting}
  7309. \fi}
  7310. {\if\edition\pythonEd\pythonColor
  7311. \begin{lstlisting}
  7312. class InterpLif(InterpLvar):
  7313. def interp_exp(self, e, env):
  7314. match e:
  7315. case IfExp(test, body, orelse):
  7316. if self.interp_exp(test, env):
  7317. return self.interp_exp(body, env)
  7318. else:
  7319. return self.interp_exp(orelse, env)
  7320. case UnaryOp(Not(), v):
  7321. return not self.interp_exp(v, env)
  7322. case BoolOp(And(), values):
  7323. if self.interp_exp(values[0], env):
  7324. return self.interp_exp(values[1], env)
  7325. else:
  7326. return False
  7327. case BoolOp(Or(), values):
  7328. if self.interp_exp(values[0], env):
  7329. return True
  7330. else:
  7331. return self.interp_exp(values[1], env)
  7332. case Compare(left, [cmp], [right]):
  7333. l = self.interp_exp(left, env)
  7334. r = self.interp_exp(right, env)
  7335. return self.interp_cmp(cmp)(l, r)
  7336. case _:
  7337. return super().interp_exp(e, env)
  7338. def interp_stmt(self, s, env, cont):
  7339. match s:
  7340. case If(test, body, orelse):
  7341. match self.interp_exp(test, env):
  7342. case True:
  7343. return self.interp_stmts(body + cont, env)
  7344. case False:
  7345. return self.interp_stmts(orelse + cont, env)
  7346. case _:
  7347. return super().interp_stmt(s, env, cont)
  7348. ...
  7349. \end{lstlisting}
  7350. \fi}
  7351. \end{tcolorbox}
  7352. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7353. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7354. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7355. \label{fig:interp-Lif}
  7356. \end{figure}
  7357. {\if\edition\racketEd
  7358. \begin{figure}[tbp]
  7359. \begin{tcolorbox}[colback=white]
  7360. \begin{lstlisting}
  7361. (define/public (interp_op op)
  7362. (match op
  7363. ['+ fx+]
  7364. ['- fx-]
  7365. ['read read-fixnum]
  7366. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7367. ['eq? (lambda (v1 v2)
  7368. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7369. (and (boolean? v1) (boolean? v2))
  7370. (and (vector? v1) (vector? v2)))
  7371. (eq? v1 v2)]))]
  7372. ['< (lambda (v1 v2)
  7373. (cond [(and (fixnum? v1) (fixnum? v2))
  7374. (< v1 v2)]))]
  7375. ['<= (lambda (v1 v2)
  7376. (cond [(and (fixnum? v1) (fixnum? v2))
  7377. (<= v1 v2)]))]
  7378. ['> (lambda (v1 v2)
  7379. (cond [(and (fixnum? v1) (fixnum? v2))
  7380. (> v1 v2)]))]
  7381. ['>= (lambda (v1 v2)
  7382. (cond [(and (fixnum? v1) (fixnum? v2))
  7383. (>= v1 v2)]))]
  7384. [else (error 'interp_op "unknown operator")]))
  7385. \end{lstlisting}
  7386. \end{tcolorbox}
  7387. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7388. \label{fig:interp-op-Lif}
  7389. \end{figure}
  7390. \fi}
  7391. {\if\edition\pythonEd\pythonColor
  7392. \begin{figure}
  7393. \begin{tcolorbox}[colback=white]
  7394. \begin{lstlisting}
  7395. class InterpLif(InterpLvar):
  7396. ...
  7397. def interp_cmp(self, cmp):
  7398. match cmp:
  7399. case Lt():
  7400. return lambda x, y: x < y
  7401. case LtE():
  7402. return lambda x, y: x <= y
  7403. case Gt():
  7404. return lambda x, y: x > y
  7405. case GtE():
  7406. return lambda x, y: x >= y
  7407. case Eq():
  7408. return lambda x, y: x == y
  7409. case NotEq():
  7410. return lambda x, y: x != y
  7411. \end{lstlisting}
  7412. \end{tcolorbox}
  7413. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7414. \label{fig:interp-cmp-Lif}
  7415. \end{figure}
  7416. \fi}
  7417. \section{Type Checking \LangIf{} Programs}
  7418. \label{sec:type-check-Lif}
  7419. It is helpful to think about type checking\index{subject}{type
  7420. checking} in two complementary ways. A type checker predicts the
  7421. type of value that will be produced by each expression in the program.
  7422. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7423. type checker should predict that {\if\edition\racketEd
  7424. \begin{lstlisting}
  7425. (+ 10 (- (+ 12 20)))
  7426. \end{lstlisting}
  7427. \fi}
  7428. {\if\edition\pythonEd\pythonColor
  7429. \begin{lstlisting}
  7430. 10 + -(12 + 20)
  7431. \end{lstlisting}
  7432. \fi}
  7433. \noindent produces a value of type \INTTY{}, whereas
  7434. {\if\edition\racketEd
  7435. \begin{lstlisting}
  7436. (and (not #f) #t)
  7437. \end{lstlisting}
  7438. \fi}
  7439. {\if\edition\pythonEd\pythonColor
  7440. \begin{lstlisting}
  7441. (not False) and True
  7442. \end{lstlisting}
  7443. \fi}
  7444. \noindent produces a value of type \BOOLTY{}.
  7445. A second way to think about type checking is that it enforces a set of
  7446. rules about which operators can be applied to which kinds of
  7447. values. For example, our type checker for \LangIf{} signals an error
  7448. for the following expression:
  7449. %
  7450. {\if\edition\racketEd
  7451. \begin{lstlisting}
  7452. (not (+ 10 (- (+ 12 20))))
  7453. \end{lstlisting}
  7454. \fi}
  7455. {\if\edition\pythonEd\pythonColor
  7456. \begin{lstlisting}
  7457. not (10 + -(12 + 20))
  7458. \end{lstlisting}
  7459. \fi}
  7460. \noindent The subexpression
  7461. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7462. \python{\code{(10 + -(12 + 20))}}
  7463. has type \INTTY{}, but the type checker enforces the rule that the
  7464. argument of \code{not} must be an expression of type \BOOLTY{}.
  7465. We implement type checking using classes and methods because they
  7466. provide the open recursion needed to reuse code as we extend the type
  7467. checker in subsequent chapters, analogous to the use of classes and methods
  7468. for the interpreters (section~\ref{sec:extensible-interp}).
  7469. We separate the type checker for the \LangVar{} subset into its own
  7470. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7471. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7472. from the type checker for \LangVar{}. These type checkers are in the
  7473. files
  7474. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7475. and
  7476. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7477. of the support code.
  7478. %
  7479. Each type checker is a structurally recursive function over the AST.
  7480. Given an input expression \code{e}, the type checker either signals an
  7481. error or returns \racket{an expression and} its type.
  7482. %
  7483. \racket{It returns an expression because there are situations in which
  7484. we want to change or update the expression.}
  7485. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7486. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7487. constant is \INTTY{}. To handle variables, the type checker uses the
  7488. environment \code{env} to map variables to types.
  7489. %
  7490. \racket{Consider the case for \key{let}. We type check the
  7491. initializing expression to obtain its type \key{T} and then
  7492. associate type \code{T} with the variable \code{x} in the
  7493. environment used to type check the body of the \key{let}. Thus,
  7494. when the type checker encounters a use of variable \code{x}, it can
  7495. find its type in the environment.}
  7496. %
  7497. \python{Consider the case for assignment. We type check the
  7498. initializing expression to obtain its type \key{t}. If the variable
  7499. \code{lhs.id} is already in the environment because there was a
  7500. prior assignment, we check that this initializer has the same type
  7501. as the prior one. If this is the first assignment to the variable,
  7502. we associate type \code{t} with the variable \code{lhs.id} in the
  7503. environment. Thus, when the type checker encounters a use of
  7504. variable \code{x}, it can find its type in the environment.}
  7505. %
  7506. \racket{Regarding primitive operators, we recursively analyze the
  7507. arguments and then invoke \code{type\_check\_op} to check whether
  7508. the argument types are allowed.}
  7509. %
  7510. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7511. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7512. \racket{Several auxiliary methods are used in the type checker. The
  7513. method \code{operator-types} defines a dictionary that maps the
  7514. operator names to their parameter and return types. The
  7515. \code{type-equal?} method determines whether two types are equal,
  7516. which for now simply dispatches to \code{equal?} (deep
  7517. equality). The \code{check-type-equal?} method triggers an error if
  7518. the two types are not equal. The \code{type-check-op} method looks
  7519. up the operator in the \code{operator-types} dictionary and then
  7520. checks whether the argument types are equal to the parameter types.
  7521. The result is the return type of the operator.}
  7522. %
  7523. \python{The auxiliary method \code{check\_type\_equal} triggers
  7524. an error if the two types are not equal.}
  7525. \begin{figure}[tbp]
  7526. \begin{tcolorbox}[colback=white]
  7527. {\if\edition\racketEd
  7528. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7529. (define type-check-Lvar-class
  7530. (class object%
  7531. (super-new)
  7532. (define/public (operator-types)
  7533. '((+ . ((Integer Integer) . Integer))
  7534. (- . ((Integer Integer) . Integer))
  7535. (read . (() . Integer))))
  7536. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7537. (define/public (check-type-equal? t1 t2 e)
  7538. (unless (type-equal? t1 t2)
  7539. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7540. (define/public (type-check-op op arg-types e)
  7541. (match (dict-ref (operator-types) op)
  7542. [`(,param-types . ,return-type)
  7543. (for ([at arg-types] [pt param-types])
  7544. (check-type-equal? at pt e))
  7545. return-type]
  7546. [else (error 'type-check-op "unrecognized ~a" op)]))
  7547. (define/public (type-check-exp env)
  7548. (lambda (e)
  7549. (match e
  7550. [(Int n) (values (Int n) 'Integer)]
  7551. [(Var x) (values (Var x) (dict-ref env x))]
  7552. [(Let x e body)
  7553. (define-values (e^ Te) ((type-check-exp env) e))
  7554. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7555. (values (Let x e^ b) Tb)]
  7556. [(Prim op es)
  7557. (define-values (new-es ts)
  7558. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7559. (values (Prim op new-es) (type-check-op op ts e))]
  7560. [else (error 'type-check-exp "couldn't match" e)])))
  7561. (define/public (type-check-program e)
  7562. (match e
  7563. [(Program info body)
  7564. (define-values (body^ Tb) ((type-check-exp '()) body))
  7565. (check-type-equal? Tb 'Integer body)
  7566. (Program info body^)]
  7567. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7568. ))
  7569. (define (type-check-Lvar p)
  7570. (send (new type-check-Lvar-class) type-check-program p))
  7571. \end{lstlisting}
  7572. \fi}
  7573. {\if\edition\pythonEd\pythonColor
  7574. \begin{lstlisting}[escapechar=`]
  7575. class TypeCheckLvar:
  7576. def check_type_equal(self, t1, t2, e):
  7577. if t1 != t2:
  7578. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7579. raise Exception(msg)
  7580. def type_check_exp(self, e, env):
  7581. match e:
  7582. case BinOp(left, (Add() | Sub()), right):
  7583. l = self.type_check_exp(left, env)
  7584. check_type_equal(l, int, left)
  7585. r = self.type_check_exp(right, env)
  7586. check_type_equal(r, int, right)
  7587. return int
  7588. case UnaryOp(USub(), v):
  7589. t = self.type_check_exp(v, env)
  7590. check_type_equal(t, int, v)
  7591. return int
  7592. case Name(id):
  7593. return env[id]
  7594. case Constant(value) if isinstance(value, int):
  7595. return int
  7596. case Call(Name('input_int'), []):
  7597. return int
  7598. def type_check_stmts(self, ss, env):
  7599. if len(ss) == 0:
  7600. return
  7601. match ss[0]:
  7602. case Assign([lhs], value):
  7603. t = self.type_check_exp(value, env)
  7604. if lhs.id in env:
  7605. check_type_equal(env[lhs.id], t, value)
  7606. else:
  7607. env[lhs.id] = t
  7608. return self.type_check_stmts(ss[1:], env)
  7609. case Expr(Call(Name('print'), [arg])):
  7610. t = self.type_check_exp(arg, env)
  7611. check_type_equal(t, int, arg)
  7612. return self.type_check_stmts(ss[1:], env)
  7613. case Expr(value):
  7614. self.type_check_exp(value, env)
  7615. return self.type_check_stmts(ss[1:], env)
  7616. def type_check_P(self, p):
  7617. match p:
  7618. case Module(body):
  7619. self.type_check_stmts(body, {})
  7620. \end{lstlisting}
  7621. \fi}
  7622. \end{tcolorbox}
  7623. \caption{Type checker for the \LangVar{} language.}
  7624. \label{fig:type-check-Lvar}
  7625. \end{figure}
  7626. \begin{figure}[tbp]
  7627. \begin{tcolorbox}[colback=white]
  7628. {\if\edition\racketEd
  7629. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7630. (define type-check-Lif-class
  7631. (class type-check-Lvar-class
  7632. (super-new)
  7633. (inherit check-type-equal?)
  7634. (define/override (operator-types)
  7635. (append '((and . ((Boolean Boolean) . Boolean))
  7636. (or . ((Boolean Boolean) . Boolean))
  7637. (< . ((Integer Integer) . Boolean))
  7638. (<= . ((Integer Integer) . Boolean))
  7639. (> . ((Integer Integer) . Boolean))
  7640. (>= . ((Integer Integer) . Boolean))
  7641. (not . ((Boolean) . Boolean)))
  7642. (super operator-types)))
  7643. (define/override (type-check-exp env)
  7644. (lambda (e)
  7645. (match e
  7646. [(Bool b) (values (Bool b) 'Boolean)]
  7647. [(Prim 'eq? (list e1 e2))
  7648. (define-values (e1^ T1) ((type-check-exp env) e1))
  7649. (define-values (e2^ T2) ((type-check-exp env) e2))
  7650. (check-type-equal? T1 T2 e)
  7651. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7652. [(If cnd thn els)
  7653. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7654. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7655. (define-values (els^ Te) ((type-check-exp env) els))
  7656. (check-type-equal? Tc 'Boolean e)
  7657. (check-type-equal? Tt Te e)
  7658. (values (If cnd^ thn^ els^) Te)]
  7659. [else ((super type-check-exp env) e)])))
  7660. ))
  7661. (define (type-check-Lif p)
  7662. (send (new type-check-Lif-class) type-check-program p))
  7663. \end{lstlisting}
  7664. \fi}
  7665. {\if\edition\pythonEd\pythonColor
  7666. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7667. class TypeCheckLif(TypeCheckLvar):
  7668. def type_check_exp(self, e, env):
  7669. match e:
  7670. case Constant(value) if isinstance(value, bool):
  7671. return bool
  7672. case BinOp(left, Sub(), right):
  7673. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7674. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7675. return int
  7676. case UnaryOp(Not(), v):
  7677. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7678. return bool
  7679. case BoolOp(op, values):
  7680. left = values[0] ; right = values[1]
  7681. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7682. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7683. return bool
  7684. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7685. or isinstance(cmp, NotEq):
  7686. l = self.type_check_exp(left, env)
  7687. r = self.type_check_exp(right, env)
  7688. check_type_equal(l, r, e)
  7689. return bool
  7690. case Compare(left, [cmp], [right]):
  7691. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7692. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7693. return bool
  7694. case IfExp(test, body, orelse):
  7695. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7696. b = self.type_check_exp(body, env)
  7697. o = self.type_check_exp(orelse, env)
  7698. check_type_equal(b, o, e)
  7699. return b
  7700. case _:
  7701. return super().type_check_exp(e, env)
  7702. def type_check_stmts(self, ss, env):
  7703. if len(ss) == 0:
  7704. return
  7705. match ss[0]:
  7706. case If(test, body, orelse):
  7707. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7708. b = self.type_check_stmts(body, env)
  7709. o = self.type_check_stmts(orelse, env)
  7710. check_type_equal(b, o, ss[0])
  7711. return self.type_check_stmts(ss[1:], env)
  7712. case _:
  7713. return super().type_check_stmts(ss, env)
  7714. \end{lstlisting}
  7715. \fi}
  7716. \end{tcolorbox}
  7717. \caption{Type checker for the \LangIf{} language.}
  7718. \label{fig:type-check-Lif}
  7719. \end{figure}
  7720. The definition of the type checker for \LangIf{} is shown in
  7721. figure~\ref{fig:type-check-Lif}.
  7722. %
  7723. The type of a Boolean constant is \BOOLTY{}.
  7724. %
  7725. \racket{The \code{operator-types} function adds dictionary entries for
  7726. the new operators.}
  7727. %
  7728. \python{The logical \code{not} operator requires its argument to be a
  7729. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7730. and logical \code{or} operators.}
  7731. %
  7732. The equality operator requires the two arguments to have the same type,
  7733. and therefore we handle it separately from the other operators.
  7734. %
  7735. \python{The other comparisons (less-than, etc.) require their
  7736. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7737. %
  7738. The condition of an \code{if} must
  7739. be of \BOOLTY{} type, and the two branches must have the same type.
  7740. \begin{exercise}\normalfont\normalsize
  7741. Create ten new test programs in \LangIf{}. Half the programs should
  7742. have a type error. For those programs, create an empty file with the
  7743. same base name and with file extension \code{.tyerr}. For example, if
  7744. the test
  7745. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7746. is expected to error, then create
  7747. an empty file named \code{cond\_test\_14.tyerr}.
  7748. %
  7749. \racket{This indicates to \code{interp-tests} and
  7750. \code{compiler-tests} that a type error is expected. }
  7751. %
  7752. The other half of the test programs should not have type errors.
  7753. %
  7754. \racket{In the \code{run-tests.rkt} script, change the second argument
  7755. of \code{interp-tests} and \code{compiler-tests} to
  7756. \code{type-check-Lif}, which causes the type checker to run prior to
  7757. the compiler passes. Temporarily change the \code{passes} to an
  7758. empty list and run the script, thereby checking that the new test
  7759. programs either type check or do not, as intended.}
  7760. %
  7761. Run the test script to check that these test programs type check as
  7762. expected.
  7763. \end{exercise}
  7764. \clearpage
  7765. \section{The \LangCIf{} Intermediate Language}
  7766. \label{sec:Cif}
  7767. {\if\edition\racketEd
  7768. %
  7769. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7770. comparison operators to the \Exp{} nonterminal and the literals
  7771. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7772. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7773. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7774. comparison operation and the branches are \code{goto} statements,
  7775. making it straightforward to compile \code{if} statements to x86. The
  7776. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7777. expressions. A \code{goto} statement transfers control to the $\Tail$
  7778. expression corresponding to its label.
  7779. %
  7780. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7781. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7782. defines its abstract syntax.
  7783. %
  7784. \fi}
  7785. %
  7786. {\if\edition\pythonEd\pythonColor
  7787. %
  7788. The output of \key{explicate\_control} is a language similar to the
  7789. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7790. \code{goto} statements, so we name it \LangCIf{}.
  7791. %
  7792. The \LangCIf{} language supports the same operators as \LangIf{} but
  7793. the arguments of operators are restricted to atomic expressions. The
  7794. \LangCIf{} language does not include \code{if} expressions, but it does
  7795. include a restricted form of \code{if} statement. The condition must be
  7796. a comparison, and the two branches may contain only \code{goto}
  7797. statements. These restrictions make it easier to translate \code{if}
  7798. statements to x86. The \LangCIf{} language also adds a \code{return}
  7799. statement to finish the program with a specified value.
  7800. %
  7801. The \key{CProgram} construct contains a dictionary mapping labels to
  7802. lists of statements that end with a \emph{tail} statement, which is
  7803. either a \code{return} statement, a \code{goto}, or an
  7804. \code{if} statement.
  7805. %
  7806. A \code{goto} transfers control to the sequence of statements
  7807. associated with its label.
  7808. %
  7809. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7810. and figure~\ref{fig:c1-syntax} shows its
  7811. abstract syntax.
  7812. %
  7813. \fi}
  7814. %
  7815. \newcommand{\CifGrammarRacket}{
  7816. \begin{array}{lcl}
  7817. \Atm &::=& \itm{bool} \\
  7818. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7819. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7820. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7821. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7822. \end{array}
  7823. }
  7824. \newcommand{\CifASTRacket}{
  7825. \begin{array}{lcl}
  7826. \Atm &::=& \BOOL{\itm{bool}} \\
  7827. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7828. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7829. \Tail &::= & \GOTO{\itm{label}} \\
  7830. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7831. \end{array}
  7832. }
  7833. \newcommand{\CifGrammarPython}{
  7834. \begin{array}{lcl}
  7835. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7836. \Exp &::= & \Atm \MID \CREAD{}
  7837. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7838. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7839. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7840. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7841. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7842. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7843. \end{array}
  7844. }
  7845. \newcommand{\CifASTPython}{
  7846. \begin{array}{lcl}
  7847. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7848. \Exp &::= & \Atm \MID \READ{} \\
  7849. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7850. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7851. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7852. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7853. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7854. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7855. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7856. \end{array}
  7857. }
  7858. \begin{figure}[tbp]
  7859. \begin{tcolorbox}[colback=white]
  7860. \small
  7861. {\if\edition\racketEd
  7862. \[
  7863. \begin{array}{l}
  7864. \gray{\CvarGrammarRacket} \\ \hline
  7865. \CifGrammarRacket \\
  7866. \begin{array}{lcl}
  7867. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7868. \end{array}
  7869. \end{array}
  7870. \]
  7871. \fi}
  7872. {\if\edition\pythonEd\pythonColor
  7873. \[
  7874. \begin{array}{l}
  7875. \CifGrammarPython \\
  7876. \begin{array}{lcl}
  7877. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7878. \end{array}
  7879. \end{array}
  7880. \]
  7881. \fi}
  7882. \end{tcolorbox}
  7883. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7884. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7885. \label{fig:c1-concrete-syntax}
  7886. \end{figure}
  7887. \begin{figure}[tp]
  7888. \begin{tcolorbox}[colback=white]
  7889. \small
  7890. {\if\edition\racketEd
  7891. \[
  7892. \begin{array}{l}
  7893. \gray{\CvarASTRacket} \\ \hline
  7894. \CifASTRacket \\
  7895. \begin{array}{lcl}
  7896. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7897. \end{array}
  7898. \end{array}
  7899. \]
  7900. \fi}
  7901. {\if\edition\pythonEd\pythonColor
  7902. \[
  7903. \begin{array}{l}
  7904. \CifASTPython \\
  7905. \begin{array}{lcl}
  7906. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7907. \end{array}
  7908. \end{array}
  7909. \]
  7910. \fi}
  7911. \end{tcolorbox}
  7912. \racket{
  7913. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7914. }
  7915. \index{subject}{Goto@\texttt{Goto}}
  7916. \index{subject}{Return@\texttt{Return}}
  7917. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7918. (figure~\ref{fig:c0-syntax})}.}
  7919. \label{fig:c1-syntax}
  7920. \end{figure}
  7921. \section{The \LangXIf{} Language}
  7922. \label{sec:x86-if}
  7923. \index{subject}{x86}
  7924. To implement Booleans, the new logical operations, the
  7925. comparison operations, and the \key{if} expression\python{ and
  7926. statement}, we delve further into the x86
  7927. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7928. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7929. subset of x86, which includes instructions for logical operations,
  7930. comparisons, and \racket{conditional} jumps.
  7931. %
  7932. \python{The abstract syntax for an \LangXIf{} program contains a
  7933. dictionary mapping labels to sequences of instructions, each of
  7934. which we refer to as a \emph{basic block}\index{subject}{basic
  7935. block}.}
  7936. As x86 does not provide direct support for Booleans, we take the usual
  7937. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7938. \code{False} as $0$.
  7939. Furthermore, x86 does not provide an instruction that directly
  7940. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7941. However, the \code{xorq} instruction can be used to encode \code{not}.
  7942. The \key{xorq} instruction takes two arguments, performs a pairwise
  7943. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7944. and writes the results into its second argument. Recall the following
  7945. truth table for exclusive-or:
  7946. \begin{center}
  7947. \begin{tabular}{l|cc}
  7948. & 0 & 1 \\ \hline
  7949. 0 & 0 & 1 \\
  7950. 1 & 1 & 0
  7951. \end{tabular}
  7952. \end{center}
  7953. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7954. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7955. for the bit $1$, the result is the opposite of the second bit. Thus,
  7956. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7957. the first argument, as follows, where $\Arg$ is the translation of
  7958. $\Atm$ to x86:
  7959. \[
  7960. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7961. \qquad\Rightarrow\qquad
  7962. \begin{array}{l}
  7963. \key{movq}~ \Arg\key{,} \Var\\
  7964. \key{xorq}~ \key{\$1,} \Var
  7965. \end{array}
  7966. \]
  7967. \newcommand{\GrammarXIf}{
  7968. \begin{array}{lcl}
  7969. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7970. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7971. \Arg &::=& \key{\%}\itm{bytereg}\\
  7972. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7973. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7974. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7975. \MID \key{set}cc~\Arg
  7976. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7977. &\MID& \key{j}cc~\itm{label} \\
  7978. \end{array}
  7979. }
  7980. \begin{figure}[tp]
  7981. \begin{tcolorbox}[colback=white]
  7982. \[
  7983. \begin{array}{l}
  7984. \gray{\GrammarXInt} \\ \hline
  7985. \GrammarXIf \\
  7986. \begin{array}{lcl}
  7987. \LangXIfM{} &::= & \key{.globl main} \\
  7988. & & \key{main:} \; \Instr\ldots
  7989. \end{array}
  7990. \end{array}
  7991. \]
  7992. \end{tcolorbox}
  7993. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7994. \label{fig:x86-1-concrete}
  7995. \end{figure}
  7996. \newcommand{\ASTXIfRacket}{
  7997. \begin{array}{lcl}
  7998. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7999. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8000. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8001. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8002. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8003. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8004. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8005. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8006. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8007. \end{array}
  8008. }
  8009. \newcommand{\ASTXIfPython}{
  8010. \begin{array}{lcl}
  8011. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8012. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8013. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8014. \MID \BYTEREG{\itm{bytereg}} \\
  8015. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8016. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8017. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8018. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8019. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8020. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8021. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8022. \end{array}
  8023. }
  8024. \begin{figure}[tp]
  8025. \begin{tcolorbox}[colback=white]
  8026. \small
  8027. {\if\edition\racketEd
  8028. \[\arraycolsep=3pt
  8029. \begin{array}{l}
  8030. \gray{\ASTXIntRacket} \\ \hline
  8031. \ASTXIfRacket \\
  8032. \begin{array}{lcl}
  8033. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8034. \end{array}
  8035. \end{array}
  8036. \]
  8037. \fi}
  8038. %
  8039. {\if\edition\pythonEd\pythonColor
  8040. \[
  8041. \begin{array}{l}
  8042. \gray{\ASTXIntPython} \\ \hline
  8043. \ASTXIfPython \\
  8044. \begin{array}{lcl}
  8045. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8046. \end{array}
  8047. \end{array}
  8048. \]
  8049. \fi}
  8050. \end{tcolorbox}
  8051. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8052. \label{fig:x86-1}
  8053. \end{figure}
  8054. Next we consider the x86 instructions that are relevant for compiling
  8055. the comparison operations. The \key{cmpq} instruction compares its two
  8056. arguments to determine whether one argument is less than, equal to, or
  8057. greater than the other argument. The \key{cmpq} instruction is unusual
  8058. regarding the order of its arguments and where the result is
  8059. placed. The argument order is backward: if you want to test whether
  8060. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8061. \key{cmpq} is placed in the special EFLAGS register. This register
  8062. cannot be accessed directly, but it can be queried by a number of
  8063. instructions, including the \key{set} instruction. The instruction
  8064. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8065. depending on whether the contents of the EFLAGS register matches the
  8066. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8067. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8068. The \key{set} instruction has a quirk in that its destination argument
  8069. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8070. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8071. register. Thankfully, the \key{movzbq} instruction can be used to
  8072. move from a single-byte register to a normal 64-bit register. The
  8073. abstract syntax for the \code{set} instruction differs from the
  8074. concrete syntax in that it separates the instruction name from the
  8075. condition code.
  8076. \python{The x86 instructions for jumping are relevant to the
  8077. compilation of \key{if} expressions.}
  8078. %
  8079. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8080. counter to the address of the instruction after the specified
  8081. label.}
  8082. %
  8083. \racket{The x86 instruction for conditional jump is relevant to the
  8084. compilation of \key{if} expressions.}
  8085. %
  8086. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8087. counter to point to the instruction after \itm{label}, depending on
  8088. whether the result in the EFLAGS register matches the condition code
  8089. \itm{cc}; otherwise, the jump instruction falls through to the next
  8090. instruction. Like the abstract syntax for \code{set}, the abstract
  8091. syntax for conditional jump separates the instruction name from the
  8092. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8093. corresponds to \code{jle foo}. Because the conditional jump instruction
  8094. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8095. a \key{cmpq} instruction to set the EFLAGS register.
  8096. \section{Shrink the \LangIf{} Language}
  8097. \label{sec:shrink-Lif}
  8098. The \code{shrink} pass translates some of the language features into
  8099. other features, thereby reducing the kinds of expressions in the
  8100. language. For example, the short-circuiting nature of the \code{and}
  8101. and \code{or} logical operators can be expressed using \code{if} as
  8102. follows.
  8103. \begin{align*}
  8104. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8105. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8106. \end{align*}
  8107. By performing these translations in the front end of the compiler,
  8108. subsequent passes of the compiler can be shorter.
  8109. On the other hand, translations sometimes reduce the efficiency of the
  8110. generated code by increasing the number of instructions. For example,
  8111. expressing subtraction in terms of addition and negation
  8112. \[
  8113. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8114. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8115. \]
  8116. produces code with two x86 instructions (\code{negq} and \code{addq})
  8117. instead of just one (\code{subq}). Thus, we do not recommend
  8118. translating subtraction into addition and negation.
  8119. \begin{exercise}\normalfont\normalsize
  8120. %
  8121. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8122. the language by translating them to \code{if} expressions in \LangIf{}.
  8123. %
  8124. Create four test programs that involve these operators.
  8125. %
  8126. {\if\edition\racketEd
  8127. In the \code{run-tests.rkt} script, add the following entry for
  8128. \code{shrink} to the list of passes (it should be the only pass at
  8129. this point).
  8130. \begin{lstlisting}
  8131. (list "shrink" shrink interp_Lif type-check-Lif)
  8132. \end{lstlisting}
  8133. This instructs \code{interp-tests} to run the interpreter
  8134. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8135. output of \code{shrink}.
  8136. \fi}
  8137. %
  8138. Run the script to test your compiler on all the test programs.
  8139. \end{exercise}
  8140. {\if\edition\racketEd
  8141. \section{Uniquify Variables}
  8142. \label{sec:uniquify-Lif}
  8143. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8144. \code{if} expressions.
  8145. \begin{exercise}\normalfont\normalsize
  8146. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8147. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8148. \begin{lstlisting}
  8149. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8150. \end{lstlisting}
  8151. Run the script to test your compiler.
  8152. \end{exercise}
  8153. \fi}
  8154. \section{Remove Complex Operands}
  8155. \label{sec:remove-complex-opera-Lif}
  8156. The output language of \code{remove\_complex\_operands} is
  8157. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8158. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8159. but the \code{if} expression is not. All three subexpressions of an
  8160. \code{if} are allowed to be complex expressions, but the operands of
  8161. the \code{not} operator and comparison operators must be atomic.
  8162. %
  8163. \python{We add a new language form, the \code{Begin} expression, to aid
  8164. in the translation of \code{if} expressions. When we recursively
  8165. process the two branches of the \code{if}, we generate temporary
  8166. variables and their initializing expressions. However, these
  8167. expressions may contain side effects and should be executed only
  8168. when the condition of the \code{if} is true (for the ``then''
  8169. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8170. a way to initialize the temporary variables within the two branches
  8171. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8172. form executes the statements $ss$ and then returns the result of
  8173. expression $e$.}
  8174. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8175. the new features in \LangIf{}. In recursively processing
  8176. subexpressions, recall that you should invoke \code{rco\_atom} when
  8177. the output needs to be an \Atm{} (as specified in the grammar for
  8178. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8179. \Exp{}. Regarding \code{if}, it is particularly important
  8180. \emph{not} to replace its condition with a temporary variable, because
  8181. that would interfere with the generation of high-quality output in the
  8182. upcoming \code{explicate\_control} pass.
  8183. \newcommand{\LifMonadASTRacket}{
  8184. \begin{array}{rcl}
  8185. \Atm &::=& \BOOL{\itm{bool}}\\
  8186. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8187. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8188. \MID \IF{\Exp}{\Exp}{\Exp}
  8189. \end{array}
  8190. }
  8191. \newcommand{\LifMonadASTPython}{
  8192. \begin{array}{rcl}
  8193. \Atm &::=& \BOOL{\itm{bool}}\\
  8194. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8195. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8196. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8197. \end{array}
  8198. }
  8199. \begin{figure}[tp]
  8200. \centering
  8201. \begin{tcolorbox}[colback=white]
  8202. {\if\edition\racketEd
  8203. \[
  8204. \begin{array}{l}
  8205. \gray{\LvarMonadASTRacket} \\ \hline
  8206. \LifMonadASTRacket \\
  8207. \begin{array}{rcl}
  8208. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8209. \end{array}
  8210. \end{array}
  8211. \]
  8212. \fi}
  8213. {\if\edition\pythonEd\pythonColor
  8214. \[
  8215. \begin{array}{l}
  8216. \gray{\LvarMonadASTPython} \\ \hline
  8217. \LifMonadASTPython \\
  8218. \begin{array}{rcl}
  8219. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8220. \end{array}
  8221. \end{array}
  8222. \]
  8223. \fi}
  8224. \end{tcolorbox}
  8225. \python{\index{subject}{Begin@\texttt{Begin}}}
  8226. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8227. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8228. \label{fig:Lif-anf-syntax}
  8229. \end{figure}
  8230. \begin{exercise}\normalfont\normalsize
  8231. %
  8232. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8233. and \code{rco\_exp} functions.
  8234. %
  8235. Create three new \LangIf{} programs that exercise the interesting
  8236. code in this pass.
  8237. %
  8238. {\if\edition\racketEd
  8239. In the \code{run-tests.rkt} script, add the following entry to the
  8240. list of \code{passes} and then run the script to test your compiler.
  8241. \begin{lstlisting}
  8242. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8243. \end{lstlisting}
  8244. \fi}
  8245. \end{exercise}
  8246. \section{Explicate Control}
  8247. \label{sec:explicate-control-Lif}
  8248. \racket{Recall that the purpose of \code{explicate\_control} is to
  8249. make the order of evaluation explicit in the syntax of the program.
  8250. With the addition of \key{if}, this becomes more interesting.}
  8251. %
  8252. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8253. %
  8254. The main challenge to overcome is that the condition of an \key{if}
  8255. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8256. condition must be a comparison.
  8257. As a motivating example, consider the following program that has an
  8258. \key{if} expression nested in the condition of another \key{if}:%
  8259. \python{\footnote{Programmers rarely write nested \code{if}
  8260. expressions, but they do write nested expressions involving
  8261. logical \code{and}, which, as we have seen, translates to
  8262. \code{if}.}}
  8263. % cond_test_41.rkt, if_lt_eq.py
  8264. \begin{center}
  8265. \begin{minipage}{0.96\textwidth}
  8266. {\if\edition\racketEd
  8267. \begin{lstlisting}
  8268. (let ([x (read)])
  8269. (let ([y (read)])
  8270. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8271. (+ y 2)
  8272. (+ y 10))))
  8273. \end{lstlisting}
  8274. \fi}
  8275. {\if\edition\pythonEd\pythonColor
  8276. \begin{lstlisting}
  8277. x = input_int()
  8278. y = input_int()
  8279. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8280. \end{lstlisting}
  8281. \fi}
  8282. \end{minipage}
  8283. \end{center}
  8284. %
  8285. The naive way to compile \key{if} and the comparison operations would
  8286. be to handle each of them in isolation, regardless of their context.
  8287. Each comparison would be translated into a \key{cmpq} instruction
  8288. followed by several instructions to move the result from the EFLAGS
  8289. register into a general purpose register or stack location. Each
  8290. \key{if} would be translated into a \key{cmpq} instruction followed by
  8291. a conditional jump. The generated code for the inner \key{if} in this
  8292. example would be as follows:
  8293. \begin{center}
  8294. \begin{minipage}{0.96\textwidth}
  8295. \begin{lstlisting}
  8296. cmpq $1, x
  8297. setl %al
  8298. movzbq %al, tmp
  8299. cmpq $1, tmp
  8300. je then_branch_1
  8301. jmp else_branch_1
  8302. \end{lstlisting}
  8303. \end{minipage}
  8304. \end{center}
  8305. Notice that the three instructions starting with \code{setl} are
  8306. redundant; the conditional jump could come immediately after the first
  8307. \code{cmpq}.
  8308. Our goal is to compile \key{if} expressions so that the relevant
  8309. comparison instruction appears directly before the conditional jump.
  8310. For example, we want to generate the following code for the inner
  8311. \code{if}:
  8312. \begin{center}
  8313. \begin{minipage}{0.96\textwidth}
  8314. \begin{lstlisting}
  8315. cmpq $1, x
  8316. jl then_branch_1
  8317. jmp else_branch_1
  8318. \end{lstlisting}
  8319. \end{minipage}
  8320. \end{center}
  8321. One way to achieve this goal is to reorganize the code at the level of
  8322. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8323. the following code:
  8324. \begin{center}
  8325. \begin{minipage}{0.96\textwidth}
  8326. {\if\edition\racketEd
  8327. \begin{lstlisting}
  8328. (let ([x (read)])
  8329. (let ([y (read)])
  8330. (if (< x 1)
  8331. (if (eq? x 0)
  8332. (+ y 2)
  8333. (+ y 10))
  8334. (if (eq? x 2)
  8335. (+ y 2)
  8336. (+ y 10)))))
  8337. \end{lstlisting}
  8338. \fi}
  8339. {\if\edition\pythonEd\pythonColor
  8340. \begin{lstlisting}
  8341. x = input_int()
  8342. y = input_int()
  8343. print(((y + 2) if x == 0 else (y + 10)) \
  8344. if (x < 1) \
  8345. else ((y + 2) if (x == 2) else (y + 10)))
  8346. \end{lstlisting}
  8347. \fi}
  8348. \end{minipage}
  8349. \end{center}
  8350. Unfortunately, this approach duplicates the two branches from the
  8351. outer \code{if}, and a compiler must never duplicate code! After all,
  8352. the two branches could be very large expressions.
  8353. How can we apply this transformation without duplicating code? In
  8354. other words, how can two different parts of a program refer to one
  8355. piece of code?
  8356. %
  8357. The answer is that we must move away from abstract syntax \emph{trees}
  8358. and instead use \emph{graphs}.
  8359. %
  8360. At the level of x86 assembly, this is straightforward because we can
  8361. label the code for each branch and insert jumps in all the places that
  8362. need to execute the branch. In this way, jump instructions are edges
  8363. in the graph and the basic blocks are the nodes.
  8364. %
  8365. Likewise, our language \LangCIf{} provides the ability to label a
  8366. sequence of statements and to jump to a label via \code{goto}.
  8367. As a preview of what \code{explicate\_control} will do,
  8368. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8369. \code{explicate\_control} on this example. Note how the condition of
  8370. every \code{if} is a comparison operation and that we have not
  8371. duplicated any code but instead have used labels and \code{goto} to
  8372. enable sharing of code.
  8373. \begin{figure}[tbp]
  8374. \begin{tcolorbox}[colback=white]
  8375. {\if\edition\racketEd
  8376. \begin{tabular}{lll}
  8377. \begin{minipage}{0.4\textwidth}
  8378. % cond_test_41.rkt
  8379. \begin{lstlisting}
  8380. (let ([x (read)])
  8381. (let ([y (read)])
  8382. (if (if (< x 1)
  8383. (eq? x 0)
  8384. (eq? x 2))
  8385. (+ y 2)
  8386. (+ y 10))))
  8387. \end{lstlisting}
  8388. \end{minipage}
  8389. &
  8390. $\Rightarrow$
  8391. &
  8392. \begin{minipage}{0.55\textwidth}
  8393. \begin{lstlisting}
  8394. start:
  8395. x = (read);
  8396. y = (read);
  8397. if (< x 1)
  8398. goto block_4;
  8399. else
  8400. goto block_5;
  8401. block_4:
  8402. if (eq? x 0)
  8403. goto block_2;
  8404. else
  8405. goto block_3;
  8406. block_5:
  8407. if (eq? x 2)
  8408. goto block_2;
  8409. else
  8410. goto block_3;
  8411. block_2:
  8412. return (+ y 2);
  8413. block_3:
  8414. return (+ y 10);
  8415. \end{lstlisting}
  8416. \end{minipage}
  8417. \end{tabular}
  8418. \fi}
  8419. {\if\edition\pythonEd\pythonColor
  8420. \begin{tabular}{lll}
  8421. \begin{minipage}{0.4\textwidth}
  8422. % cond_test_41.rkt
  8423. \begin{lstlisting}
  8424. x = input_int()
  8425. y = input_int()
  8426. print(y + 2 \
  8427. if (x == 0 \
  8428. if x < 1 \
  8429. else x == 2) \
  8430. else y + 10)
  8431. \end{lstlisting}
  8432. \end{minipage}
  8433. &
  8434. $\Rightarrow$
  8435. &
  8436. \begin{minipage}{0.55\textwidth}
  8437. \begin{lstlisting}
  8438. start:
  8439. x = input_int()
  8440. y = input_int()
  8441. if x < 1:
  8442. goto block_8
  8443. else:
  8444. goto block_9
  8445. block_8:
  8446. if x == 0:
  8447. goto block_4
  8448. else:
  8449. goto block_5
  8450. block_9:
  8451. if x == 2:
  8452. goto block_6
  8453. else:
  8454. goto block_7
  8455. block_4:
  8456. goto block_2
  8457. block_5:
  8458. goto block_3
  8459. block_6:
  8460. goto block_2
  8461. block_7:
  8462. goto block_3
  8463. block_2:
  8464. tmp_0 = y + 2
  8465. goto block_1
  8466. block_3:
  8467. tmp_0 = y + 10
  8468. goto block_1
  8469. block_1:
  8470. print(tmp_0)
  8471. return 0
  8472. \end{lstlisting}
  8473. \end{minipage}
  8474. \end{tabular}
  8475. \fi}
  8476. \end{tcolorbox}
  8477. \caption{Translation from \LangIf{} to \LangCIf{}
  8478. via the \code{explicate\_control}.}
  8479. \label{fig:explicate-control-s1-38}
  8480. \end{figure}
  8481. {\if\edition\racketEd
  8482. %
  8483. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8484. \code{explicate\_control} for \LangVar{} using two recursive
  8485. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8486. former function translates expressions in tail position, whereas the
  8487. latter function translates expressions on the right-hand side of a
  8488. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8489. have a new kind of position to deal with: the predicate position of
  8490. the \key{if}. We need another function, \code{explicate\_pred}, that
  8491. decides how to compile an \key{if} by analyzing its condition. So,
  8492. \code{explicate\_pred} takes an \LangIf{} expression and two
  8493. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8494. and outputs a tail. In the following paragraphs we discuss specific
  8495. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8496. \code{explicate\_pred} functions.
  8497. %
  8498. \fi}
  8499. %
  8500. {\if\edition\pythonEd\pythonColor
  8501. %
  8502. We recommend implementing \code{explicate\_control} using the
  8503. following four auxiliary functions.
  8504. \begin{description}
  8505. \item[\code{explicate\_effect}] generates code for expressions as
  8506. statements, so their result is ignored and only their side effects
  8507. matter.
  8508. \item[\code{explicate\_assign}] generates code for expressions
  8509. on the right-hand side of an assignment.
  8510. \item[\code{explicate\_pred}] generates code for an \code{if}
  8511. expression or statement by analyzing the condition expression.
  8512. \item[\code{explicate\_stmt}] generates code for statements.
  8513. \end{description}
  8514. These four functions should build the dictionary of basic blocks. The
  8515. following auxiliary function can be used to create a new basic block
  8516. from a list of statements. It returns a \code{goto} statement that
  8517. jumps to the new basic block.
  8518. \begin{center}
  8519. \begin{minipage}{\textwidth}
  8520. \begin{lstlisting}
  8521. def create_block(stmts, basic_blocks):
  8522. label = label_name(generate_name('block'))
  8523. basic_blocks[label] = stmts
  8524. return [Goto(label)]
  8525. \end{lstlisting}
  8526. \end{minipage}
  8527. \end{center}
  8528. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8529. \code{explicate\_control} pass.
  8530. The \code{explicate\_effect} function has three parameters: (1) the
  8531. expression to be compiled; (2) the already-compiled code for this
  8532. expression's \emph{continuation}, that is, the list of statements that
  8533. should execute after this expression; and (3) the dictionary of
  8534. generated basic blocks. The \code{explicate\_effect} function returns
  8535. a list of \LangCIf{} statements and it may add to the dictionary of
  8536. basic blocks.
  8537. %
  8538. Let's consider a few of the cases for the expression to be compiled.
  8539. If the expression to be compiled is a constant, then it can be
  8540. discarded because it has no side effects. If it's a \CREAD{}, then it
  8541. has a side effect and should be preserved. So the expression should be
  8542. translated into a statement using the \code{Expr} AST class. If the
  8543. expression to be compiled is an \code{if} expression, we translate the
  8544. two branches using \code{explicate\_effect} and then translate the
  8545. condition expression using \code{explicate\_pred}, which generates
  8546. code for the entire \code{if}.
  8547. The \code{explicate\_assign} function has four parameters: (1) the
  8548. right-hand side of the assignment, (2) the left-hand side of the
  8549. assignment (the variable), (3) the continuation, and (4) the dictionary
  8550. of basic blocks. The \code{explicate\_assign} function returns a list
  8551. of \LangCIf{} statements, and it may add to the dictionary of basic
  8552. blocks.
  8553. When the right-hand side is an \code{if} expression, there is some
  8554. work to do. In particular, the two branches should be translated using
  8555. \code{explicate\_assign} and the condition expression should be
  8556. translated using \code{explicate\_pred}. Otherwise we can simply
  8557. generate an assignment statement, with the given left and right-hand
  8558. sides, concatenated with its continuation.
  8559. \begin{figure}[tbp]
  8560. \begin{tcolorbox}[colback=white]
  8561. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8562. def explicate_effect(e, cont, basic_blocks):
  8563. match e:
  8564. case IfExp(test, body, orelse):
  8565. ...
  8566. case Call(func, args):
  8567. ...
  8568. case Begin(body, result):
  8569. ...
  8570. case _:
  8571. ...
  8572. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8573. match rhs:
  8574. case IfExp(test, body, orelse):
  8575. ...
  8576. case Begin(body, result):
  8577. ...
  8578. case _:
  8579. return [Assign([lhs], rhs)] + cont
  8580. def explicate_pred(cnd, thn, els, basic_blocks):
  8581. match cnd:
  8582. case Compare(left, [op], [right]):
  8583. goto_thn = create_block(thn, basic_blocks)
  8584. goto_els = create_block(els, basic_blocks)
  8585. return [If(cnd, goto_thn, goto_els)]
  8586. case Constant(True):
  8587. return thn;
  8588. case Constant(False):
  8589. return els;
  8590. case UnaryOp(Not(), operand):
  8591. ...
  8592. case IfExp(test, body, orelse):
  8593. ...
  8594. case Begin(body, result):
  8595. ...
  8596. case _:
  8597. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8598. create_block(els, basic_blocks),
  8599. create_block(thn, basic_blocks))]
  8600. def explicate_stmt(s, cont, basic_blocks):
  8601. match s:
  8602. case Assign([lhs], rhs):
  8603. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8604. case Expr(value):
  8605. return explicate_effect(value, cont, basic_blocks)
  8606. case If(test, body, orelse):
  8607. ...
  8608. def explicate_control(p):
  8609. match p:
  8610. case Module(body):
  8611. new_body = [Return(Constant(0))]
  8612. basic_blocks = {}
  8613. for s in reversed(body):
  8614. new_body = explicate_stmt(s, new_body, basic_blocks)
  8615. basic_blocks[label_name('start')] = new_body
  8616. return CProgram(basic_blocks)
  8617. \end{lstlisting}
  8618. \end{tcolorbox}
  8619. \caption{Skeleton for the \code{explicate\_control} pass.}
  8620. \label{fig:explicate-control-Lif}
  8621. \end{figure}
  8622. \fi}
  8623. {\if\edition\racketEd
  8624. \subsection{Explicate Tail and Assign}
  8625. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8626. additional cases for Boolean constants and \key{if}. The cases for
  8627. \code{if} should recursively compile the two branches using either
  8628. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8629. cases should then invoke \code{explicate\_pred} on the condition
  8630. expression, passing in the generated code for the two branches. For
  8631. example, consider the following program with an \code{if} in tail
  8632. position.
  8633. % cond_test_6.rkt
  8634. \begin{lstlisting}
  8635. (let ([x (read)])
  8636. (if (eq? x 0) 42 777))
  8637. \end{lstlisting}
  8638. The two branches are recursively compiled to return statements. We
  8639. then delegate to \code{explicate\_pred}, passing the condition
  8640. \code{(eq? x 0)} and the two return statements. We return to this
  8641. example shortly when we discuss \code{explicate\_pred}.
  8642. Next let us consider a program with an \code{if} on the right-hand
  8643. side of a \code{let}.
  8644. \begin{lstlisting}
  8645. (let ([y (read)])
  8646. (let ([x (if (eq? y 0) 40 777)])
  8647. (+ x 2)))
  8648. \end{lstlisting}
  8649. Note that the body of the inner \code{let} will have already been
  8650. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8651. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8652. to recursively process both branches of the \code{if}, and we do not
  8653. want to duplicate code, so we generate the following block using an
  8654. auxiliary function named \code{create\_block}, discussed in the next
  8655. section.
  8656. \begin{lstlisting}
  8657. block_6:
  8658. return (+ x 2)
  8659. \end{lstlisting}
  8660. We then use \code{goto block\_6;} as the \code{cont} argument for
  8661. compiling the branches. So the two branches compile to
  8662. \begin{center}
  8663. \begin{minipage}{0.2\textwidth}
  8664. \begin{lstlisting}
  8665. x = 40;
  8666. goto block_6;
  8667. \end{lstlisting}
  8668. \end{minipage}
  8669. \hspace{0.5in} and \hspace{0.5in}
  8670. \begin{minipage}{0.2\textwidth}
  8671. \begin{lstlisting}
  8672. x = 777;
  8673. goto block_6;
  8674. \end{lstlisting}
  8675. \end{minipage}
  8676. \end{center}
  8677. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8678. \code{(eq? y 0)} and the previously presented code for the branches.
  8679. \subsection{Create Block}
  8680. We recommend implementing the \code{create\_block} auxiliary function
  8681. as follows, using a global variable \code{basic-blocks} to store a
  8682. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8683. that \code{create\_block} generates a new label and then associates
  8684. the given \code{tail} with the new label in the \code{basic-blocks}
  8685. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8686. new label. However, if the given \code{tail} is already a \code{Goto},
  8687. then there is no need to generate a new label and entry in
  8688. \code{basic-blocks}; we can simply return that \code{Goto}.
  8689. %
  8690. \begin{lstlisting}
  8691. (define (create_block tail)
  8692. (match tail
  8693. [(Goto label) (Goto label)]
  8694. [else
  8695. (let ([label (gensym 'block)])
  8696. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8697. (Goto label))]))
  8698. \end{lstlisting}
  8699. \fi}
  8700. {\if\edition\racketEd
  8701. \subsection{Explicate Predicate}
  8702. The skeleton for the \code{explicate\_pred} function is given in
  8703. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8704. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8705. the code generated by explicate for the \emph{then} branch; and (3)
  8706. \code{els}, the code generated by explicate for the \emph{else}
  8707. branch. The \code{explicate\_pred} function should match on
  8708. \code{cnd} with a case for every kind of expression that can have type
  8709. \BOOLTY{}.
  8710. \begin{figure}[tbp]
  8711. \begin{tcolorbox}[colback=white]
  8712. \begin{lstlisting}
  8713. (define (explicate_pred cnd thn els)
  8714. (match cnd
  8715. [(Var x) ___]
  8716. [(Let x rhs body) ___]
  8717. [(Prim 'not (list e)) ___]
  8718. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8719. (IfStmt (Prim op es) (create_block thn)
  8720. (create_block els))]
  8721. [(Bool b) (if b thn els)]
  8722. [(If cnd^ thn^ els^) ___]
  8723. [else (error "explicate_pred unhandled case" cnd)]))
  8724. \end{lstlisting}
  8725. \end{tcolorbox}
  8726. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8727. \label{fig:explicate-pred}
  8728. \end{figure}
  8729. \fi}
  8730. %
  8731. {\if\edition\pythonEd\pythonColor
  8732. The \code{explicate\_pred} function has four parameters: 1) the
  8733. condition expression, 2) the generated statements for the ``then''
  8734. branch, 3) the generated statements for the ``else'' branch, and 4)
  8735. the dictionary of basic blocks. The \code{explicate\_pred} function
  8736. returns a list of \LangCIf{} statements and it may add to the
  8737. dictionary of basic blocks.
  8738. \fi}
  8739. Consider the case for comparison operators. We translate the
  8740. comparison to an \code{if} statement whose branches are \code{goto}
  8741. statements created by applying \code{create\_block} to the code
  8742. generated for the \code{thn} and \code{els} branches. Let us
  8743. illustrate this translation by returning to the program with an
  8744. \code{if} expression in tail position, shown next. We invoke
  8745. \code{explicate\_pred} on its condition
  8746. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8747. %
  8748. {\if\edition\racketEd
  8749. \begin{lstlisting}
  8750. (let ([x (read)])
  8751. (if (eq? x 0) 42 777))
  8752. \end{lstlisting}
  8753. \fi}
  8754. %
  8755. {\if\edition\pythonEd\pythonColor
  8756. \begin{lstlisting}
  8757. x = input_int()
  8758. 42 if x == 0 else 777
  8759. \end{lstlisting}
  8760. \fi}
  8761. %
  8762. \noindent The two branches \code{42} and \code{777} were already
  8763. compiled to \code{return} statements, from which we now create the
  8764. following blocks:
  8765. %
  8766. \begin{center}
  8767. \begin{minipage}{\textwidth}
  8768. \begin{lstlisting}
  8769. block_1:
  8770. return 42;
  8771. block_2:
  8772. return 777;
  8773. \end{lstlisting}
  8774. \end{minipage}
  8775. \end{center}
  8776. %
  8777. After that, \code{explicate\_pred} compiles the comparison
  8778. \racket{\code{(eq? x 0)}}
  8779. \python{\code{x == 0}}
  8780. to the following \code{if} statement:
  8781. %
  8782. {\if\edition\racketEd
  8783. \begin{center}
  8784. \begin{minipage}{\textwidth}
  8785. \begin{lstlisting}
  8786. if (eq? x 0)
  8787. goto block_1;
  8788. else
  8789. goto block_2;
  8790. \end{lstlisting}
  8791. \end{minipage}
  8792. \end{center}
  8793. \fi}
  8794. {\if\edition\pythonEd\pythonColor
  8795. \begin{center}
  8796. \begin{minipage}{\textwidth}
  8797. \begin{lstlisting}
  8798. if x == 0:
  8799. goto block_1;
  8800. else
  8801. goto block_2;
  8802. \end{lstlisting}
  8803. \end{minipage}
  8804. \end{center}
  8805. \fi}
  8806. Next consider the case for Boolean constants. We perform a kind of
  8807. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8808. either the \code{thn} or \code{els} branch, depending on whether the
  8809. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8810. following program:
  8811. {\if\edition\racketEd
  8812. \begin{lstlisting}
  8813. (if #t 42 777)
  8814. \end{lstlisting}
  8815. \fi}
  8816. {\if\edition\pythonEd\pythonColor
  8817. \begin{lstlisting}
  8818. 42 if True else 777
  8819. \end{lstlisting}
  8820. \fi}
  8821. %
  8822. \noindent Again, the two branches \code{42} and \code{777} were
  8823. compiled to \code{return} statements, so \code{explicate\_pred}
  8824. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8825. code for the \emph{then} branch.
  8826. \begin{lstlisting}
  8827. return 42;
  8828. \end{lstlisting}
  8829. This case demonstrates that we sometimes discard the \code{thn} or
  8830. \code{els} blocks that are input to \code{explicate\_pred}.
  8831. The case for \key{if} expressions in \code{explicate\_pred} is
  8832. particularly illuminating because it deals with the challenges
  8833. discussed previously regarding nested \key{if} expressions
  8834. (figure~\ref{fig:explicate-control-s1-38}). The
  8835. \racket{\lstinline{thn^}}\python{\code{body}} and
  8836. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8837. \key{if} inherit their context from the current one, that is,
  8838. predicate context. So, you should recursively apply
  8839. \code{explicate\_pred} to the
  8840. \racket{\lstinline{thn^}}\python{\code{body}} and
  8841. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8842. those recursive calls, pass \code{thn} and \code{els} as the extra
  8843. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8844. inside each recursive call. As discussed previously, to avoid
  8845. duplicating code, we need to add them to the dictionary of basic
  8846. blocks so that we can instead refer to them by name and execute them
  8847. with a \key{goto}.
  8848. {\if\edition\pythonEd\pythonColor
  8849. %
  8850. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8851. three parameters: (1) the statement to be compiled, (2) the code for its
  8852. continuation, and (3) the dictionary of basic blocks. The
  8853. \code{explicate\_stmt} returns a list of statements, and it may add to
  8854. the dictionary of basic blocks. The cases for assignment and an
  8855. expression-statement are given in full in the skeleton code: they
  8856. simply dispatch to \code{explicate\_assign} and
  8857. \code{explicate\_effect}, respectively. The case for \code{if}
  8858. statements is not given; it is similar to the case for \code{if}
  8859. expressions.
  8860. The \code{explicate\_control} function itself is given in
  8861. figure~\ref{fig:explicate-control-Lif}. It applies
  8862. \code{explicate\_stmt} to each statement in the program, from back to
  8863. front. Thus, the result so far, stored in \code{new\_body}, can be
  8864. used as the continuation parameter in the next call to
  8865. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8866. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8867. the dictionary of basic blocks, labeling it the ``start'' block.
  8868. %
  8869. \fi}
  8870. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8871. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8872. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8873. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8874. %% results from the two recursive calls. We complete the case for
  8875. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8876. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8877. %% the result $B_5$.
  8878. %% \[
  8879. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8880. %% \quad\Rightarrow\quad
  8881. %% B_5
  8882. %% \]
  8883. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8884. %% inherit the current context, so they are in tail position. Thus, the
  8885. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8886. %% \code{explicate\_tail}.
  8887. %% %
  8888. %% We need to pass $B_0$ as the accumulator argument for both of these
  8889. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8890. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8891. %% to the control-flow graph and obtain a promised goto $G_0$.
  8892. %% %
  8893. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8894. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8895. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8896. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8897. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8898. %% \[
  8899. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8900. %% \]
  8901. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8902. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8903. %% should not be confused with the labels for the blocks that appear in
  8904. %% the generated code. We initially construct unlabeled blocks; we only
  8905. %% attach labels to blocks when we add them to the control-flow graph, as
  8906. %% we see in the next case.
  8907. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8908. %% function. The context of the \key{if} is an assignment to some
  8909. %% variable $x$ and then the control continues to some promised block
  8910. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8911. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8912. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8913. %% branches of the \key{if} inherit the current context, so they are in
  8914. %% assignment positions. Let $B_2$ be the result of applying
  8915. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8916. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8917. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8918. %% the result of applying \code{explicate\_pred} to the predicate
  8919. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8920. %% translates to the promise $B_4$.
  8921. %% \[
  8922. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8923. %% \]
  8924. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8925. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8926. \code{remove\_complex\_operands} pass and then the
  8927. \code{explicate\_control} pass on the example program. We walk through
  8928. the output program.
  8929. %
  8930. Following the order of evaluation in the output of
  8931. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8932. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8933. in the predicate of the inner \key{if}. In the output of
  8934. \code{explicate\_control}, in the
  8935. block labeled \code{start}, two assignment statements are followed by an
  8936. \code{if} statement that branches to \code{block\_4} or
  8937. \code{block\_5}. The blocks associated with those labels contain the
  8938. translations of the code
  8939. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8940. and
  8941. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8942. respectively. In particular, we start \code{block\_4} with the
  8943. comparison
  8944. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8945. and then branch to \code{block\_2} or \code{block\_3},
  8946. which correspond to the two branches of the outer \key{if}, that is,
  8947. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8948. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8949. %
  8950. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8951. %
  8952. \python{The \code{block\_1} corresponds to the \code{print} statement
  8953. at the end of the program.}
  8954. {\if\edition\racketEd
  8955. \subsection{Interactions between Explicate and Shrink}
  8956. The way in which the \code{shrink} pass transforms logical operations
  8957. such as \code{and} and \code{or} can impact the quality of code
  8958. generated by \code{explicate\_control}. For example, consider the
  8959. following program:
  8960. % cond_test_21.rkt, and_eq_input.py
  8961. \begin{lstlisting}
  8962. (if (and (eq? (read) 0) (eq? (read) 1))
  8963. 0
  8964. 42)
  8965. \end{lstlisting}
  8966. The \code{and} operation should transform into something that the
  8967. \code{explicate\_pred} function can analyze and descend through to
  8968. reach the underlying \code{eq?} conditions. Ideally, for this program
  8969. your \code{explicate\_control} pass should generate code similar to
  8970. the following:
  8971. \begin{center}
  8972. \begin{minipage}{\textwidth}
  8973. \begin{lstlisting}
  8974. start:
  8975. tmp1 = (read);
  8976. if (eq? tmp1 0) goto block40;
  8977. else goto block39;
  8978. block40:
  8979. tmp2 = (read);
  8980. if (eq? tmp2 1) goto block38;
  8981. else goto block39;
  8982. block38:
  8983. return 0;
  8984. block39:
  8985. return 42;
  8986. \end{lstlisting}
  8987. \end{minipage}
  8988. \end{center}
  8989. \fi}
  8990. \begin{exercise}\normalfont\normalsize
  8991. \racket{
  8992. Implement the pass \code{explicate\_control} by adding the cases for
  8993. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8994. \code{explicate\_assign} functions. Implement the auxiliary function
  8995. \code{explicate\_pred} for predicate contexts.}
  8996. \python{Implement \code{explicate\_control} pass with its
  8997. four auxiliary functions.}
  8998. %
  8999. Create test cases that exercise all the new cases in the code for
  9000. this pass.
  9001. %
  9002. {\if\edition\racketEd
  9003. Add the following entry to the list of \code{passes} in
  9004. \code{run-tests.rkt}:
  9005. \begin{lstlisting}
  9006. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9007. \end{lstlisting}
  9008. and then run \code{run-tests.rkt} to test your compiler.
  9009. \fi}
  9010. \end{exercise}
  9011. \section{Select Instructions}
  9012. \label{sec:select-Lif}
  9013. \index{subject}{select instructions}
  9014. The \code{select\_instructions} pass translates \LangCIf{} to
  9015. \LangXIfVar{}.
  9016. %
  9017. \racket{Recall that we implement this pass using three auxiliary
  9018. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9019. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9020. %
  9021. \racket{For $\Atm$, we have new cases for the Booleans.}
  9022. %
  9023. \python{We begin with the Boolean constants.}
  9024. As previously discussed, we encode them as integers.
  9025. \[
  9026. \TRUE{} \quad\Rightarrow\quad \key{1}
  9027. \qquad\qquad
  9028. \FALSE{} \quad\Rightarrow\quad \key{0}
  9029. \]
  9030. For translating statements, we discuss some of the cases. The
  9031. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9032. discussed at the beginning of this section. Given an assignment, if
  9033. the left-hand-side variable is the same as the argument of \code{not},
  9034. then just the \code{xorq} instruction suffices.
  9035. \[
  9036. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9037. \quad\Rightarrow\quad
  9038. \key{xorq}~\key{\$}1\key{,}~\Var
  9039. \]
  9040. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9041. semantics of x86. In the following translation, let $\Arg$ be the
  9042. result of translating $\Atm$ to x86.
  9043. \[
  9044. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9045. \quad\Rightarrow\quad
  9046. \begin{array}{l}
  9047. \key{movq}~\Arg\key{,}~\Var\\
  9048. \key{xorq}~\key{\$}1\key{,}~\Var
  9049. \end{array}
  9050. \]
  9051. Next consider the cases for equality comparisons. Translating this
  9052. operation to x86 is slightly involved due to the unusual nature of the
  9053. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9054. We recommend translating an assignment with an equality on the
  9055. right-hand side into a sequence of three instructions. \\
  9056. \begin{tabular}{lll}
  9057. \begin{minipage}{0.4\textwidth}
  9058. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9059. \end{minipage}
  9060. &
  9061. $\Rightarrow$
  9062. &
  9063. \begin{minipage}{0.4\textwidth}
  9064. \begin{lstlisting}
  9065. cmpq |$\Arg_2$|, |$\Arg_1$|
  9066. sete %al
  9067. movzbq %al, |$\Var$|
  9068. \end{lstlisting}
  9069. \end{minipage}
  9070. \end{tabular} \\
  9071. The translations for the other comparison operators are similar to
  9072. this but use different condition codes for the \code{set} instruction.
  9073. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9074. \key{goto} and \key{if} statements. Both are straightforward to
  9075. translate to x86.}
  9076. %
  9077. A \key{goto} statement becomes a jump instruction.
  9078. \[
  9079. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9080. \]
  9081. %
  9082. An \key{if} statement becomes a compare instruction followed by a
  9083. conditional jump (for the \emph{then} branch), and the fall-through is to
  9084. a regular jump (for the \emph{else} branch).\\
  9085. \begin{tabular}{lll}
  9086. \begin{minipage}{0.4\textwidth}
  9087. \begin{lstlisting}
  9088. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9089. goto |$\ell_1$||$\racket{\key{;}}$|
  9090. else|$\python{\key{:}}$|
  9091. goto |$\ell_2$||$\racket{\key{;}}$|
  9092. \end{lstlisting}
  9093. \end{minipage}
  9094. &
  9095. $\Rightarrow$
  9096. &
  9097. \begin{minipage}{0.4\textwidth}
  9098. \begin{lstlisting}
  9099. cmpq |$\Arg_2$|, |$\Arg_1$|
  9100. je |$\ell_1$|
  9101. jmp |$\ell_2$|
  9102. \end{lstlisting}
  9103. \end{minipage}
  9104. \end{tabular} \\
  9105. Again, the translations for the other comparison operators are similar to this
  9106. but use different condition codes for the conditional jump instruction.
  9107. \python{Regarding the \key{return} statement, we recommend treating it
  9108. as an assignment to the \key{rax} register followed by a jump to the
  9109. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9110. \begin{exercise}\normalfont\normalsize
  9111. Expand your \code{select\_instructions} pass to handle the new
  9112. features of the \LangCIf{} language.
  9113. %
  9114. {\if\edition\racketEd
  9115. Add the following entry to the list of \code{passes} in
  9116. \code{run-tests.rkt}
  9117. \begin{lstlisting}
  9118. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9119. \end{lstlisting}
  9120. \fi}
  9121. %
  9122. Run the script to test your compiler on all the test programs.
  9123. \end{exercise}
  9124. \section{Register Allocation}
  9125. \label{sec:register-allocation-Lif}
  9126. \index{subject}{register allocation}
  9127. The changes required for compiling \LangIf{} affect liveness analysis,
  9128. building the interference graph, and assigning homes, but the graph
  9129. coloring algorithm itself does not change.
  9130. \subsection{Liveness Analysis}
  9131. \label{sec:liveness-analysis-Lif}
  9132. \index{subject}{liveness analysis}
  9133. Recall that for \LangVar{} we implemented liveness analysis for a
  9134. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9135. the addition of \key{if} expressions to \LangIf{},
  9136. \code{explicate\_control} produces many basic blocks.
  9137. %% We recommend that you create a new auxiliary function named
  9138. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9139. %% control-flow graph.
  9140. The first question is, in what order should we process the basic blocks?
  9141. Recall that to perform liveness analysis on a basic block we need to
  9142. know the live-after set for the last instruction in the block. If a
  9143. basic block has no successors (i.e., contains no jumps to other
  9144. blocks), then it has an empty live-after set and we can immediately
  9145. apply liveness analysis to it. If a basic block has some successors,
  9146. then we need to complete liveness analysis on those blocks
  9147. first. These ordering constraints are the reverse of a
  9148. \emph{topological order}\index{subject}{topological order} on a graph
  9149. representation of the program. In particular, the \emph{control flow
  9150. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9151. of a program has a node for each basic block and an edge for each jump
  9152. from one block to another. It is straightforward to generate a CFG
  9153. from the dictionary of basic blocks. One then transposes the CFG and
  9154. applies the topological sort algorithm.
  9155. %
  9156. %
  9157. \racket{We recommend using the \code{tsort} and \code{transpose}
  9158. functions of the Racket \code{graph} package to accomplish this.}
  9159. %
  9160. \python{We provide implementations of \code{topological\_sort} and
  9161. \code{transpose} in the file \code{graph.py} of the support code.}
  9162. %
  9163. As an aside, a topological ordering is only guaranteed to exist if the
  9164. graph does not contain any cycles. This is the case for the
  9165. control-flow graphs that we generate from \LangIf{} programs.
  9166. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9167. and learn how to handle cycles in the control-flow graph.
  9168. \racket{You need to construct a directed graph to represent the
  9169. control-flow graph. Do not use the \code{directed-graph} of the
  9170. \code{graph} package because that allows at most one edge
  9171. between each pair of vertices, whereas a control-flow graph may have
  9172. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9173. file in the support code implements a graph representation that
  9174. allows multiple edges between a pair of vertices.}
  9175. {\if\edition\racketEd
  9176. The next question is how to analyze jump instructions. Recall that in
  9177. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9178. \code{label->live} that maps each label to the set of live locations
  9179. at the beginning of its block. We use \code{label->live} to determine
  9180. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9181. that we have many basic blocks, \code{label->live} needs to be updated
  9182. as we process the blocks. In particular, after performing liveness
  9183. analysis on a block, we take the live-before set of its first
  9184. instruction and associate that with the block's label in the
  9185. \code{label->live} alist.
  9186. \fi}
  9187. %
  9188. {\if\edition\pythonEd\pythonColor
  9189. %
  9190. The next question is how to analyze jump instructions. The locations
  9191. that are live before a \code{jmp} should be the locations in
  9192. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9193. maintaining a dictionary named \code{live\_before\_block} that maps each
  9194. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9195. block. After performing liveness analysis on each block, we take the
  9196. live-before set of its first instruction and associate that with the
  9197. block's label in the \code{live\_before\_block} dictionary.
  9198. %
  9199. \fi}
  9200. In \LangXIfVar{} we also have the conditional jump
  9201. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9202. this instruction is particularly interesting because during
  9203. compilation, we do not know which way a conditional jump will go. Thus
  9204. we do not know whether to use the live-before set for the block
  9205. associated with the $\itm{label}$ or the live-before set for the
  9206. following instruction. So we use both, by taking the union of the
  9207. live-before sets from the following instruction and from the mapping
  9208. for $\itm{label}$ in
  9209. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9210. The auxiliary functions for computing the variables in an
  9211. instruction's argument and for computing the variables read-from ($R$)
  9212. or written-to ($W$) by an instruction need to be updated to handle the
  9213. new kinds of arguments and instructions in \LangXIfVar{}.
  9214. \begin{exercise}\normalfont\normalsize
  9215. {\if\edition\racketEd
  9216. %
  9217. Update the \code{uncover\_live} pass to apply liveness analysis to
  9218. every basic block in the program.
  9219. %
  9220. Add the following entry to the list of \code{passes} in the
  9221. \code{run-tests.rkt} script:
  9222. \begin{lstlisting}
  9223. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9224. \end{lstlisting}
  9225. \fi}
  9226. {\if\edition\pythonEd\pythonColor
  9227. %
  9228. Update the \code{uncover\_live} function to perform liveness analysis,
  9229. in reverse topological order, on all the basic blocks in the
  9230. program.
  9231. %
  9232. \fi}
  9233. % Check that the live-after sets that you generate for
  9234. % example X matches the following... -Jeremy
  9235. \end{exercise}
  9236. \subsection{Build the Interference Graph}
  9237. \label{sec:build-interference-Lif}
  9238. Many of the new instructions in \LangXIfVar{} can be handled in the
  9239. same way as the instructions in \LangXVar{}.
  9240. % Thus, if your code was
  9241. % already quite general, it will not need to be changed to handle the
  9242. % new instructions. If your code is not general enough, we recommend that
  9243. % you change your code to be more general. For example, you can factor
  9244. % out the computing of the the read and write sets for each kind of
  9245. % instruction into auxiliary functions.
  9246. %
  9247. Some instructions, such as the \key{movzbq} instruction, require special care,
  9248. similar to the \key{movq} instruction. Refer to rule number 1 in
  9249. section~\ref{sec:build-interference}.
  9250. \begin{exercise}\normalfont\normalsize
  9251. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9252. {\if\edition\racketEd
  9253. Add the following entries to the list of \code{passes} in the
  9254. \code{run-tests.rkt} script:
  9255. \begin{lstlisting}
  9256. (list "build_interference" build_interference interp-pseudo-x86-1)
  9257. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9258. \end{lstlisting}
  9259. \fi}
  9260. % Check that the interference graph that you generate for
  9261. % example X matches the following graph G... -Jeremy
  9262. \end{exercise}
  9263. \section{Patch Instructions}
  9264. The new instructions \key{cmpq} and \key{movzbq} have some special
  9265. restrictions that need to be handled in the \code{patch\_instructions}
  9266. pass.
  9267. %
  9268. The second argument of the \key{cmpq} instruction must not be an
  9269. immediate value (such as an integer). So, if you are comparing two
  9270. immediates, we recommend inserting a \key{movq} instruction to put the
  9271. second argument in \key{rax}. On the other hand, if you implemented
  9272. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9273. update it for \LangIf{} and then this situation would not arise.
  9274. %
  9275. As usual, \key{cmpq} may have at most one memory reference.
  9276. %
  9277. The second argument of the \key{movzbq} must be a register.
  9278. \begin{exercise}\normalfont\normalsize
  9279. %
  9280. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9281. %
  9282. {\if\edition\racketEd
  9283. Add the following entry to the list of \code{passes} in
  9284. \code{run-tests.rkt}, and then run this script to test your compiler.
  9285. \begin{lstlisting}
  9286. (list "patch_instructions" patch_instructions interp-x86-1)
  9287. \end{lstlisting}
  9288. \fi}
  9289. \end{exercise}
  9290. {\if\edition\pythonEd\pythonColor
  9291. \section{Prelude and Conclusion}
  9292. \label{sec:prelude-conclusion-cond}
  9293. The generation of the \code{main} function with its prelude and
  9294. conclusion must change to accommodate how the program now consists of
  9295. one or more basic blocks. After the prelude in \code{main}, jump to
  9296. the \code{start} block. Place the conclusion in a basic block labeled
  9297. with \code{conclusion}.
  9298. \fi}
  9299. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9300. \LangIf{} translated to x86, showing the results of
  9301. \code{explicate\_control}, \code{select\_instructions}, and the final
  9302. x86 assembly.
  9303. \begin{figure}[tbp]
  9304. \begin{tcolorbox}[colback=white]
  9305. {\if\edition\racketEd
  9306. \begin{tabular}{lll}
  9307. \begin{minipage}{0.4\textwidth}
  9308. % cond_test_20.rkt, eq_input.py
  9309. \begin{lstlisting}
  9310. (if (eq? (read) 1) 42 0)
  9311. \end{lstlisting}
  9312. $\Downarrow$
  9313. \begin{lstlisting}
  9314. start:
  9315. tmp7951 = (read);
  9316. if (eq? tmp7951 1)
  9317. goto block7952;
  9318. else
  9319. goto block7953;
  9320. block7952:
  9321. return 42;
  9322. block7953:
  9323. return 0;
  9324. \end{lstlisting}
  9325. $\Downarrow$
  9326. \begin{lstlisting}
  9327. start:
  9328. callq read_int
  9329. movq %rax, tmp7951
  9330. cmpq $1, tmp7951
  9331. je block7952
  9332. jmp block7953
  9333. block7953:
  9334. movq $0, %rax
  9335. jmp conclusion
  9336. block7952:
  9337. movq $42, %rax
  9338. jmp conclusion
  9339. \end{lstlisting}
  9340. \end{minipage}
  9341. &
  9342. $\Rightarrow\qquad$
  9343. \begin{minipage}{0.4\textwidth}
  9344. \begin{lstlisting}
  9345. start:
  9346. callq read_int
  9347. movq %rax, %rcx
  9348. cmpq $1, %rcx
  9349. je block7952
  9350. jmp block7953
  9351. block7953:
  9352. movq $0, %rax
  9353. jmp conclusion
  9354. block7952:
  9355. movq $42, %rax
  9356. jmp conclusion
  9357. .globl main
  9358. main:
  9359. pushq %rbp
  9360. movq %rsp, %rbp
  9361. pushq %r13
  9362. pushq %r12
  9363. pushq %rbx
  9364. pushq %r14
  9365. subq $0, %rsp
  9366. jmp start
  9367. conclusion:
  9368. addq $0, %rsp
  9369. popq %r14
  9370. popq %rbx
  9371. popq %r12
  9372. popq %r13
  9373. popq %rbp
  9374. retq
  9375. \end{lstlisting}
  9376. \end{minipage}
  9377. \end{tabular}
  9378. \fi}
  9379. {\if\edition\pythonEd\pythonColor
  9380. \begin{tabular}{lll}
  9381. \begin{minipage}{0.4\textwidth}
  9382. % cond_test_20.rkt, eq_input.py
  9383. \begin{lstlisting}
  9384. print(42 if input_int() == 1 else 0)
  9385. \end{lstlisting}
  9386. $\Downarrow$
  9387. \begin{lstlisting}
  9388. start:
  9389. tmp_0 = input_int()
  9390. if tmp_0 == 1:
  9391. goto block_3
  9392. else:
  9393. goto block_4
  9394. block_3:
  9395. tmp_1 = 42
  9396. goto block_2
  9397. block_4:
  9398. tmp_1 = 0
  9399. goto block_2
  9400. block_2:
  9401. print(tmp_1)
  9402. return 0
  9403. \end{lstlisting}
  9404. $\Downarrow$
  9405. \begin{lstlisting}
  9406. start:
  9407. callq read_int
  9408. movq %rax, tmp_0
  9409. cmpq 1, tmp_0
  9410. je block_3
  9411. jmp block_4
  9412. block_3:
  9413. movq 42, tmp_1
  9414. jmp block_2
  9415. block_4:
  9416. movq 0, tmp_1
  9417. jmp block_2
  9418. block_2:
  9419. movq tmp_1, %rdi
  9420. callq print_int
  9421. movq 0, %rax
  9422. jmp conclusion
  9423. \end{lstlisting}
  9424. \end{minipage}
  9425. &
  9426. $\Rightarrow\qquad$
  9427. \begin{minipage}{0.4\textwidth}
  9428. \begin{lstlisting}
  9429. .globl main
  9430. main:
  9431. pushq %rbp
  9432. movq %rsp, %rbp
  9433. subq $0, %rsp
  9434. jmp start
  9435. start:
  9436. callq read_int
  9437. movq %rax, %rcx
  9438. cmpq $1, %rcx
  9439. je block_3
  9440. jmp block_4
  9441. block_3:
  9442. movq $42, %rcx
  9443. jmp block_2
  9444. block_4:
  9445. movq $0, %rcx
  9446. jmp block_2
  9447. block_2:
  9448. movq %rcx, %rdi
  9449. callq print_int
  9450. movq $0, %rax
  9451. jmp conclusion
  9452. conclusion:
  9453. addq $0, %rsp
  9454. popq %rbp
  9455. retq
  9456. \end{lstlisting}
  9457. \end{minipage}
  9458. \end{tabular}
  9459. \fi}
  9460. \end{tcolorbox}
  9461. \caption{Example compilation of an \key{if} expression to x86, showing
  9462. the results of \code{explicate\_control},
  9463. \code{select\_instructions}, and the final x86 assembly code. }
  9464. \label{fig:if-example-x86}
  9465. \end{figure}
  9466. \begin{figure}[tbp]
  9467. \begin{tcolorbox}[colback=white]
  9468. {\if\edition\racketEd
  9469. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9470. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9471. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9472. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9473. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9474. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9475. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9476. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9477. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9478. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9479. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9480. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9481. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9482. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9483. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9484. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9485. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9486. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9487. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9488. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9489. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9490. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9491. \end{tikzpicture}
  9492. \fi}
  9493. {\if\edition\pythonEd\pythonColor
  9494. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9495. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9496. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9497. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9498. \node (C-1) at (0,0) {\large \LangCIf{}};
  9499. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9500. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9501. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9502. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9503. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9504. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9505. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9506. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9507. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9508. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9509. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9510. \end{tikzpicture}
  9511. \fi}
  9512. \end{tcolorbox}
  9513. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9514. \label{fig:Lif-passes}
  9515. \end{figure}
  9516. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9517. compilation of \LangIf{}.
  9518. \section{Challenge: Optimize Blocks and Remove Jumps}
  9519. \label{sec:opt-jumps}
  9520. We discuss two challenges that involve optimizing the control-flow of
  9521. the program.
  9522. \subsection{Optimize Blocks}
  9523. The algorithm for \code{explicate\_control} that we discussed in
  9524. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9525. blocks. It creates a block whenever a continuation \emph{might} get
  9526. used more than once (for example, whenever the \code{cont} parameter
  9527. is passed into two or more recursive calls). However, some
  9528. continuation arguments may not be used at all. Consider the case for
  9529. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9530. the \code{els} continuation.
  9531. %
  9532. {\if\edition\racketEd
  9533. The following example program falls into this
  9534. case, and it creates two unused blocks.
  9535. \begin{center}
  9536. \begin{tabular}{lll}
  9537. \begin{minipage}{0.4\textwidth}
  9538. % cond_test_82.rkt
  9539. \begin{lstlisting}
  9540. (let ([y (if #t
  9541. (read)
  9542. (if (eq? (read) 0)
  9543. 777
  9544. (let ([x (read)])
  9545. (+ 1 x))))])
  9546. (+ y 2))
  9547. \end{lstlisting}
  9548. \end{minipage}
  9549. &
  9550. $\Rightarrow$
  9551. &
  9552. \begin{minipage}{0.55\textwidth}
  9553. \begin{lstlisting}
  9554. start:
  9555. y = (read);
  9556. goto block_5;
  9557. block_5:
  9558. return (+ y 2);
  9559. block_6:
  9560. y = 777;
  9561. goto block_5;
  9562. block_7:
  9563. x = (read);
  9564. y = (+ 1 x2);
  9565. goto block_5;
  9566. \end{lstlisting}
  9567. \end{minipage}
  9568. \end{tabular}
  9569. \end{center}
  9570. \fi}
  9571. The question is, how can we decide whether to create a basic block?
  9572. \emph{Lazy evaluation}\index{subject}{lazy
  9573. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9574. delaying the creation of a basic block until the point in time at which
  9575. we know that it will be used.
  9576. %
  9577. {\if\edition\racketEd
  9578. %
  9579. Racket provides support for
  9580. lazy evaluation with the
  9581. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9582. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9583. \index{subject}{delay} creates a
  9584. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9585. expressions is postponed. When \key{(force}
  9586. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9587. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9588. result of $e_n$ is cached in the promise and returned. If \code{force}
  9589. is applied again to the same promise, then the cached result is
  9590. returned. If \code{force} is applied to an argument that is not a
  9591. promise, \code{force} simply returns the argument.
  9592. %
  9593. \fi}
  9594. %
  9595. {\if\edition\pythonEd\pythonColor
  9596. %
  9597. Although Python does not provide direct support for lazy evaluation,
  9598. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9599. by wrapping it inside a function with no parameters. We \emph{force}
  9600. its evaluation by calling the function. However, we might need to
  9601. force multiple times, so we store the result of calling the
  9602. function instead of recomputing it each time. The following
  9603. \code{Promise} class handles this memoization process.
  9604. %
  9605. \begin{lstlisting}
  9606. @dataclass
  9607. class Promise:
  9608. fun : typing.Any
  9609. cache : list[stmt] = None
  9610. def force(self):
  9611. if self.cache is None:
  9612. self.cache = self.fun(); return self.cache
  9613. else:
  9614. return self.cache
  9615. \end{lstlisting}
  9616. %
  9617. However, in some cases of \code{explicate\_pred} we return a list
  9618. of statements, and in other cases we return a function that
  9619. computes a list of statements. To uniformly deal with both regular
  9620. data and promises, we define the following \code{force} function that
  9621. checks whether its input is delayed (i.e., whether it is a
  9622. \code{Promise}) and then either (1) forces the promise or (2) returns
  9623. the input.
  9624. %
  9625. \begin{lstlisting}
  9626. def force(promise):
  9627. if isinstance(promise, Promise):
  9628. return promise.force()
  9629. else:
  9630. return promise
  9631. \end{lstlisting}
  9632. %
  9633. \fi}
  9634. We use promises for the input and output of the functions
  9635. \code{explicate\_pred}, \code{explicate\_assign},
  9636. %
  9637. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9638. %
  9639. So, instead of taking and returning \racket{$\Tail$
  9640. expressions}\python{lists of statements}, they take and return
  9641. promises. Furthermore, when we come to a situation in which a
  9642. continuation might be used more than once, as in the case for
  9643. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9644. that creates a basic block for each continuation (if there is not
  9645. already one) and then returns a \code{goto} statement to that basic
  9646. block. When we come to a situation in which we have a promise but need an
  9647. actual piece of code, for example, to create a larger piece of code with a
  9648. constructor such as \code{Seq}, then insert a call to \code{force}.
  9649. %
  9650. {\if\edition\racketEd
  9651. %
  9652. Also, we must modify the \code{create\_block} function to begin with
  9653. \code{delay} to create a promise. When forced, this promise forces the
  9654. original promise. If that returns a \code{Goto} (because the block was
  9655. already added to \code{basic-blocks}), then we return the
  9656. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9657. return a \code{Goto} to the new label.
  9658. \begin{center}
  9659. \begin{minipage}{\textwidth}
  9660. \begin{lstlisting}
  9661. (define (create_block tail)
  9662. (delay
  9663. (define t (force tail))
  9664. (match t
  9665. [(Goto label) (Goto label)]
  9666. [else
  9667. (let ([label (gensym 'block)])
  9668. (set! basic-blocks (cons (cons label t) basic-blocks))
  9669. (Goto label))])))
  9670. \end{lstlisting}
  9671. \end{minipage}
  9672. \end{center}
  9673. \fi}
  9674. {\if\edition\pythonEd\pythonColor
  9675. %
  9676. Here is the new version of the \code{create\_block} auxiliary function
  9677. that works on promises and that checks whether the block consists of a
  9678. solitary \code{goto} statement.\\
  9679. \begin{minipage}{\textwidth}
  9680. \begin{lstlisting}
  9681. def create_block(promise, basic_blocks):
  9682. def delay():
  9683. stmts = force(promise)
  9684. match stmts:
  9685. case [Goto(l)]:
  9686. return [Goto(l)]
  9687. case _:
  9688. label = label_name(generate_name('block'))
  9689. basic_blocks[label] = stmts
  9690. return [Goto(label)]
  9691. return Promise(delay)
  9692. \end{lstlisting}
  9693. \end{minipage}
  9694. \fi}
  9695. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9696. improved \code{explicate\_control} on this example. As you can
  9697. see, the number of basic blocks has been reduced from four blocks (see
  9698. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9699. \begin{figure}[tbp]
  9700. \begin{tcolorbox}[colback=white]
  9701. {\if\edition\racketEd
  9702. \begin{tabular}{lll}
  9703. \begin{minipage}{0.4\textwidth}
  9704. % cond_test_82.rkt
  9705. \begin{lstlisting}
  9706. (let ([y (if #t
  9707. (read)
  9708. (if (eq? (read) 0)
  9709. 777
  9710. (let ([x (read)])
  9711. (+ 1 x))))])
  9712. (+ y 2))
  9713. \end{lstlisting}
  9714. \end{minipage}
  9715. &
  9716. $\Rightarrow$
  9717. &
  9718. \begin{minipage}{0.55\textwidth}
  9719. \begin{lstlisting}
  9720. start:
  9721. y = (read);
  9722. goto block_5;
  9723. block_5:
  9724. return (+ y 2);
  9725. \end{lstlisting}
  9726. \end{minipage}
  9727. \end{tabular}
  9728. \fi}
  9729. {\if\edition\pythonEd\pythonColor
  9730. \begin{tabular}{lll}
  9731. \begin{minipage}{0.4\textwidth}
  9732. % cond_test_41.rkt
  9733. \begin{lstlisting}
  9734. x = input_int()
  9735. y = input_int()
  9736. print(y + 2 \
  9737. if (x == 0 \
  9738. if x < 1 \
  9739. else x == 2) \
  9740. else y + 10)
  9741. \end{lstlisting}
  9742. \end{minipage}
  9743. &
  9744. $\Rightarrow$
  9745. &
  9746. \begin{minipage}{0.55\textwidth}
  9747. \begin{lstlisting}
  9748. start:
  9749. x = input_int()
  9750. y = input_int()
  9751. if x < 1:
  9752. goto block_4
  9753. else:
  9754. goto block_5
  9755. block_4:
  9756. if x == 0:
  9757. goto block_2
  9758. else:
  9759. goto block_3
  9760. block_5:
  9761. if x == 2:
  9762. goto block_2
  9763. else:
  9764. goto block_3
  9765. block_2:
  9766. tmp_0 = y + 2
  9767. goto block_1
  9768. block_3:
  9769. tmp_0 = y + 10
  9770. goto block_1
  9771. block_1:
  9772. print(tmp_0)
  9773. return 0
  9774. \end{lstlisting}
  9775. \end{minipage}
  9776. \end{tabular}
  9777. \fi}
  9778. \end{tcolorbox}
  9779. \caption{Translation from \LangIf{} to \LangCIf{}
  9780. via the improved \code{explicate\_control}.}
  9781. \label{fig:explicate-control-challenge}
  9782. \end{figure}
  9783. %% Recall that in the example output of \code{explicate\_control} in
  9784. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9785. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9786. %% block. The first goal of this challenge assignment is to remove those
  9787. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9788. %% \code{explicate\_control} on the left and shows the result of bypassing
  9789. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9790. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9791. %% \code{block55}. The optimized code on the right of
  9792. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9793. %% \code{then} branch jumping directly to \code{block55}. The story is
  9794. %% similar for the \code{else} branch, as well as for the two branches in
  9795. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9796. %% have been optimized in this way, there are no longer any jumps to
  9797. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9798. %% \begin{figure}[tbp]
  9799. %% \begin{tabular}{lll}
  9800. %% \begin{minipage}{0.4\textwidth}
  9801. %% \begin{lstlisting}
  9802. %% block62:
  9803. %% tmp54 = (read);
  9804. %% if (eq? tmp54 2) then
  9805. %% goto block59;
  9806. %% else
  9807. %% goto block60;
  9808. %% block61:
  9809. %% tmp53 = (read);
  9810. %% if (eq? tmp53 0) then
  9811. %% goto block57;
  9812. %% else
  9813. %% goto block58;
  9814. %% block60:
  9815. %% goto block56;
  9816. %% block59:
  9817. %% goto block55;
  9818. %% block58:
  9819. %% goto block56;
  9820. %% block57:
  9821. %% goto block55;
  9822. %% block56:
  9823. %% return (+ 700 77);
  9824. %% block55:
  9825. %% return (+ 10 32);
  9826. %% start:
  9827. %% tmp52 = (read);
  9828. %% if (eq? tmp52 1) then
  9829. %% goto block61;
  9830. %% else
  9831. %% goto block62;
  9832. %% \end{lstlisting}
  9833. %% \end{minipage}
  9834. %% &
  9835. %% $\Rightarrow$
  9836. %% &
  9837. %% \begin{minipage}{0.55\textwidth}
  9838. %% \begin{lstlisting}
  9839. %% block62:
  9840. %% tmp54 = (read);
  9841. %% if (eq? tmp54 2) then
  9842. %% goto block55;
  9843. %% else
  9844. %% goto block56;
  9845. %% block61:
  9846. %% tmp53 = (read);
  9847. %% if (eq? tmp53 0) then
  9848. %% goto block55;
  9849. %% else
  9850. %% goto block56;
  9851. %% block56:
  9852. %% return (+ 700 77);
  9853. %% block55:
  9854. %% return (+ 10 32);
  9855. %% start:
  9856. %% tmp52 = (read);
  9857. %% if (eq? tmp52 1) then
  9858. %% goto block61;
  9859. %% else
  9860. %% goto block62;
  9861. %% \end{lstlisting}
  9862. %% \end{minipage}
  9863. %% \end{tabular}
  9864. %% \caption{Optimize jumps by removing trivial blocks.}
  9865. %% \label{fig:optimize-jumps}
  9866. %% \end{figure}
  9867. %% The name of this pass is \code{optimize-jumps}. We recommend
  9868. %% implementing this pass in two phases. The first phrase builds a hash
  9869. %% table that maps labels to possibly improved labels. The second phase
  9870. %% changes the target of each \code{goto} to use the improved label. If
  9871. %% the label is for a trivial block, then the hash table should map the
  9872. %% label to the first non-trivial block that can be reached from this
  9873. %% label by jumping through trivial blocks. If the label is for a
  9874. %% non-trivial block, then the hash table should map the label to itself;
  9875. %% we do not want to change jumps to non-trivial blocks.
  9876. %% The first phase can be accomplished by constructing an empty hash
  9877. %% table, call it \code{short-cut}, and then iterating over the control
  9878. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9879. %% then update the hash table, mapping the block's source to the target
  9880. %% of the \code{goto}. Also, the hash table may already have mapped some
  9881. %% labels to the block's source, to you must iterate through the hash
  9882. %% table and update all of those so that they instead map to the target
  9883. %% of the \code{goto}.
  9884. %% For the second phase, we recommend iterating through the $\Tail$ of
  9885. %% each block in the program, updating the target of every \code{goto}
  9886. %% according to the mapping in \code{short-cut}.
  9887. \begin{exercise}\normalfont\normalsize
  9888. Implement the improvements to the \code{explicate\_control} pass.
  9889. Check that it removes trivial blocks in a few example programs. Then
  9890. check that your compiler still passes all your tests.
  9891. \end{exercise}
  9892. \subsection{Remove Jumps}
  9893. There is an opportunity for removing jumps that is apparent in the
  9894. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9895. ends with a jump to \code{block\_5}, and there are no other jumps to
  9896. \code{block\_5} in the rest of the program. In this situation we can
  9897. avoid the runtime overhead of this jump by merging \code{block\_5}
  9898. into the preceding block, which in this case is the \code{start} block.
  9899. Figure~\ref{fig:remove-jumps} shows the output of
  9900. \code{allocate\_registers} on the left and the result of this
  9901. optimization on the right.
  9902. \begin{figure}[tbp]
  9903. \begin{tcolorbox}[colback=white]
  9904. {\if\edition\racketEd
  9905. \begin{tabular}{lll}
  9906. \begin{minipage}{0.5\textwidth}
  9907. % cond_test_82.rkt
  9908. \begin{lstlisting}
  9909. start:
  9910. callq read_int
  9911. movq %rax, %rcx
  9912. jmp block_5
  9913. block_5:
  9914. movq %rcx, %rax
  9915. addq $2, %rax
  9916. jmp conclusion
  9917. \end{lstlisting}
  9918. \end{minipage}
  9919. &
  9920. $\Rightarrow\qquad$
  9921. \begin{minipage}{0.4\textwidth}
  9922. \begin{lstlisting}
  9923. start:
  9924. callq read_int
  9925. movq %rax, %rcx
  9926. movq %rcx, %rax
  9927. addq $2, %rax
  9928. jmp conclusion
  9929. \end{lstlisting}
  9930. \end{minipage}
  9931. \end{tabular}
  9932. \fi}
  9933. {\if\edition\pythonEd\pythonColor
  9934. \begin{tabular}{lll}
  9935. \begin{minipage}{0.5\textwidth}
  9936. % cond_test_20.rkt
  9937. \begin{lstlisting}
  9938. start:
  9939. callq read_int
  9940. movq %rax, tmp_0
  9941. cmpq 1, tmp_0
  9942. je block_3
  9943. jmp block_4
  9944. block_3:
  9945. movq 42, tmp_1
  9946. jmp block_2
  9947. block_4:
  9948. movq 0, tmp_1
  9949. jmp block_2
  9950. block_2:
  9951. movq tmp_1, %rdi
  9952. callq print_int
  9953. movq 0, %rax
  9954. jmp conclusion
  9955. \end{lstlisting}
  9956. \end{minipage}
  9957. &
  9958. $\Rightarrow\qquad$
  9959. \begin{minipage}{0.4\textwidth}
  9960. \begin{lstlisting}
  9961. start:
  9962. callq read_int
  9963. movq %rax, tmp_0
  9964. cmpq 1, tmp_0
  9965. je block_3
  9966. movq 0, tmp_1
  9967. jmp block_2
  9968. block_3:
  9969. movq 42, tmp_1
  9970. jmp block_2
  9971. block_2:
  9972. movq tmp_1, %rdi
  9973. callq print_int
  9974. movq 0, %rax
  9975. jmp conclusion
  9976. \end{lstlisting}
  9977. \end{minipage}
  9978. \end{tabular}
  9979. \fi}
  9980. \end{tcolorbox}
  9981. \caption{Merging basic blocks by removing unnecessary jumps.}
  9982. \label{fig:remove-jumps}
  9983. \end{figure}
  9984. \begin{exercise}\normalfont\normalsize
  9985. %
  9986. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9987. into their preceding basic block, when there is only one preceding
  9988. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9989. %
  9990. {\if\edition\racketEd
  9991. In the \code{run-tests.rkt} script, add the following entry to the
  9992. list of \code{passes} between \code{allocate\_registers}
  9993. and \code{patch\_instructions}:
  9994. \begin{lstlisting}
  9995. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9996. \end{lstlisting}
  9997. \fi}
  9998. %
  9999. Run the script to test your compiler.
  10000. %
  10001. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10002. blocks on several test programs.
  10003. \end{exercise}
  10004. \section{Further Reading}
  10005. \label{sec:cond-further-reading}
  10006. The algorithm for the \code{explicate\_control} pass is based on the
  10007. \code{expose-basic-blocks} pass in the course notes of
  10008. \citet{Dybvig:2010aa}.
  10009. %
  10010. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10011. \citet{Appel:2003fk}, and is related to translations into continuation
  10012. passing
  10013. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10014. %
  10015. The treatment of conditionals in the \code{explicate\_control} pass is
  10016. similar to short-cut Boolean
  10017. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10018. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10019. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10020. \chapter{Loops and Dataflow Analysis}
  10021. \label{ch:Lwhile}
  10022. \setcounter{footnote}{0}
  10023. % TODO: define R'_8
  10024. % TODO: multi-graph
  10025. {\if\edition\racketEd
  10026. %
  10027. In this chapter we study two features that are the hallmarks of
  10028. imperative programming languages: loops and assignments to local
  10029. variables. The following example demonstrates these new features by
  10030. computing the sum of the first five positive integers:
  10031. % similar to loop_test_1.rkt
  10032. \begin{lstlisting}
  10033. (let ([sum 0])
  10034. (let ([i 5])
  10035. (begin
  10036. (while (> i 0)
  10037. (begin
  10038. (set! sum (+ sum i))
  10039. (set! i (- i 1))))
  10040. sum)))
  10041. \end{lstlisting}
  10042. The \code{while} loop consists of a condition and a
  10043. body.\footnote{The \code{while} loop is not a built-in
  10044. feature of the Racket language, but Racket includes many looping
  10045. constructs and it is straightforward to define \code{while} as a
  10046. macro.} The body is evaluated repeatedly so long as the condition
  10047. remains true.
  10048. %
  10049. The \code{set!} consists of a variable and a right-hand side
  10050. expression. The \code{set!} updates value of the variable to the
  10051. value of the right-hand side.
  10052. %
  10053. The primary purpose of both the \code{while} loop and \code{set!} is
  10054. to cause side effects, so they do not give a meaningful result
  10055. value. Instead, their result is the \code{\#<void>} value. The
  10056. expression \code{(void)} is an explicit way to create the
  10057. \code{\#<void>} value, and it has type \code{Void}. The
  10058. \code{\#<void>} value can be passed around just like other values
  10059. inside an \LangLoop{} program, and it can be compared for equality with
  10060. another \code{\#<void>} value. However, there are no other operations
  10061. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10062. Racket defines the \code{void?} predicate that returns \code{\#t}
  10063. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10064. %
  10065. \footnote{Racket's \code{Void} type corresponds to what is often
  10066. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10067. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10068. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10069. %
  10070. With the addition of side effect-producing features such as
  10071. \code{while} loop and \code{set!}, it is helpful to include a language
  10072. feature for sequencing side effects: the \code{begin} expression. It
  10073. consists of one or more subexpressions that are evaluated
  10074. left to right.
  10075. %
  10076. \fi}
  10077. {\if\edition\pythonEd\pythonColor
  10078. %
  10079. In this chapter we study loops, one of the hallmarks of imperative
  10080. programming languages. The following example demonstrates the
  10081. \code{while} loop by computing the sum of the first five positive
  10082. integers.
  10083. \begin{lstlisting}
  10084. sum = 0
  10085. i = 5
  10086. while i > 0:
  10087. sum = sum + i
  10088. i = i - 1
  10089. print(sum)
  10090. \end{lstlisting}
  10091. The \code{while} loop consists of a condition expression and a body (a
  10092. sequence of statements). The body is evaluated repeatedly so long as
  10093. the condition remains true.
  10094. %
  10095. \fi}
  10096. \section{The \LangLoop{} Language}
  10097. \newcommand{\LwhileGrammarRacket}{
  10098. \begin{array}{lcl}
  10099. \Type &::=& \key{Void}\\
  10100. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10101. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10102. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10103. \end{array}
  10104. }
  10105. \newcommand{\LwhileASTRacket}{
  10106. \begin{array}{lcl}
  10107. \Type &::=& \key{Void}\\
  10108. \Exp &::=& \SETBANG{\Var}{\Exp}
  10109. \MID \BEGIN{\Exp^{*}}{\Exp}
  10110. \MID \WHILE{\Exp}{\Exp}
  10111. \MID \VOID{}
  10112. \end{array}
  10113. }
  10114. \newcommand{\LwhileGrammarPython}{
  10115. \begin{array}{rcl}
  10116. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10117. \end{array}
  10118. }
  10119. \newcommand{\LwhileASTPython}{
  10120. \begin{array}{lcl}
  10121. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10122. \end{array}
  10123. }
  10124. \begin{figure}[tp]
  10125. \centering
  10126. \begin{tcolorbox}[colback=white]
  10127. \small
  10128. {\if\edition\racketEd
  10129. \[
  10130. \begin{array}{l}
  10131. \gray{\LintGrammarRacket{}} \\ \hline
  10132. \gray{\LvarGrammarRacket{}} \\ \hline
  10133. \gray{\LifGrammarRacket{}} \\ \hline
  10134. \LwhileGrammarRacket \\
  10135. \begin{array}{lcl}
  10136. \LangLoopM{} &::=& \Exp
  10137. \end{array}
  10138. \end{array}
  10139. \]
  10140. \fi}
  10141. {\if\edition\pythonEd\pythonColor
  10142. \[
  10143. \begin{array}{l}
  10144. \gray{\LintGrammarPython} \\ \hline
  10145. \gray{\LvarGrammarPython} \\ \hline
  10146. \gray{\LifGrammarPython} \\ \hline
  10147. \LwhileGrammarPython \\
  10148. \begin{array}{rcl}
  10149. \LangLoopM{} &::=& \Stmt^{*}
  10150. \end{array}
  10151. \end{array}
  10152. \]
  10153. \fi}
  10154. \end{tcolorbox}
  10155. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10156. \label{fig:Lwhile-concrete-syntax}
  10157. \end{figure}
  10158. \begin{figure}[tp]
  10159. \centering
  10160. \begin{tcolorbox}[colback=white]
  10161. \small
  10162. {\if\edition\racketEd
  10163. \[
  10164. \begin{array}{l}
  10165. \gray{\LintOpAST} \\ \hline
  10166. \gray{\LvarASTRacket{}} \\ \hline
  10167. \gray{\LifASTRacket{}} \\ \hline
  10168. \LwhileASTRacket{} \\
  10169. \begin{array}{lcl}
  10170. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10171. \end{array}
  10172. \end{array}
  10173. \]
  10174. \fi}
  10175. {\if\edition\pythonEd\pythonColor
  10176. \[
  10177. \begin{array}{l}
  10178. \gray{\LintASTPython} \\ \hline
  10179. \gray{\LvarASTPython} \\ \hline
  10180. \gray{\LifASTPython} \\ \hline
  10181. \LwhileASTPython \\
  10182. \begin{array}{lcl}
  10183. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10184. \end{array}
  10185. \end{array}
  10186. \]
  10187. \fi}
  10188. \end{tcolorbox}
  10189. \python{
  10190. \index{subject}{While@\texttt{While}}
  10191. }
  10192. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10193. \label{fig:Lwhile-syntax}
  10194. \end{figure}
  10195. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10196. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10197. shows the definition of its abstract syntax.
  10198. %
  10199. The definitional interpreter for \LangLoop{} is shown in
  10200. figure~\ref{fig:interp-Lwhile}.
  10201. %
  10202. {\if\edition\racketEd
  10203. %
  10204. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10205. and \code{Void}, and we make changes to the cases for \code{Var} and
  10206. \code{Let} regarding variables. To support assignment to variables and
  10207. to make their lifetimes indefinite (see the second example in
  10208. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10209. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10210. value.
  10211. %
  10212. Now we discuss the new cases. For \code{SetBang}, we find the
  10213. variable in the environment to obtain a boxed value, and then we change
  10214. it using \code{set-box!} to the result of evaluating the right-hand
  10215. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10216. %
  10217. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10218. if the result is true, (2) evaluate the body.
  10219. The result value of a \code{while} loop is also \code{\#<void>}.
  10220. %
  10221. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10222. subexpressions \itm{es} for their effects and then evaluates
  10223. and returns the result from \itm{body}.
  10224. %
  10225. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10226. %
  10227. \fi}
  10228. {\if\edition\pythonEd\pythonColor
  10229. %
  10230. We add a new case for \code{While} in the \code{interp\_stmts}
  10231. function, in which we repeatedly interpret the \code{body} so long as the
  10232. \code{test} expression remains true.
  10233. %
  10234. \fi}
  10235. \begin{figure}[tbp]
  10236. \begin{tcolorbox}[colback=white]
  10237. {\if\edition\racketEd
  10238. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10239. (define interp-Lwhile-class
  10240. (class interp-Lif-class
  10241. (super-new)
  10242. (define/override ((interp-exp env) e)
  10243. (define recur (interp-exp env))
  10244. (match e
  10245. [(Let x e body)
  10246. (define new-env (dict-set env x (box (recur e))))
  10247. ((interp-exp new-env) body)]
  10248. [(Var x) (unbox (dict-ref env x))]
  10249. [(SetBang x rhs)
  10250. (set-box! (dict-ref env x) (recur rhs))]
  10251. [(WhileLoop cnd body)
  10252. (define (loop)
  10253. (cond [(recur cnd) (recur body) (loop)]
  10254. [else (void)]))
  10255. (loop)]
  10256. [(Begin es body)
  10257. (for ([e es]) (recur e))
  10258. (recur body)]
  10259. [(Void) (void)]
  10260. [else ((super interp-exp env) e)]))
  10261. ))
  10262. (define (interp-Lwhile p)
  10263. (send (new interp-Lwhile-class) interp-program p))
  10264. \end{lstlisting}
  10265. \fi}
  10266. {\if\edition\pythonEd\pythonColor
  10267. \begin{lstlisting}
  10268. class InterpLwhile(InterpLif):
  10269. def interp_stmt(self, s, env, cont):
  10270. match s:
  10271. case While(test, body, []):
  10272. if self.interp_exp(test, env):
  10273. self.interp_stmts(body + [s] + cont, env)
  10274. else:
  10275. return self.interp_stmts(cont, env)
  10276. case _:
  10277. return super().interp_stmt(s, env, cont)
  10278. \end{lstlisting}
  10279. \fi}
  10280. \end{tcolorbox}
  10281. \caption{Interpreter for \LangLoop{}.}
  10282. \label{fig:interp-Lwhile}
  10283. \end{figure}
  10284. The definition of the type checker for \LangLoop{} is shown in
  10285. figure~\ref{fig:type-check-Lwhile}.
  10286. %
  10287. {\if\edition\racketEd
  10288. %
  10289. The type checking of the \code{SetBang} expression requires the type
  10290. of the variable and the right-hand side to agree. The result type is
  10291. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10292. and the result type is \code{Void}. For \code{Begin}, the result type
  10293. is the type of its last subexpression.
  10294. %
  10295. \fi}
  10296. %
  10297. {\if\edition\pythonEd\pythonColor
  10298. %
  10299. A \code{while} loop is well typed if the type of the \code{test}
  10300. expression is \code{bool} and the statements in the \code{body} are
  10301. well typed.
  10302. %
  10303. \fi}
  10304. \begin{figure}[tbp]
  10305. \begin{tcolorbox}[colback=white]
  10306. {\if\edition\racketEd
  10307. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10308. (define type-check-Lwhile-class
  10309. (class type-check-Lif-class
  10310. (super-new)
  10311. (inherit check-type-equal?)
  10312. (define/override (type-check-exp env)
  10313. (lambda (e)
  10314. (define recur (type-check-exp env))
  10315. (match e
  10316. [(SetBang x rhs)
  10317. (define-values (rhs^ rhsT) (recur rhs))
  10318. (define varT (dict-ref env x))
  10319. (check-type-equal? rhsT varT e)
  10320. (values (SetBang x rhs^) 'Void)]
  10321. [(WhileLoop cnd body)
  10322. (define-values (cnd^ Tc) (recur cnd))
  10323. (check-type-equal? Tc 'Boolean e)
  10324. (define-values (body^ Tbody) ((type-check-exp env) body))
  10325. (values (WhileLoop cnd^ body^) 'Void)]
  10326. [(Begin es body)
  10327. (define-values (es^ ts)
  10328. (for/lists (l1 l2) ([e es]) (recur e)))
  10329. (define-values (body^ Tbody) (recur body))
  10330. (values (Begin es^ body^) Tbody)]
  10331. [else ((super type-check-exp env) e)])))
  10332. ))
  10333. (define (type-check-Lwhile p)
  10334. (send (new type-check-Lwhile-class) type-check-program p))
  10335. \end{lstlisting}
  10336. \fi}
  10337. {\if\edition\pythonEd\pythonColor
  10338. \begin{lstlisting}
  10339. class TypeCheckLwhile(TypeCheckLif):
  10340. def type_check_stmts(self, ss, env):
  10341. if len(ss) == 0:
  10342. return
  10343. match ss[0]:
  10344. case While(test, body, []):
  10345. test_t = self.type_check_exp(test, env)
  10346. check_type_equal(bool, test_t, test)
  10347. body_t = self.type_check_stmts(body, env)
  10348. return self.type_check_stmts(ss[1:], env)
  10349. case _:
  10350. return super().type_check_stmts(ss, env)
  10351. \end{lstlisting}
  10352. \fi}
  10353. \end{tcolorbox}
  10354. \caption{Type checker for the \LangLoop{} language.}
  10355. \label{fig:type-check-Lwhile}
  10356. \end{figure}
  10357. {\if\edition\racketEd
  10358. %
  10359. At first glance, the translation of these language features to x86
  10360. seems straightforward because the \LangCIf{} intermediate language
  10361. already supports all the ingredients that we need: assignment,
  10362. \code{goto}, conditional branching, and sequencing. However,
  10363. complications arise, which we discuss in the next section. After
  10364. that we introduce the changes necessary to the existing passes.
  10365. %
  10366. \fi}
  10367. {\if\edition\pythonEd\pythonColor
  10368. %
  10369. At first glance, the translation of \code{while} loops to x86 seems
  10370. straightforward because the \LangCIf{} intermediate language already
  10371. supports \code{goto} and conditional branching. However, there are
  10372. complications that arise which we discuss in the next section. After
  10373. that we introduce the changes necessary to the existing passes.
  10374. %
  10375. \fi}
  10376. \section{Cyclic Control Flow and Dataflow Analysis}
  10377. \label{sec:dataflow-analysis}
  10378. Up until this point, the programs generated in
  10379. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10380. \code{while} loop introduces a cycle. Does that matter?
  10381. %
  10382. Indeed, it does. Recall that for register allocation, the compiler
  10383. performs liveness analysis to determine which variables can share the
  10384. same register. To accomplish this, we analyzed the control-flow graph
  10385. in reverse topological order
  10386. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10387. well defined only for acyclic graphs.
  10388. Let us return to the example of computing the sum of the first five
  10389. positive integers. Here is the program after instruction
  10390. selection\index{subject}{instruction selection} but before register
  10391. allocation.
  10392. \begin{center}
  10393. {\if\edition\racketEd
  10394. \begin{minipage}{0.45\textwidth}
  10395. \begin{lstlisting}
  10396. (define (main) : Integer
  10397. mainstart:
  10398. movq $0, sum
  10399. movq $5, i
  10400. jmp block5
  10401. block5:
  10402. movq i, tmp3
  10403. cmpq tmp3, $0
  10404. jl block7
  10405. jmp block8
  10406. \end{lstlisting}
  10407. \end{minipage}
  10408. \begin{minipage}{0.45\textwidth}
  10409. \begin{lstlisting}
  10410. block7:
  10411. addq i, sum
  10412. movq $1, tmp4
  10413. negq tmp4
  10414. addq tmp4, i
  10415. jmp block5
  10416. block8:
  10417. movq $27, %rax
  10418. addq sum, %rax
  10419. jmp mainconclusion)
  10420. \end{lstlisting}
  10421. \end{minipage}
  10422. \fi}
  10423. {\if\edition\pythonEd\pythonColor
  10424. \begin{minipage}{0.45\textwidth}
  10425. \begin{lstlisting}
  10426. mainstart:
  10427. movq $0, sum
  10428. movq $5, i
  10429. jmp block5
  10430. block5:
  10431. cmpq $0, i
  10432. jg block7
  10433. jmp block8
  10434. \end{lstlisting}
  10435. \end{minipage}
  10436. \begin{minipage}{0.45\textwidth}
  10437. \begin{lstlisting}
  10438. block7:
  10439. addq i, sum
  10440. subq $1, i
  10441. jmp block5
  10442. block8:
  10443. movq sum, %rdi
  10444. callq print_int
  10445. movq $0, %rax
  10446. jmp mainconclusion
  10447. \end{lstlisting}
  10448. \end{minipage}
  10449. \fi}
  10450. \end{center}
  10451. Recall that liveness analysis works backward, starting at the end
  10452. of each function. For this example we could start with \code{block8}
  10453. because we know what is live at the beginning of the conclusion:
  10454. only \code{rax} and \code{rsp}. So the live-before set
  10455. for \code{block8} is \code{\{rsp,sum\}}.
  10456. %
  10457. Next we might try to analyze \code{block5} or \code{block7}, but
  10458. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10459. we are stuck.
  10460. The way out of this impasse is to realize that we can compute an
  10461. underapproximation of each live-before set by starting with empty
  10462. live-after sets. By \emph{underapproximation}, we mean that the set
  10463. contains only variables that are live for some execution of the
  10464. program, but the set may be missing some variables that are live.
  10465. Next, the underapproximations for each block can be improved by (1)
  10466. updating the live-after set for each block using the approximate
  10467. live-before sets from the other blocks, and (2) performing liveness
  10468. analysis again on each block. In fact, by iterating this process, the
  10469. underapproximations eventually become the correct solutions!
  10470. %
  10471. This approach of iteratively analyzing a control-flow graph is
  10472. applicable to many static analysis problems and goes by the name
  10473. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10474. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10475. Washington.
  10476. Let us apply this approach to the previously presented example. We use
  10477. the empty set for the initial live-before set for each block. Let
  10478. $m_0$ be the following mapping from label names to sets of locations
  10479. (variables and registers):
  10480. \begin{center}
  10481. \begin{lstlisting}
  10482. mainstart: {}, block5: {}, block7: {}, block8: {}
  10483. \end{lstlisting}
  10484. \end{center}
  10485. Using the above live-before approximations, we determine the
  10486. live-after for each block and then apply liveness analysis to each
  10487. block. This produces our next approximation $m_1$ of the live-before
  10488. sets.
  10489. \begin{center}
  10490. \begin{lstlisting}
  10491. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10492. \end{lstlisting}
  10493. \end{center}
  10494. For the second round, the live-after for \code{mainstart} is the
  10495. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10496. the liveness analysis for \code{mainstart} computes the empty set. The
  10497. live-after for \code{block5} is the union of the live-before sets for
  10498. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10499. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10500. sum\}}. The live-after for \code{block7} is the live-before for
  10501. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10502. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10503. Together these yield the following approximation $m_2$ of
  10504. the live-before sets:
  10505. \begin{center}
  10506. \begin{lstlisting}
  10507. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10508. \end{lstlisting}
  10509. \end{center}
  10510. In the preceding iteration, only \code{block5} changed, so we can
  10511. limit our attention to \code{mainstart} and \code{block7}, the two
  10512. blocks that jump to \code{block5}. As a result, the live-before sets
  10513. for \code{mainstart} and \code{block7} are updated to include
  10514. \code{rsp}, yielding the following approximation $m_3$:
  10515. \begin{center}
  10516. \begin{lstlisting}
  10517. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10518. \end{lstlisting}
  10519. \end{center}
  10520. Because \code{block7} changed, we analyze \code{block5} once more, but
  10521. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10522. our approximations have converged, so $m_3$ is the solution.
  10523. This iteration process is guaranteed to converge to a solution by the
  10524. Kleene fixed-point theorem, a general theorem about functions on
  10525. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10526. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10527. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10528. join operator
  10529. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10530. will be working with join semilattices.} When two elements are
  10531. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10532. as much information as $m_i$, so we can think of $m_j$ as a
  10533. better-than-or-equal-to approximation in relation to $m_i$. The
  10534. bottom element $\bot$ represents the complete lack of information,
  10535. that is, the worst approximation. The join operator takes two lattice
  10536. elements and combines their information; that is, it produces the
  10537. least upper bound of the two.\index{subject}{least upper bound}
  10538. A dataflow analysis typically involves two lattices: one lattice to
  10539. represent abstract states and another lattice that aggregates the
  10540. abstract states of all the blocks in the control-flow graph. For
  10541. liveness analysis, an abstract state is a set of locations. We form
  10542. the lattice $L$ by taking its elements to be sets of locations, the
  10543. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10544. set, and the join operator to be set union.
  10545. %
  10546. We form a second lattice $M$ by taking its elements to be mappings
  10547. from the block labels to sets of locations (elements of $L$). We
  10548. order the mappings point-wise, using the ordering of $L$. So, given any
  10549. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10550. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10551. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10552. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10553. We can think of one iteration of liveness analysis applied to the
  10554. whole program as being a function $f$ on the lattice $M$. It takes a
  10555. mapping as input and computes a new mapping.
  10556. \[
  10557. f(m_i) = m_{i+1}
  10558. \]
  10559. Next let us think for a moment about what a final solution $m_s$
  10560. should look like. If we perform liveness analysis using the solution
  10561. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10562. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10563. \[
  10564. f(m_s) = m_s
  10565. \]
  10566. Furthermore, the solution should include only locations that are
  10567. forced to be there by performing liveness analysis on the program, so
  10568. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10569. The Kleene fixed-point theorem states that if a function $f$ is
  10570. monotone (better inputs produce better outputs), then the least fixed
  10571. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10572. chain} obtained by starting at $\bot$ and iterating $f$, as
  10573. follows:\index{subject}{Kleene fixed-point theorem}
  10574. \[
  10575. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10576. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10577. \]
  10578. When a lattice contains only finitely long ascending chains, then
  10579. every Kleene chain tops out at some fixed point after some number of
  10580. iterations of $f$.
  10581. \[
  10582. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10583. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10584. \]
  10585. The liveness analysis is indeed a monotone function and the lattice
  10586. $M$ has finitely long ascending chains because there are only a
  10587. finite number of variables and blocks in the program. Thus we are
  10588. guaranteed that iteratively applying liveness analysis to all blocks
  10589. in the program will eventually produce the least fixed point solution.
  10590. Next let us consider dataflow analysis in general and discuss the
  10591. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10592. %
  10593. The algorithm has four parameters: the control-flow graph \code{G}, a
  10594. function \code{transfer} that applies the analysis to one block, and the
  10595. \code{bottom} and \code{join} operators for the lattice of abstract
  10596. states. The \code{analyze\_dataflow} function is formulated as a
  10597. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10598. function come from the predecessor nodes in the control-flow
  10599. graph. However, liveness analysis is a \emph{backward} dataflow
  10600. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10601. function with the transpose of the control-flow graph.
  10602. The algorithm begins by creating the bottom mapping, represented by a
  10603. hash table. It then pushes all the nodes in the control-flow graph
  10604. onto the work list (a queue). The algorithm repeats the \code{while}
  10605. loop as long as there are items in the work list. In each iteration, a
  10606. node is popped from the work list and processed. The \code{input} for
  10607. the node is computed by taking the join of the abstract states of all
  10608. the predecessor nodes. The \code{transfer} function is then applied to
  10609. obtain the \code{output} abstract state. If the output differs from
  10610. the previous state for this block, the mapping for this block is
  10611. updated and its successor nodes are pushed onto the work list.
  10612. \begin{figure}[tb]
  10613. \begin{tcolorbox}[colback=white]
  10614. {\if\edition\racketEd
  10615. \begin{lstlisting}
  10616. (define (analyze_dataflow G transfer bottom join)
  10617. (define mapping (make-hash))
  10618. (for ([v (in-vertices G)])
  10619. (dict-set! mapping v bottom))
  10620. (define worklist (make-queue))
  10621. (for ([v (in-vertices G)])
  10622. (enqueue! worklist v))
  10623. (define trans-G (transpose G))
  10624. (while (not (queue-empty? worklist))
  10625. (define node (dequeue! worklist))
  10626. (define input (for/fold ([state bottom])
  10627. ([pred (in-neighbors trans-G node)])
  10628. (join state (dict-ref mapping pred))))
  10629. (define output (transfer node input))
  10630. (cond [(not (equal? output (dict-ref mapping node)))
  10631. (dict-set! mapping node output)
  10632. (for ([v (in-neighbors G node)])
  10633. (enqueue! worklist v))]))
  10634. mapping)
  10635. \end{lstlisting}
  10636. \fi}
  10637. {\if\edition\pythonEd\pythonColor
  10638. \begin{lstlisting}
  10639. def analyze_dataflow(G, transfer, bottom, join):
  10640. trans_G = transpose(G)
  10641. mapping = dict((v, bottom) for v in G.vertices())
  10642. worklist = deque(G.vertices)
  10643. while worklist:
  10644. node = worklist.pop()
  10645. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10646. input = reduce(join, inputs, bottom)
  10647. output = transfer(node, input)
  10648. if output != mapping[node]:
  10649. mapping[node] = output
  10650. worklist.extend(G.adjacent(node))
  10651. \end{lstlisting}
  10652. \fi}
  10653. \end{tcolorbox}
  10654. \caption{Generic work list algorithm for dataflow analysis.}
  10655. \label{fig:generic-dataflow}
  10656. \end{figure}
  10657. {\if\edition\racketEd
  10658. \section{Mutable Variables and Remove Complex Operands}
  10659. There is a subtle interaction between the
  10660. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10661. and the left-to-right order of evaluation of Racket. Consider the
  10662. following example:
  10663. \begin{lstlisting}
  10664. (let ([x 2])
  10665. (+ x (begin (set! x 40) x)))
  10666. \end{lstlisting}
  10667. The result of this program is \code{42} because the first read from
  10668. \code{x} produces \code{2} and the second produces \code{40}. However,
  10669. if we naively apply the \code{remove\_complex\_operands} pass to this
  10670. example we obtain the following program whose result is \code{80}!
  10671. \begin{lstlisting}
  10672. (let ([x 2])
  10673. (let ([tmp (begin (set! x 40) x)])
  10674. (+ x tmp)))
  10675. \end{lstlisting}
  10676. The problem is that with mutable variables, the ordering between
  10677. reads and writes is important, and the
  10678. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10679. before the first read of \code{x}.
  10680. We recommend solving this problem by giving special treatment to reads
  10681. from mutable variables, that is, variables that occur on the left-hand
  10682. side of a \code{set!}. We mark each read from a mutable variable with
  10683. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10684. that the read operation is effectful in that it can produce different
  10685. results at different points in time. Let's apply this idea to the
  10686. following variation that also involves a variable that is not mutated:
  10687. % loop_test_24.rkt
  10688. \begin{lstlisting}
  10689. (let ([x 2])
  10690. (let ([y 0])
  10691. (+ y (+ x (begin (set! x 40) x)))))
  10692. \end{lstlisting}
  10693. We first analyze this program to discover that variable \code{x}
  10694. is mutable but \code{y} is not. We then transform the program as
  10695. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10696. \begin{lstlisting}
  10697. (let ([x 2])
  10698. (let ([y 0])
  10699. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10700. \end{lstlisting}
  10701. Now that we have a clear distinction between reads from mutable and
  10702. immutable variables, we can apply the \code{remove\_complex\_operands}
  10703. pass, where reads from immutable variables are still classified as
  10704. atomic expressions but reads from mutable variables are classified as
  10705. complex. Thus, \code{remove\_complex\_operands} yields the following
  10706. program:\\
  10707. \begin{minipage}{\textwidth}
  10708. \begin{lstlisting}
  10709. (let ([x 2])
  10710. (let ([y 0])
  10711. (let ([t1 x])
  10712. (let ([t2 (begin (set! x 40) x)])
  10713. (let ([t3 (+ t1 t2)])
  10714. (+ y t3))))))
  10715. \end{lstlisting}
  10716. \end{minipage}
  10717. The temporary variable \code{t1} gets the value of \code{x} before the
  10718. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10719. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10720. do not generate a temporary variable for the occurrence of \code{y}
  10721. because it's an immutable variable. We want to avoid such unnecessary
  10722. extra temporaries because they would needlessly increase the number of
  10723. variables, making it more likely for some of them to be spilled. The
  10724. result of this program is \code{42}, the same as the result prior to
  10725. \code{remove\_complex\_operands}.
  10726. The approach that we've sketched requires only a small
  10727. modification to \code{remove\_complex\_operands} to handle
  10728. \code{get!}. However, it requires a new pass, called
  10729. \code{uncover-get!}, that we discuss in
  10730. section~\ref{sec:uncover-get-bang}.
  10731. As an aside, this problematic interaction between \code{set!} and the
  10732. pass \code{remove\_complex\_operands} is particular to Racket and not
  10733. its predecessor, the Scheme language. The key difference is that
  10734. Scheme does not specify an order of evaluation for the arguments of an
  10735. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10736. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10737. would be correct results for the example program. Interestingly,
  10738. Racket is implemented on top of the Chez Scheme
  10739. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10740. presented in this section (using extra \code{let} bindings to control
  10741. the order of evaluation) is used in the translation from Racket to
  10742. Scheme~\citep{Flatt:2019tb}.
  10743. \fi} % racket
  10744. Having discussed the complications that arise from adding support for
  10745. assignment and loops, we turn to discussing the individual compilation
  10746. passes.
  10747. {\if\edition\racketEd
  10748. \section{Uncover \texttt{get!}}
  10749. \label{sec:uncover-get-bang}
  10750. The goal of this pass is to mark uses of mutable variables so that
  10751. \code{remove\_complex\_operands} can treat them as complex expressions
  10752. and thereby preserve their ordering relative to the side effects in
  10753. other operands. So, the first step is to collect all the mutable
  10754. variables. We recommend creating an auxiliary function for this,
  10755. named \code{collect-set!}, that recursively traverses expressions,
  10756. returning the set of all variables that occur on the left-hand side of a
  10757. \code{set!}. Here's an excerpt of its implementation.
  10758. \begin{center}
  10759. \begin{minipage}{\textwidth}
  10760. \begin{lstlisting}
  10761. (define (collect-set! e)
  10762. (match e
  10763. [(Var x) (set)]
  10764. [(Int n) (set)]
  10765. [(Let x rhs body)
  10766. (set-union (collect-set! rhs) (collect-set! body))]
  10767. [(SetBang var rhs)
  10768. (set-union (set var) (collect-set! rhs))]
  10769. ...))
  10770. \end{lstlisting}
  10771. \end{minipage}
  10772. \end{center}
  10773. By placing this pass after \code{uniquify}, we need not worry about
  10774. variable shadowing, and our logic for \code{Let} can remain simple, as
  10775. in this excerpt.
  10776. The second step is to mark the occurrences of the mutable variables
  10777. with the new \code{GetBang} AST node (\code{get!} in concrete
  10778. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10779. function, which takes two parameters: the set of mutable variables
  10780. \code{set!-vars} and the expression \code{e} to be processed. The
  10781. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10782. mutable variable or leaves it alone if not.
  10783. \begin{center}
  10784. \begin{minipage}{\textwidth}
  10785. \begin{lstlisting}
  10786. (define ((uncover-get!-exp set!-vars) e)
  10787. (match e
  10788. [(Var x)
  10789. (if (set-member? set!-vars x)
  10790. (GetBang x)
  10791. (Var x))]
  10792. ...))
  10793. \end{lstlisting}
  10794. \end{minipage}
  10795. \end{center}
  10796. To wrap things up, define the \code{uncover-get!} function for
  10797. processing a whole program, using \code{collect-set!} to obtain the
  10798. set of mutable variables and then \code{uncover-get!-exp} to replace
  10799. their occurrences with \code{GetBang}.
  10800. \fi}
  10801. \section{Remove Complex Operands}
  10802. \label{sec:rco-loop}
  10803. {\if\edition\racketEd
  10804. %
  10805. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10806. \code{while} are all complex expressions. The subexpressions of
  10807. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10808. %
  10809. \fi}
  10810. {\if\edition\pythonEd\pythonColor
  10811. %
  10812. The change needed for this pass is to add a case for the \code{while}
  10813. statement. The condition of a \code{while} loop is allowed to be a
  10814. complex expression, just like the condition of the \code{if}
  10815. statement.
  10816. %
  10817. \fi}
  10818. %
  10819. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10820. \LangLoopANF{} of this pass.
  10821. \newcommand{\LwhileMonadASTRacket}{
  10822. \begin{array}{rcl}
  10823. \Atm &::=& \VOID{} \\
  10824. \Exp &::=& \GETBANG{\Var}
  10825. \MID \SETBANG{\Var}{\Exp}
  10826. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10827. &\MID& \WHILE{\Exp}{\Exp}
  10828. \end{array}
  10829. }
  10830. \newcommand{\LwhileMonadASTPython}{
  10831. \begin{array}{rcl}
  10832. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10833. \end{array}
  10834. }
  10835. \begin{figure}[tp]
  10836. \centering
  10837. \begin{tcolorbox}[colback=white]
  10838. \small
  10839. {\if\edition\racketEd
  10840. \[
  10841. \begin{array}{l}
  10842. \gray{\LvarMonadASTRacket} \\ \hline
  10843. \gray{\LifMonadASTRacket} \\ \hline
  10844. \LwhileMonadASTRacket \\
  10845. \begin{array}{rcl}
  10846. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10847. \end{array}
  10848. \end{array}
  10849. \]
  10850. \fi}
  10851. {\if\edition\pythonEd\pythonColor
  10852. \[
  10853. \begin{array}{l}
  10854. \gray{\LvarMonadASTPython} \\ \hline
  10855. \gray{\LifMonadASTPython} \\ \hline
  10856. \LwhileMonadASTPython \\
  10857. \begin{array}{rcl}
  10858. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10859. \end{array}
  10860. \end{array}
  10861. %% \begin{array}{rcl}
  10862. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10863. %% \Exp &::=& \Atm \MID \READ{} \\
  10864. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10865. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10866. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10867. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10868. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10869. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10870. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10871. %% \end{array}
  10872. \]
  10873. \fi}
  10874. \end{tcolorbox}
  10875. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10876. \label{fig:Lwhile-anf-syntax}
  10877. \end{figure}
  10878. {\if\edition\racketEd
  10879. %
  10880. As usual, when a complex expression appears in a grammar position that
  10881. needs to be atomic, such as the argument of a primitive operator, we
  10882. must introduce a temporary variable and bind it to the complex
  10883. expression. This approach applies, unchanged, to handle the new
  10884. language forms. For example, in the following code there are two
  10885. \code{begin} expressions appearing as arguments to the \code{+}
  10886. operator. The output of \code{rco\_exp} is then shown, in which the
  10887. \code{begin} expressions have been bound to temporary
  10888. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10889. allowed to have arbitrary expressions in their right-hand side
  10890. expression, so it is fine to place \code{begin} there.
  10891. %
  10892. \begin{center}
  10893. \begin{tabular}{lcl}
  10894. \begin{minipage}{0.4\textwidth}
  10895. \begin{lstlisting}
  10896. (let ([x2 10])
  10897. (let ([y3 0])
  10898. (+ (+ (begin
  10899. (set! y3 (read))
  10900. (get! x2))
  10901. (begin
  10902. (set! x2 (read))
  10903. (get! y3)))
  10904. (get! x2))))
  10905. \end{lstlisting}
  10906. \end{minipage}
  10907. &
  10908. $\Rightarrow$
  10909. &
  10910. \begin{minipage}{0.4\textwidth}
  10911. \begin{lstlisting}
  10912. (let ([x2 10])
  10913. (let ([y3 0])
  10914. (let ([tmp4 (begin
  10915. (set! y3 (read))
  10916. x2)])
  10917. (let ([tmp5 (begin
  10918. (set! x2 (read))
  10919. y3)])
  10920. (let ([tmp6 (+ tmp4 tmp5)])
  10921. (let ([tmp7 x2])
  10922. (+ tmp6 tmp7)))))))
  10923. \end{lstlisting}
  10924. \end{minipage}
  10925. \end{tabular}
  10926. \end{center}
  10927. \fi}
  10928. \section{Explicate Control \racket{and \LangCLoop{}}}
  10929. \label{sec:explicate-loop}
  10930. \newcommand{\CloopASTRacket}{
  10931. \begin{array}{lcl}
  10932. \Atm &::=& \VOID \\
  10933. \Stmt &::=& \READ{}
  10934. \end{array}
  10935. }
  10936. {\if\edition\racketEd
  10937. Recall that in the \code{explicate\_control} pass we define one helper
  10938. function for each kind of position in the program. For the \LangVar{}
  10939. language of integers and variables, we needed assignment and tail
  10940. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10941. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10942. another kind of position: effect position. Except for the last
  10943. subexpression, the subexpressions inside a \code{begin} are evaluated
  10944. only for their effect. Their result values are discarded. We can
  10945. generate better code by taking this fact into account.
  10946. The output language of \code{explicate\_control} is \LangCLoop{}
  10947. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10948. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10949. and that \code{read} may appear as a statement. The most significant
  10950. difference between the programs generated by \code{explicate\_control}
  10951. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10952. chapter is that the control-flow graphs of the latter may contain
  10953. cycles.
  10954. \begin{figure}[tp]
  10955. \begin{tcolorbox}[colback=white]
  10956. \small
  10957. \[
  10958. \begin{array}{l}
  10959. \gray{\CvarASTRacket} \\ \hline
  10960. \gray{\CifASTRacket} \\ \hline
  10961. \CloopASTRacket \\
  10962. \begin{array}{lcl}
  10963. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10964. \end{array}
  10965. \end{array}
  10966. \]
  10967. \end{tcolorbox}
  10968. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10969. \label{fig:c7-syntax}
  10970. \end{figure}
  10971. The new auxiliary function \code{explicate\_effect} takes an
  10972. expression (in an effect position) and the code for its
  10973. continuation. The function returns a $\Tail$ that includes the
  10974. generated code for the input expression followed by the
  10975. continuation. If the expression is obviously pure, that is, never
  10976. causes side effects, then the expression can be removed, so the result
  10977. is just the continuation.
  10978. %
  10979. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10980. interesting; the generated code is depicted in the following diagram:
  10981. \begin{center}
  10982. \begin{minipage}{0.3\textwidth}
  10983. \xymatrix{
  10984. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10985. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10986. & *+[F]{\txt{\itm{cont}}} \\
  10987. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10988. }
  10989. \end{minipage}
  10990. \end{center}
  10991. We start by creating a fresh label $\itm{loop}$ for the top of the
  10992. loop. Next, recursively process the \itm{body} (in effect position)
  10993. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10994. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10995. \itm{body'} as the \emph{then} branch and the continuation block as the
  10996. \emph{else} branch. The result should be added to the dictionary of
  10997. \code{basic-blocks} with the label \itm{loop}. The result for the
  10998. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10999. The auxiliary functions for tail, assignment, and predicate positions
  11000. need to be updated. The three new language forms, \code{while},
  11001. \code{set!}, and \code{begin}, can appear in assignment and tail
  11002. positions. Only \code{begin} may appear in predicate positions; the
  11003. other two have result type \code{Void}.
  11004. \fi}
  11005. %
  11006. {\if\edition\pythonEd\pythonColor
  11007. %
  11008. The output of this pass is the language \LangCIf{}. No new language
  11009. features are needed in the output, because a \code{while} loop can be
  11010. expressed in terms of \code{goto} and \code{if} statements, which are
  11011. already in \LangCIf{}.
  11012. %
  11013. Add a case for the \code{while} statement to the
  11014. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11015. the condition expression.
  11016. %
  11017. \fi}
  11018. {\if\edition\racketEd
  11019. \section{Select Instructions}
  11020. \label{sec:select-instructions-loop}
  11021. \index{subject}{select instructions}
  11022. Only two small additions are needed in the \code{select\_instructions}
  11023. pass to handle the changes to \LangCLoop{}. First, to handle the
  11024. addition of \VOID{} we simply translate it to \code{0}. Second,
  11025. \code{read} may appear as a stand-alone statement instead of
  11026. appearing only on the right-hand side of an assignment statement. The code
  11027. generation is nearly identical to the one for assignment; just leave
  11028. off the instruction for moving the result into the left-hand side.
  11029. \fi}
  11030. \section{Register Allocation}
  11031. \label{sec:register-allocation-loop}
  11032. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11033. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11034. which complicates the liveness analysis needed for register
  11035. allocation.
  11036. %
  11037. We recommend using the generic \code{analyze\_dataflow} function that
  11038. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11039. perform liveness analysis, replacing the code in
  11040. \code{uncover\_live} that processed the basic blocks in topological
  11041. order (section~\ref{sec:liveness-analysis-Lif}).
  11042. The \code{analyze\_dataflow} function has the following four parameters.
  11043. \begin{enumerate}
  11044. \item The first parameter \code{G} should be passed the transpose
  11045. of the control-flow graph.
  11046. \item The second parameter \code{transfer} should be passed a function
  11047. that applies liveness analysis to a basic block. It takes two
  11048. parameters: the label for the block to analyze and the live-after
  11049. set for that block. The transfer function should return the
  11050. live-before set for the block.
  11051. %
  11052. \racket{Also, as a side effect, it should update the block's
  11053. $\itm{info}$ with the liveness information for each instruction.}
  11054. %
  11055. \python{Also, as a side effect, it should update the live-before and
  11056. live-after sets for each instruction.}
  11057. %
  11058. To implement the \code{transfer} function, you should be able to
  11059. reuse the code you already have for analyzing basic blocks.
  11060. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11061. \code{bottom} and \code{join} for the lattice of abstract states,
  11062. that is, sets of locations. For liveness analysis, the bottom of the
  11063. lattice is the empty set, and the join operator is set union.
  11064. \end{enumerate}
  11065. \begin{figure}[tp]
  11066. \begin{tcolorbox}[colback=white]
  11067. {\if\edition\racketEd
  11068. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11069. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11070. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11071. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11072. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11073. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11074. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11075. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11076. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11077. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11078. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11079. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11080. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11081. \path[->,bend left=15] (Lfun) edge [above] node
  11082. {\ttfamily\footnotesize shrink} (Lfun-2);
  11083. \path[->,bend left=15] (Lfun-2) edge [above] node
  11084. {\ttfamily\footnotesize uniquify} (F1-4);
  11085. \path[->,bend left=15] (F1-4) edge [above] node
  11086. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11087. \path[->,bend left=15] (F1-5) edge [left] node
  11088. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11089. \path[->,bend left=10] (F1-6) edge [above] node
  11090. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11091. \path[->,bend left=15] (C3-2) edge [right] node
  11092. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11093. \path[->,bend right=15] (x86-2) edge [right] node
  11094. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11095. \path[->,bend right=15] (x86-2-1) edge [below] node
  11096. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11097. \path[->,bend right=15] (x86-2-2) edge [right] node
  11098. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11099. \path[->,bend left=15] (x86-3) edge [above] node
  11100. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11101. \path[->,bend left=15] (x86-4) edge [right] node
  11102. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11103. \end{tikzpicture}
  11104. \fi}
  11105. {\if\edition\pythonEd\pythonColor
  11106. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11107. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11108. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11109. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11110. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11111. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11112. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11113. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11114. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11115. \path[->,bend left=15] (Lfun) edge [above] node
  11116. {\ttfamily\footnotesize shrink} (Lfun-2);
  11117. \path[->,bend left=15] (Lfun-2) edge [above] node
  11118. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11119. \path[->,bend left=10] (F1-6) edge [right] node
  11120. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11121. \path[->,bend right=15] (C3-2) edge [right] node
  11122. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11123. \path[->,bend right=15] (x86-2) edge [below] node
  11124. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11125. \path[->,bend left=15] (x86-3) edge [above] node
  11126. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11127. \path[->,bend right=15] (x86-4) edge [below] node
  11128. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11129. \end{tikzpicture}
  11130. \fi}
  11131. \end{tcolorbox}
  11132. \caption{Diagram of the passes for \LangLoop{}.}
  11133. \label{fig:Lwhile-passes}
  11134. \end{figure}
  11135. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11136. for the compilation of \LangLoop{}.
  11137. % Further Reading: dataflow analysis
  11138. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11139. \chapter{Tuples and Garbage Collection}
  11140. \label{ch:Lvec}
  11141. \index{subject}{tuple}
  11142. \index{subject}{vector}
  11143. \setcounter{footnote}{0}
  11144. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11145. %% all the IR grammars are spelled out! \\ --Jeremy}
  11146. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11147. %% the root stack. \\ --Jeremy}
  11148. In this chapter we study the implementation of tuples\racket{, called
  11149. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11150. in which each element may have a different type.
  11151. %
  11152. This language feature is the first to use the computer's
  11153. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11154. indefinite; that is, a tuple lives forever from the programmer's
  11155. viewpoint. Of course, from an implementer's viewpoint, it is important
  11156. to reclaim the space associated with a tuple when it is no longer
  11157. needed, which is why we also study \emph{garbage collection}
  11158. \index{subject}{garbage collection} techniques in this chapter.
  11159. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11160. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11161. language (chapter~\ref{ch:Lwhile}) with tuples.
  11162. %
  11163. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11164. copying live tuples back and forth between two halves of the heap. The
  11165. garbage collector requires coordination with the compiler so that it
  11166. can find all the live tuples.
  11167. %
  11168. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11169. discuss the necessary changes and additions to the compiler passes,
  11170. including a new compiler pass named \code{expose\_allocation}.
  11171. \section{The \LangVec{} Language}
  11172. \label{sec:r3}
  11173. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11174. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11175. the definition of the abstract syntax.
  11176. %
  11177. \racket{The \LangVec{} language includes the forms \code{vector} for
  11178. creating a tuple, \code{vector-ref} for reading an element of a
  11179. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11180. \code{vector-length} for obtaining the number of elements of a
  11181. tuple.}
  11182. %
  11183. \python{The \LangVec{} language adds (1) tuple creation via a
  11184. comma-separated list of expressions; (2) accessing an element of a
  11185. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11186. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11187. comparison operator; and (4) obtaining the number of elements (the
  11188. length) of a tuple. In this chapter, we restrict access indices to
  11189. constant integers.}
  11190. %
  11191. The following program shows an example of the use of tuples. It creates a tuple
  11192. \code{t} containing the elements \code{40},
  11193. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11194. contains just \code{2}. The element at index $1$ of \code{t} is
  11195. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11196. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11197. to which we add \code{2}, the element at index $0$ of the tuple.
  11198. The result of the program is \code{42}.
  11199. %
  11200. {\if\edition\racketEd
  11201. \begin{lstlisting}
  11202. (let ([t (vector 40 #t (vector 2))])
  11203. (if (vector-ref t 1)
  11204. (+ (vector-ref t 0)
  11205. (vector-ref (vector-ref t 2) 0))
  11206. 44))
  11207. \end{lstlisting}
  11208. \fi}
  11209. {\if\edition\pythonEd\pythonColor
  11210. \begin{lstlisting}
  11211. t = 40, True, (2,)
  11212. print(t[0] + t[2][0] if t[1] else 44)
  11213. \end{lstlisting}
  11214. \fi}
  11215. \newcommand{\LtupGrammarRacket}{
  11216. \begin{array}{lcl}
  11217. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11218. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11219. \MID \LP\key{vector-length}\;\Exp\RP \\
  11220. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11221. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11222. \end{array}
  11223. }
  11224. \newcommand{\LtupASTRacket}{
  11225. \begin{array}{lcl}
  11226. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11227. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11228. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11229. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11230. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11231. \end{array}
  11232. }
  11233. \newcommand{\LtupGrammarPython}{
  11234. \begin{array}{rcl}
  11235. \itm{cmp} &::= & \key{is} \\
  11236. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11237. \end{array}
  11238. }
  11239. \newcommand{\LtupASTPython}{
  11240. \begin{array}{lcl}
  11241. \itm{cmp} &::= & \code{Is()} \\
  11242. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11243. &\MID& \LEN{\Exp}
  11244. \end{array}
  11245. }
  11246. \begin{figure}[tbp]
  11247. \centering
  11248. \begin{tcolorbox}[colback=white]
  11249. \small
  11250. {\if\edition\racketEd
  11251. \[
  11252. \begin{array}{l}
  11253. \gray{\LintGrammarRacket{}} \\ \hline
  11254. \gray{\LvarGrammarRacket{}} \\ \hline
  11255. \gray{\LifGrammarRacket{}} \\ \hline
  11256. \gray{\LwhileGrammarRacket} \\ \hline
  11257. \LtupGrammarRacket \\
  11258. \begin{array}{lcl}
  11259. \LangVecM{} &::=& \Exp
  11260. \end{array}
  11261. \end{array}
  11262. \]
  11263. \fi}
  11264. {\if\edition\pythonEd\pythonColor
  11265. \[
  11266. \begin{array}{l}
  11267. \gray{\LintGrammarPython{}} \\ \hline
  11268. \gray{\LvarGrammarPython{}} \\ \hline
  11269. \gray{\LifGrammarPython{}} \\ \hline
  11270. \gray{\LwhileGrammarPython} \\ \hline
  11271. \LtupGrammarPython \\
  11272. \begin{array}{rcl}
  11273. \LangVecM{} &::=& \Stmt^{*}
  11274. \end{array}
  11275. \end{array}
  11276. \]
  11277. \fi}
  11278. \end{tcolorbox}
  11279. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11280. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11281. \label{fig:Lvec-concrete-syntax}
  11282. \end{figure}
  11283. \begin{figure}[tp]
  11284. \centering
  11285. \begin{tcolorbox}[colback=white]
  11286. \small
  11287. {\if\edition\racketEd
  11288. \[
  11289. \begin{array}{l}
  11290. \gray{\LintOpAST} \\ \hline
  11291. \gray{\LvarASTRacket{}} \\ \hline
  11292. \gray{\LifASTRacket{}} \\ \hline
  11293. \gray{\LwhileASTRacket{}} \\ \hline
  11294. \LtupASTRacket{} \\
  11295. \begin{array}{lcl}
  11296. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11297. \end{array}
  11298. \end{array}
  11299. \]
  11300. \fi}
  11301. {\if\edition\pythonEd\pythonColor
  11302. \[
  11303. \begin{array}{l}
  11304. \gray{\LintASTPython} \\ \hline
  11305. \gray{\LvarASTPython} \\ \hline
  11306. \gray{\LifASTPython} \\ \hline
  11307. \gray{\LwhileASTPython} \\ \hline
  11308. \LtupASTPython \\
  11309. \begin{array}{lcl}
  11310. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11311. \end{array}
  11312. \end{array}
  11313. \]
  11314. \fi}
  11315. \end{tcolorbox}
  11316. \caption{The abstract syntax of \LangVec{}.}
  11317. \label{fig:Lvec-syntax}
  11318. \end{figure}
  11319. Tuples raise several interesting new issues. First, variable binding
  11320. performs a shallow copy in dealing with tuples, which means that
  11321. different variables can refer to the same tuple; that is, two
  11322. variables can be \emph{aliases}\index{subject}{alias} for the same
  11323. entity. Consider the following example, in which \code{t1} and
  11324. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11325. different tuple value with equal elements. The result of the
  11326. program is \code{42}.
  11327. \begin{center}
  11328. \begin{minipage}{0.96\textwidth}
  11329. {\if\edition\racketEd
  11330. \begin{lstlisting}
  11331. (let ([t1 (vector 3 7)])
  11332. (let ([t2 t1])
  11333. (let ([t3 (vector 3 7)])
  11334. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11335. 42
  11336. 0))))
  11337. \end{lstlisting}
  11338. \fi}
  11339. {\if\edition\pythonEd\pythonColor
  11340. \begin{lstlisting}
  11341. t1 = 3, 7
  11342. t2 = t1
  11343. t3 = 3, 7
  11344. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11345. \end{lstlisting}
  11346. \fi}
  11347. \end{minipage}
  11348. \end{center}
  11349. {\if\edition\racketEd
  11350. Whether two variables are aliased or not affects what happens
  11351. when the underlying tuple is mutated\index{subject}{mutation}.
  11352. Consider the following example in which \code{t1} and \code{t2}
  11353. again refer to the same tuple value.
  11354. \begin{center}
  11355. \begin{minipage}{0.96\textwidth}
  11356. \begin{lstlisting}
  11357. (let ([t1 (vector 3 7)])
  11358. (let ([t2 t1])
  11359. (let ([_ (vector-set! t2 0 42)])
  11360. (vector-ref t1 0))))
  11361. \end{lstlisting}
  11362. \end{minipage}
  11363. \end{center}
  11364. The mutation through \code{t2} is visible in referencing the tuple
  11365. from \code{t1}, so the result of this program is \code{42}.
  11366. \fi}
  11367. The next issue concerns the lifetime of tuples. When does a tuple's
  11368. lifetime end? Notice that \LangVec{} does not include an operation
  11369. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11370. to any notion of static scoping.
  11371. %
  11372. {\if\edition\racketEd
  11373. %
  11374. For example, the following program returns \code{42} even though the
  11375. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11376. that reads from the vector to which it was bound.
  11377. \begin{center}
  11378. \begin{minipage}{0.96\textwidth}
  11379. \begin{lstlisting}
  11380. (let ([v (vector (vector 44))])
  11381. (let ([x (let ([w (vector 42)])
  11382. (let ([_ (vector-set! v 0 w)])
  11383. 0))])
  11384. (+ x (vector-ref (vector-ref v 0) 0))))
  11385. \end{lstlisting}
  11386. \end{minipage}
  11387. \end{center}
  11388. \fi}
  11389. %
  11390. {\if\edition\pythonEd\pythonColor
  11391. %
  11392. For example, the following program returns \code{42} even though the
  11393. variable \code{x} goes out of scope when the function returns, prior
  11394. to reading the tuple element at index $0$. (We study the compilation
  11395. of functions in chapter~\ref{ch:Lfun}.)
  11396. %
  11397. \begin{center}
  11398. \begin{minipage}{0.96\textwidth}
  11399. \begin{lstlisting}
  11400. def f():
  11401. x = 42, 43
  11402. return x
  11403. t = f()
  11404. print(t[0])
  11405. \end{lstlisting}
  11406. \end{minipage}
  11407. \end{center}
  11408. \fi}
  11409. %
  11410. From the perspective of programmer-observable behavior, tuples live
  11411. forever. However, if they really lived forever then many long-running
  11412. programs would run out of memory. To solve this problem, the
  11413. language's runtime system performs automatic garbage collection.
  11414. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11415. \LangVec{} language.
  11416. %
  11417. \racket{We define the \code{vector}, \code{vector-ref},
  11418. \code{vector-set!}, and \code{vector-length} operations for
  11419. \LangVec{} in terms of the corresponding operations in Racket. One
  11420. subtle point is that the \code{vector-set!} operation returns the
  11421. \code{\#<void>} value.}
  11422. %
  11423. \python{We represent tuples with Python lists in the interpreter
  11424. because we need to write to them
  11425. (section~\ref{sec:expose-allocation}). (Python tuples are
  11426. immutable.) We define element access, the \code{is} operator, and
  11427. the \code{len} operator for \LangVec{} in terms of the corresponding
  11428. operations in Python.}
  11429. \begin{figure}[tbp]
  11430. \begin{tcolorbox}[colback=white]
  11431. {\if\edition\racketEd
  11432. \begin{lstlisting}
  11433. (define interp-Lvec-class
  11434. (class interp-Lwhile-class
  11435. (super-new)
  11436. (define/override (interp-op op)
  11437. (match op
  11438. ['eq? (lambda (v1 v2)
  11439. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11440. (and (boolean? v1) (boolean? v2))
  11441. (and (vector? v1) (vector? v2))
  11442. (and (void? v1) (void? v2)))
  11443. (eq? v1 v2)]))]
  11444. ['vector vector]
  11445. ['vector-length vector-length]
  11446. ['vector-ref vector-ref]
  11447. ['vector-set! vector-set!]
  11448. [else (super interp-op op)]
  11449. ))
  11450. (define/override ((interp-exp env) e)
  11451. (match e
  11452. [(HasType e t) ((interp-exp env) e)]
  11453. [else ((super interp-exp env) e)]
  11454. ))
  11455. ))
  11456. (define (interp-Lvec p)
  11457. (send (new interp-Lvec-class) interp-program p))
  11458. \end{lstlisting}
  11459. \fi}
  11460. %
  11461. {\if\edition\pythonEd\pythonColor
  11462. \begin{lstlisting}
  11463. class InterpLtup(InterpLwhile):
  11464. def interp_cmp(self, cmp):
  11465. match cmp:
  11466. case Is():
  11467. return lambda x, y: x is y
  11468. case _:
  11469. return super().interp_cmp(cmp)
  11470. def interp_exp(self, e, env):
  11471. match e:
  11472. case Tuple(es, Load()):
  11473. return tuple([self.interp_exp(e, env) for e in es])
  11474. case Subscript(tup, index, Load()):
  11475. t = self.interp_exp(tup, env)
  11476. n = self.interp_exp(index, env)
  11477. return t[n]
  11478. case _:
  11479. return super().interp_exp(e, env)
  11480. \end{lstlisting}
  11481. \fi}
  11482. \end{tcolorbox}
  11483. \caption{Interpreter for the \LangVec{} language.}
  11484. \label{fig:interp-Lvec}
  11485. \end{figure}
  11486. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11487. \LangVec{}.
  11488. %
  11489. The type of a tuple is a
  11490. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11491. type for each of its elements.
  11492. %
  11493. \racket{To create the s-expression for the \code{Vector} type, we use the
  11494. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11495. operator} \code{,@} to insert the list \code{t*} without its usual
  11496. start and end parentheses. \index{subject}{unquote-splicing}}
  11497. %
  11498. The type of accessing the ith element of a tuple is the ith element
  11499. type of the tuple's type, if there is one. If not, an error is
  11500. signaled. Note that the index \code{i} is required to be a constant
  11501. integer (and not, for example, a call to
  11502. \racket{\code{read}}\python{input\_int}) so that the type checker
  11503. can determine the element's type given the tuple type.
  11504. %
  11505. \racket{
  11506. Regarding writing an element to a tuple, the element's type must
  11507. be equal to the ith element type of the tuple's type.
  11508. The result type is \code{Void}.}
  11509. %% When allocating a tuple,
  11510. %% we need to know which elements of the tuple are themselves tuples for
  11511. %% the purposes of garbage collection. We can obtain this information
  11512. %% during type checking. The type checker shown in
  11513. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11514. %% expression; it also
  11515. %% %
  11516. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11517. %% where $T$ is the tuple's type.
  11518. %
  11519. %records the type of each tuple expression in a new field named \code{has\_type}.
  11520. \begin{figure}[tp]
  11521. \begin{tcolorbox}[colback=white]
  11522. {\if\edition\racketEd
  11523. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11524. (define type-check-Lvec-class
  11525. (class type-check-Lif-class
  11526. (super-new)
  11527. (inherit check-type-equal?)
  11528. (define/override (type-check-exp env)
  11529. (lambda (e)
  11530. (define recur (type-check-exp env))
  11531. (match e
  11532. [(Prim 'vector es)
  11533. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11534. (define t `(Vector ,@t*))
  11535. (values (Prim 'vector e*) t)]
  11536. [(Prim 'vector-ref (list e1 (Int i)))
  11537. (define-values (e1^ t) (recur e1))
  11538. (match t
  11539. [`(Vector ,ts ...)
  11540. (unless (and (0 . <= . i) (i . < . (length ts)))
  11541. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11542. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11543. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11544. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11545. (define-values (e-vec t-vec) (recur e1))
  11546. (define-values (e-elt^ t-elt) (recur elt))
  11547. (match t-vec
  11548. [`(Vector ,ts ...)
  11549. (unless (and (0 . <= . i) (i . < . (length ts)))
  11550. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11551. (check-type-equal? (list-ref ts i) t-elt e)
  11552. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11553. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11554. [(Prim 'vector-length (list e))
  11555. (define-values (e^ t) (recur e))
  11556. (match t
  11557. [`(Vector ,ts ...)
  11558. (values (Prim 'vector-length (list e^)) 'Integer)]
  11559. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11560. [(Prim 'eq? (list arg1 arg2))
  11561. (define-values (e1 t1) (recur arg1))
  11562. (define-values (e2 t2) (recur arg2))
  11563. (match* (t1 t2)
  11564. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11565. [(other wise) (check-type-equal? t1 t2 e)])
  11566. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11567. [else ((super type-check-exp env) e)]
  11568. )))
  11569. ))
  11570. (define (type-check-Lvec p)
  11571. (send (new type-check-Lvec-class) type-check-program p))
  11572. \end{lstlisting}
  11573. \fi}
  11574. {\if\edition\pythonEd\pythonColor
  11575. \begin{lstlisting}
  11576. class TypeCheckLtup(TypeCheckLwhile):
  11577. def type_check_exp(self, e, env):
  11578. match e:
  11579. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11580. l = self.type_check_exp(left, env)
  11581. r = self.type_check_exp(right, env)
  11582. check_type_equal(l, r, e)
  11583. return bool
  11584. case Tuple(es, Load()):
  11585. ts = [self.type_check_exp(e, env) for e in es]
  11586. e.has_type = TupleType(ts)
  11587. return e.has_type
  11588. case Subscript(tup, Constant(i), Load()):
  11589. tup_ty = self.type_check_exp(tup, env)
  11590. i_ty = self.type_check_exp(Constant(i), env)
  11591. check_type_equal(i_ty, int, i)
  11592. match tup_ty:
  11593. case TupleType(ts):
  11594. return ts[i]
  11595. case _:
  11596. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11597. case _:
  11598. return super().type_check_exp(e, env)
  11599. \end{lstlisting}
  11600. \fi}
  11601. \end{tcolorbox}
  11602. \caption{Type checker for the \LangVec{} language.}
  11603. \label{fig:type-check-Lvec}
  11604. \end{figure}
  11605. \section{Garbage Collection}
  11606. \label{sec:GC}
  11607. Garbage collection is a runtime technique for reclaiming space on the
  11608. heap that will not be used in the future of the running program. We
  11609. use the term \emph{object}\index{subject}{object} to refer to any
  11610. value that is stored in the heap, which for now includes only
  11611. tuples.%
  11612. %
  11613. \footnote{The term \emph{object} as it is used in the context of
  11614. object-oriented programming has a more specific meaning than the
  11615. way in which we use the term here.}
  11616. %
  11617. Unfortunately, it is impossible to know precisely which objects will
  11618. be accessed in the future and which will not. Instead, garbage
  11619. collectors overapproximate the set of objects that will be accessed by
  11620. identifying which objects can possibly be accessed. The running
  11621. program can directly access objects that are in registers and on the
  11622. procedure call stack. It can also transitively access the elements of
  11623. tuples, starting with a tuple whose address is in a register or on the
  11624. procedure call stack. We define the \emph{root
  11625. set}\index{subject}{root set} to be all the tuple addresses that are
  11626. in registers or on the procedure call stack. We define the \emph{live
  11627. objects}\index{subject}{live objects} to be the objects that are
  11628. reachable from the root set. Garbage collectors reclaim the space that
  11629. is allocated to objects that are no longer live. \index{subject}{allocate}
  11630. That means that some objects may not get reclaimed as soon as they could be,
  11631. but at least
  11632. garbage collectors do not reclaim the space dedicated to objects that
  11633. will be accessed in the future! The programmer can influence which
  11634. objects get reclaimed by causing them to become unreachable.
  11635. So the goal of the garbage collector is twofold:
  11636. \begin{enumerate}
  11637. \item to preserve all the live objects, and
  11638. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11639. \end{enumerate}
  11640. \subsection{Two-Space Copying Collector}
  11641. Here we study a relatively simple algorithm for garbage collection
  11642. that is the basis of many state-of-the-art garbage
  11643. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11644. particular, we describe a two-space copying
  11645. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11646. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11647. collector} \index{subject}{two-space copying collector}
  11648. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11649. what happens in a two-space collector, showing two time steps, prior
  11650. to garbage collection (on the top) and after garbage collection (on
  11651. the bottom). In a two-space collector, the heap is divided into two
  11652. parts named the FromSpace\index{subject}{FromSpace} and the
  11653. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11654. FromSpace until there is not enough room for the next allocation
  11655. request. At that point, the garbage collector goes to work to make
  11656. room for the next allocation.
  11657. A copying collector makes more room by copying all the live objects
  11658. from the FromSpace into the ToSpace and then performs a sleight of
  11659. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11660. as the new ToSpace. In the example shown in
  11661. figure~\ref{fig:copying-collector}, the root set consists of three
  11662. pointers, one in a register and two on the stack. All the live
  11663. objects have been copied to the ToSpace (the right-hand side of
  11664. figure~\ref{fig:copying-collector}) in a way that preserves the
  11665. pointer relationships. For example, the pointer in the register still
  11666. points to a tuple that in turn points to two other tuples. There are
  11667. four tuples that are not reachable from the root set and therefore do
  11668. not get copied into the ToSpace.
  11669. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11670. created by a well-typed program in \LangVec{} because it contains a
  11671. cycle. However, creating cycles will be possible once we get to
  11672. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11673. to deal with cycles to begin with, so we will not need to revisit this
  11674. issue.
  11675. \begin{figure}[tbp]
  11676. \centering
  11677. \begin{tcolorbox}[colback=white]
  11678. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11679. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11680. \\[5ex]
  11681. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11682. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11683. \end{tcolorbox}
  11684. \caption{A copying collector in action.}
  11685. \label{fig:copying-collector}
  11686. \end{figure}
  11687. \subsection{Graph Copying via Cheney's Algorithm}
  11688. \label{sec:cheney}
  11689. \index{subject}{Cheney's algorithm}
  11690. Let us take a closer look at the copying of the live objects. The
  11691. allocated\index{subject}{allocate} objects and pointers can be viewed
  11692. as a graph, and we need to copy the part of the graph that is
  11693. reachable from the root set. To make sure that we copy all the
  11694. reachable vertices in the graph, we need an exhaustive graph traversal
  11695. algorithm, such as depth-first search or breadth-first
  11696. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11697. take into account the possibility of cycles by marking which vertices
  11698. have already been visited, so to ensure termination of the
  11699. algorithm. These search algorithms also use a data structure such as a
  11700. stack or queue as a to-do list to keep track of the vertices that need
  11701. to be visited. We use breadth-first search and a trick due to
  11702. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11703. copying tuples into the ToSpace.
  11704. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11705. copy progresses. The queue is represented by a chunk of contiguous
  11706. memory at the beginning of the ToSpace, using two pointers to track
  11707. the front and the back of the queue, called the \emph{free pointer}
  11708. and the \emph{scan pointer}, respectively. The algorithm starts by
  11709. copying all tuples that are immediately reachable from the root set
  11710. into the ToSpace to form the initial queue. When we copy a tuple, we
  11711. mark the old tuple to indicate that it has been visited. We discuss
  11712. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11713. that any pointers inside the copied tuples in the queue still point
  11714. back to the FromSpace. Once the initial queue has been created, the
  11715. algorithm enters a loop in which it repeatedly processes the tuple at
  11716. the front of the queue and pops it off the queue. To process a tuple,
  11717. the algorithm copies all the objects that are directly reachable from it
  11718. to the ToSpace, placing them at the back of the queue. The algorithm
  11719. then updates the pointers in the popped tuple so that they point to the
  11720. newly copied objects.
  11721. \begin{figure}[tbp]
  11722. \centering
  11723. \begin{tcolorbox}[colback=white]
  11724. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11725. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11726. \end{tcolorbox}
  11727. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11728. \label{fig:cheney}
  11729. \end{figure}
  11730. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11731. tuple whose second element is $42$ to the back of the queue. The other
  11732. pointer goes to a tuple that has already been copied, so we do not
  11733. need to copy it again, but we do need to update the pointer to the new
  11734. location. This can be accomplished by storing a \emph{forwarding
  11735. pointer}\index{subject}{forwarding pointer} to the new location in the
  11736. old tuple, when we initially copied the tuple into the
  11737. ToSpace. This completes one step of the algorithm. The algorithm
  11738. continues in this way until the queue is empty; that is, when the scan
  11739. pointer catches up with the free pointer.
  11740. \subsection{Data Representation}
  11741. \label{sec:data-rep-gc}
  11742. The garbage collector places some requirements on the data
  11743. representations used by our compiler. First, the garbage collector
  11744. needs to distinguish between pointers and other kinds of data such as
  11745. integers. The following are several ways to accomplish this:
  11746. \begin{enumerate}
  11747. \item Attach a tag to each object that identifies what type of
  11748. object it is~\citep{McCarthy:1960dz}.
  11749. \item Store different types of objects in different
  11750. regions~\citep{Steele:1977ab}.
  11751. \item Use type information from the program to either (a) generate
  11752. type-specific code for collecting, or (b) generate tables that
  11753. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11754. \end{enumerate}
  11755. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11756. need to tag objects in any case, so option 1 is a natural choice for those
  11757. languages. However, \LangVec{} is a statically typed language, so it
  11758. would be unfortunate to require tags on every object, especially small
  11759. and pervasive objects like integers and Booleans. Option 3 is the
  11760. best-performing choice for statically typed languages, but it comes with
  11761. a relatively high implementation complexity. To keep this chapter
  11762. within a reasonable scope of complexity, we recommend a combination of options
  11763. 1 and 2, using separate strategies for the stack and the heap.
  11764. Regarding the stack, we recommend using a separate stack for pointers,
  11765. which we call the \emph{root stack}\index{subject}{root stack}
  11766. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11767. That is, when a local variable needs to be spilled and is of type
  11768. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11769. root stack instead of putting it on the procedure call
  11770. stack. Furthermore, we always spill tuple-typed variables if they are
  11771. live during a call to the collector, thereby ensuring that no pointers
  11772. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11773. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11774. contrasts it with the data layout using a root stack. The root stack
  11775. contains the two pointers from the regular stack and also the pointer
  11776. in the second register.
  11777. \begin{figure}[tbp]
  11778. \centering
  11779. \begin{tcolorbox}[colback=white]
  11780. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11781. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11782. \end{tcolorbox}
  11783. \caption{Maintaining a root stack to facilitate garbage collection.}
  11784. \label{fig:shadow-stack}
  11785. \end{figure}
  11786. The problem of distinguishing between pointers and other kinds of data
  11787. also arises inside each tuple on the heap. We solve this problem by
  11788. attaching a tag, an extra 64 bits, to each
  11789. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11790. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11791. Note that we have drawn the bits in a big-endian way, from right to left,
  11792. with bit location 0 (the least significant bit) on the far right,
  11793. which corresponds to the direction of the x86 shifting instructions
  11794. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11795. is dedicated to specifying which elements of the tuple are pointers,
  11796. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11797. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11798. data. The pointer mask starts at bit location 7. We limit tuples to a
  11799. maximum size of fifty elements, so we need 50 bits for the pointer
  11800. mask.%
  11801. %
  11802. \footnote{A production-quality compiler would handle
  11803. arbitrarily sized tuples and use a more complex approach.}
  11804. %
  11805. The tag also contains two other pieces of information. The length of
  11806. the tuple (number of elements) is stored in bits at locations 1 through
  11807. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11808. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11809. has not yet been copied. If the bit has value 0, then the entire tag
  11810. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11811. zero in any case, because our tuples are 8-byte aligned.)
  11812. \begin{figure}[tbp]
  11813. \centering
  11814. \begin{tcolorbox}[colback=white]
  11815. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11816. \end{tcolorbox}
  11817. \caption{Representation of tuples in the heap.}
  11818. \label{fig:tuple-rep}
  11819. \end{figure}
  11820. \subsection{Implementation of the Garbage Collector}
  11821. \label{sec:organize-gz}
  11822. \index{subject}{prelude}
  11823. An implementation of the copying collector is provided in the
  11824. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11825. interface to the garbage collector that is used by the compiler. The
  11826. \code{initialize} function creates the FromSpace, ToSpace, and root
  11827. stack and should be called in the prelude of the \code{main}
  11828. function. The arguments of \code{initialize} are the root stack size
  11829. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11830. good choice for both. The \code{initialize} function puts the address
  11831. of the beginning of the FromSpace into the global variable
  11832. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11833. the address that is one past the last element of the FromSpace. We use
  11834. half-open intervals to represent chunks of
  11835. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11836. points to the first element of the root stack.
  11837. As long as there is room left in the FromSpace, your generated code
  11838. can allocate\index{subject}{allocate} tuples simply by moving the
  11839. \code{free\_ptr} forward.
  11840. %
  11841. The amount of room left in the FromSpace is the difference between the
  11842. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11843. function should be called when there is not enough room left in the
  11844. FromSpace for the next allocation. The \code{collect} function takes
  11845. a pointer to the current top of the root stack (one past the last item
  11846. that was pushed) and the number of bytes that need to be
  11847. allocated. The \code{collect} function performs the copying collection
  11848. and leaves the heap in a state such that there is enough room for the
  11849. next allocation.
  11850. \begin{figure}[tbp]
  11851. \begin{tcolorbox}[colback=white]
  11852. \begin{lstlisting}
  11853. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11854. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11855. int64_t* free_ptr;
  11856. int64_t* fromspace_begin;
  11857. int64_t* fromspace_end;
  11858. int64_t** rootstack_begin;
  11859. \end{lstlisting}
  11860. \end{tcolorbox}
  11861. \caption{The compiler's interface to the garbage collector.}
  11862. \label{fig:gc-header}
  11863. \end{figure}
  11864. %% \begin{exercise}
  11865. %% In the file \code{runtime.c} you will find the implementation of
  11866. %% \code{initialize} and a partial implementation of \code{collect}.
  11867. %% The \code{collect} function calls another function, \code{cheney},
  11868. %% to perform the actual copy, and that function is left to the reader
  11869. %% to implement. The following is the prototype for \code{cheney}.
  11870. %% \begin{lstlisting}
  11871. %% static void cheney(int64_t** rootstack_ptr);
  11872. %% \end{lstlisting}
  11873. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11874. %% rootstack (which is an array of pointers). The \code{cheney} function
  11875. %% also communicates with \code{collect} through the global
  11876. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11877. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11878. %% the ToSpace:
  11879. %% \begin{lstlisting}
  11880. %% static int64_t* tospace_begin;
  11881. %% static int64_t* tospace_end;
  11882. %% \end{lstlisting}
  11883. %% The job of the \code{cheney} function is to copy all the live
  11884. %% objects (reachable from the root stack) into the ToSpace, update
  11885. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11886. %% update the root stack so that it points to the objects in the
  11887. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11888. %% and ToSpace.
  11889. %% \end{exercise}
  11890. The introduction of garbage collection has a nontrivial impact on our
  11891. compiler passes. We introduce a new compiler pass named
  11892. \code{expose\_allocation} that elaborates the code for allocating
  11893. tuples. We also make significant changes to
  11894. \code{select\_instructions}, \code{build\_interference},
  11895. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11896. make minor changes in several more passes.
  11897. The following program serves as our running example. It creates
  11898. two tuples, one nested inside the other. Both tuples have length
  11899. one. The program accesses the element in the inner tuple.
  11900. % tests/vectors_test_17.rkt
  11901. {\if\edition\racketEd
  11902. \begin{lstlisting}
  11903. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11904. \end{lstlisting}
  11905. \fi}
  11906. % tests/tuple/get_get.py
  11907. {\if\edition\pythonEd\pythonColor
  11908. \begin{lstlisting}
  11909. v1 = (42,)
  11910. v2 = (v1,)
  11911. print(v2[0][0])
  11912. \end{lstlisting}
  11913. \fi}
  11914. %% {\if\edition\racketEd
  11915. %% \section{Shrink}
  11916. %% \label{sec:shrink-Lvec}
  11917. %% Recall that the \code{shrink} pass translates the primitives operators
  11918. %% into a smaller set of primitives.
  11919. %% %
  11920. %% This pass comes after type checking, and the type checker adds a
  11921. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11922. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11923. %% \fi}
  11924. \section{Expose Allocation}
  11925. \label{sec:expose-allocation}
  11926. The pass \code{expose\_allocation} lowers tuple creation into making a
  11927. conditional call to the collector followed by allocating the
  11928. appropriate amount of memory and initializing it. We choose to place
  11929. the \code{expose\_allocation} pass before
  11930. \code{remove\_complex\_operands} because it generates
  11931. code that contains complex operands.
  11932. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11933. that replaces tuple creation with new lower-level forms that we use in the
  11934. translation of tuple creation.
  11935. %
  11936. {\if\edition\racketEd
  11937. \[
  11938. \begin{array}{lcl}
  11939. \Exp &::=& (\key{collect} \,\itm{int})
  11940. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11941. \MID (\key{global-value} \,\itm{name})
  11942. \end{array}
  11943. \]
  11944. \fi}
  11945. {\if\edition\pythonEd\pythonColor
  11946. \[
  11947. \begin{array}{lcl}
  11948. \Exp &::=& \cdots\\
  11949. &\MID& \key{collect}(\itm{int})
  11950. \MID \key{allocate}(\itm{int},\itm{type})
  11951. \MID \key{global\_value}(\itm{name}) \\
  11952. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11953. \end{array}
  11954. \]
  11955. \fi}
  11956. %
  11957. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11958. make sure that there are $n$ bytes ready to be allocated. During
  11959. instruction selection\index{subject}{instruction selection},
  11960. the \CCOLLECT{$n$} form will become a call to
  11961. the \code{collect} function in \code{runtime.c}.
  11962. %
  11963. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11964. space at the front for the 64-bit tag), but the elements are not
  11965. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11966. of the tuple:
  11967. %
  11968. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11969. %
  11970. where $\Type_i$ is the type of the $i$th element.
  11971. %
  11972. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11973. variable, such as \code{free\_ptr}.
  11974. \racket{
  11975. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11976. can be obtained by running the
  11977. \code{type-check-Lvec-has-type} type checker immediately before the
  11978. \code{expose\_allocation} pass. This version of the type checker
  11979. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11980. around each tuple creation. The concrete syntax
  11981. for \code{HasType} is \code{has-type}.}
  11982. The following shows the transformation of tuple creation into (1) a
  11983. sequence of temporary variable bindings for the initializing
  11984. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11985. \code{allocate}, and (4) the initialization of the tuple. The
  11986. \itm{len} placeholder refers to the length of the tuple, and
  11987. \itm{bytes} is the total number of bytes that need to be allocated for
  11988. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11989. %
  11990. \python{The \itm{type} needed for the second argument of the
  11991. \code{allocate} form can be obtained from the \code{has\_type} field
  11992. of the tuple AST node, which is stored there by running the type
  11993. checker for \LangVec{} immediately before this pass.}
  11994. %
  11995. \begin{center}
  11996. \begin{minipage}{\textwidth}
  11997. {\if\edition\racketEd
  11998. \begin{lstlisting}
  11999. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12000. |$\Longrightarrow$|
  12001. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12002. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12003. (global-value fromspace_end))
  12004. (void)
  12005. (collect |\itm{bytes}|))])
  12006. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12007. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12008. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12009. |$v$|) ... )))) ...)
  12010. \end{lstlisting}
  12011. \fi}
  12012. {\if\edition\pythonEd\pythonColor
  12013. \begin{lstlisting}
  12014. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12015. |$\Longrightarrow$|
  12016. begin:
  12017. |$x_0$| = |$e_0$|
  12018. |$\vdots$|
  12019. |$x_{n-1}$| = |$e_{n-1}$|
  12020. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12021. 0
  12022. else:
  12023. collect(|\itm{bytes}|)
  12024. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12025. |$v$|[0] = |$x_0$|
  12026. |$\vdots$|
  12027. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12028. |$v$|
  12029. \end{lstlisting}
  12030. \fi}
  12031. \end{minipage}
  12032. \end{center}
  12033. %
  12034. \noindent The sequencing of the initializing expressions
  12035. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12036. they may trigger garbage collection and we cannot have an allocated
  12037. but uninitialized tuple on the heap during a collection.
  12038. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12039. \code{expose\_allocation} pass on our running example.
  12040. \begin{figure}[tbp]
  12041. \begin{tcolorbox}[colback=white]
  12042. % tests/s2_17.rkt
  12043. {\if\edition\racketEd
  12044. \begin{lstlisting}
  12045. (vector-ref
  12046. (vector-ref
  12047. (let ([vecinit6
  12048. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12049. (global-value fromspace_end))
  12050. (void)
  12051. (collect 16))])
  12052. (let ([alloc2 (allocate 1 (Vector Integer))])
  12053. (let ([_3 (vector-set! alloc2 0 42)])
  12054. alloc2)))])
  12055. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12056. (global-value fromspace_end))
  12057. (void)
  12058. (collect 16))])
  12059. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12060. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12061. alloc5))))
  12062. 0)
  12063. 0)
  12064. \end{lstlisting}
  12065. \fi}
  12066. {\if\edition\pythonEd\pythonColor
  12067. \begin{lstlisting}
  12068. v1 = begin:
  12069. init.514 = 42
  12070. if (free_ptr + 16) < fromspace_end:
  12071. else:
  12072. collect(16)
  12073. alloc.513 = allocate(1,tuple[int])
  12074. alloc.513[0] = init.514
  12075. alloc.513
  12076. v2 = begin:
  12077. init.516 = v1
  12078. if (free_ptr + 16) < fromspace_end:
  12079. else:
  12080. collect(16)
  12081. alloc.515 = allocate(1,tuple[tuple[int]])
  12082. alloc.515[0] = init.516
  12083. alloc.515
  12084. print(v2[0][0])
  12085. \end{lstlisting}
  12086. \fi}
  12087. \end{tcolorbox}
  12088. \caption{Output of the \code{expose\_allocation} pass.}
  12089. \label{fig:expose-alloc-output}
  12090. \end{figure}
  12091. \section{Remove Complex Operands}
  12092. \label{sec:remove-complex-opera-Lvec}
  12093. {\if\edition\racketEd
  12094. %
  12095. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12096. should be treated as complex operands.
  12097. %
  12098. \fi}
  12099. %
  12100. {\if\edition\pythonEd\pythonColor
  12101. %
  12102. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12103. and tuple access should be treated as complex operands. The
  12104. subexpressions of tuple access must be atomic.
  12105. %
  12106. \fi}
  12107. %% A new case for
  12108. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12109. %% handled carefully to prevent the \code{Prim} node from being separated
  12110. %% from its enclosing \code{HasType}.
  12111. Figure~\ref{fig:Lvec-anf-syntax}
  12112. shows the grammar for the output language \LangAllocANF{} of this
  12113. pass, which is \LangAlloc{} in monadic normal form.
  12114. \newcommand{\LtupMonadASTRacket}{
  12115. \begin{array}{rcl}
  12116. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12117. \MID \GLOBALVALUE{\Var}
  12118. \end{array}
  12119. }
  12120. \newcommand{\LtupMonadASTPython}{
  12121. \begin{array}{rcl}
  12122. \Exp &::=& \GET{\Atm}{\Atm} \\
  12123. &\MID& \LEN{\Atm}\\
  12124. &\MID& \ALLOCATE{\Int}{\Type}
  12125. \MID \GLOBALVALUE{\Var} \\
  12126. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12127. &\MID& \COLLECT{\Int}
  12128. \end{array}
  12129. }
  12130. \begin{figure}[tp]
  12131. \centering
  12132. \begin{tcolorbox}[colback=white]
  12133. \small
  12134. {\if\edition\racketEd
  12135. \[
  12136. \begin{array}{l}
  12137. \gray{\LvarMonadASTRacket} \\ \hline
  12138. \gray{\LifMonadASTRacket} \\ \hline
  12139. \gray{\LwhileMonadASTRacket} \\ \hline
  12140. \LtupMonadASTRacket \\
  12141. \begin{array}{rcl}
  12142. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12143. \end{array}
  12144. \end{array}
  12145. \]
  12146. \fi}
  12147. {\if\edition\pythonEd\pythonColor
  12148. \[
  12149. \begin{array}{l}
  12150. \gray{\LvarMonadASTPython} \\ \hline
  12151. \gray{\LifMonadASTPython} \\ \hline
  12152. \gray{\LwhileMonadASTPython} \\ \hline
  12153. \LtupMonadASTPython \\
  12154. \begin{array}{rcl}
  12155. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12156. \end{array}
  12157. \end{array}
  12158. \]
  12159. \fi}
  12160. \end{tcolorbox}
  12161. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12162. \label{fig:Lvec-anf-syntax}
  12163. \end{figure}
  12164. \section{Explicate Control and the \LangCVec{} Language}
  12165. \label{sec:explicate-control-r3}
  12166. \newcommand{\CtupASTRacket}{
  12167. \begin{array}{lcl}
  12168. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12169. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12170. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12171. &\MID& \VECLEN{\Atm} \\
  12172. &\MID& \GLOBALVALUE{\Var} \\
  12173. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12174. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12175. \end{array}
  12176. }
  12177. \newcommand{\CtupASTPython}{
  12178. \begin{array}{lcl}
  12179. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12180. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12181. \Stmt &::=& \COLLECT{\Int} \\
  12182. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12183. \end{array}
  12184. }
  12185. \begin{figure}[tp]
  12186. \begin{tcolorbox}[colback=white]
  12187. \small
  12188. {\if\edition\racketEd
  12189. \[
  12190. \begin{array}{l}
  12191. \gray{\CvarASTRacket} \\ \hline
  12192. \gray{\CifASTRacket} \\ \hline
  12193. \gray{\CloopASTRacket} \\ \hline
  12194. \CtupASTRacket \\
  12195. \begin{array}{lcl}
  12196. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12197. \end{array}
  12198. \end{array}
  12199. \]
  12200. \fi}
  12201. {\if\edition\pythonEd\pythonColor
  12202. \[
  12203. \begin{array}{l}
  12204. \gray{\CifASTPython} \\ \hline
  12205. \CtupASTPython \\
  12206. \begin{array}{lcl}
  12207. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12208. \end{array}
  12209. \end{array}
  12210. \]
  12211. \fi}
  12212. \end{tcolorbox}
  12213. \caption{The abstract syntax of \LangCVec{}, extending
  12214. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12215. (figure~\ref{fig:c1-syntax})}.}
  12216. \label{fig:c2-syntax}
  12217. \end{figure}
  12218. The output of \code{explicate\_control} is a program in the
  12219. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12220. shows the definition of the abstract syntax.
  12221. %
  12222. %% \racket{(The concrete syntax is defined in
  12223. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12224. %
  12225. The new expressions of \LangCVec{} include \key{allocate},
  12226. %
  12227. \racket{\key{vector-ref}, and \key{vector-set!},}
  12228. %
  12229. \python{accessing tuple elements,}
  12230. %
  12231. and \key{global\_value}.
  12232. %
  12233. \python{\LangCVec{} also includes the \code{collect} statement and
  12234. assignment to a tuple element.}
  12235. %
  12236. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12237. %
  12238. The \code{explicate\_control} pass can treat these new forms much like
  12239. the other forms that we've already encountered. The output of the
  12240. \code{explicate\_control} pass on the running example is shown on the
  12241. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12242. section.
  12243. \section{Select Instructions and the \LangXGlobal{} Language}
  12244. \label{sec:select-instructions-gc}
  12245. \index{subject}{select instructions}
  12246. %% void (rep as zero)
  12247. %% allocate
  12248. %% collect (callq collect)
  12249. %% vector-ref
  12250. %% vector-set!
  12251. %% vector-length
  12252. %% global (postpone)
  12253. In this pass we generate x86 code for most of the new operations that
  12254. are needed to compile tuples, including \code{Allocate},
  12255. \code{Collect}, and accessing tuple elements.
  12256. %
  12257. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12258. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12259. \ref{fig:x86-2}). \index{subject}{x86}
  12260. The tuple read and write forms translate into \code{movq}
  12261. instructions. (The $+1$ in the offset serves to move past the tag at the
  12262. beginning of the tuple representation.)
  12263. %
  12264. \begin{center}
  12265. \begin{minipage}{\textwidth}
  12266. {\if\edition\racketEd
  12267. \begin{lstlisting}
  12268. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12269. |$\Longrightarrow$|
  12270. movq |$\itm{tup}'$|, %r11
  12271. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12272. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12273. |$\Longrightarrow$|
  12274. movq |$\itm{tup}'$|, %r11
  12275. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12276. movq $0, |$\itm{lhs'}$|
  12277. \end{lstlisting}
  12278. \fi}
  12279. {\if\edition\pythonEd\pythonColor
  12280. \begin{lstlisting}
  12281. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12282. |$\Longrightarrow$|
  12283. movq |$\itm{tup}'$|, %r11
  12284. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12285. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12286. |$\Longrightarrow$|
  12287. movq |$\itm{tup}'$|, %r11
  12288. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12289. \end{lstlisting}
  12290. \fi}
  12291. \end{minipage}
  12292. \end{center}
  12293. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12294. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12295. are obtained by translating from \LangCVec{} to x86.
  12296. %
  12297. The move of $\itm{tup}'$ to
  12298. register \code{r11} ensures that the offset expression
  12299. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12300. removing \code{r11} from consideration by the register allocating.
  12301. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12302. \code{rax}. Then the generated code for tuple assignment would be
  12303. \begin{lstlisting}
  12304. movq |$\itm{tup}'$|, %rax
  12305. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12306. \end{lstlisting}
  12307. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12308. \code{patch\_instructions} would insert a move through \code{rax}
  12309. as follows:
  12310. \begin{lstlisting}
  12311. movq |$\itm{tup}'$|, %rax
  12312. movq |$\itm{rhs}'$|, %rax
  12313. movq %rax, |$8(n+1)$|(%rax)
  12314. \end{lstlisting}
  12315. However, this sequence of instructions does not work because we're
  12316. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12317. $\itm{rhs}'$) at the same time!
  12318. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12319. be translated into a sequence of instructions that read the tag of the
  12320. tuple and extract the 6 bits that represent the tuple length, which
  12321. are the bits starting at index 1 and going up to and including bit 6.
  12322. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12323. (shift right) can be used to accomplish this.
  12324. We compile the \code{allocate} form to operations on the
  12325. \code{free\_ptr}, as shown next. This approach is called
  12326. \emph{inline allocation} because it implements allocation without a
  12327. function call by simply incrementing the allocation pointer. It is much
  12328. more efficient than calling a function for each allocation. The
  12329. address in the \code{free\_ptr} is the next free address in the
  12330. FromSpace, so we copy it into \code{r11} and then move it forward by
  12331. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12332. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12333. the tag. We then initialize the \itm{tag} and finally copy the
  12334. address in \code{r11} to the left-hand side. Refer to
  12335. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12336. %
  12337. \racket{We recommend using the Racket operations
  12338. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12339. during compilation.}
  12340. %
  12341. \python{We recommend using the bitwise-or operator \code{|} and the
  12342. shift-left operator \code{<<} to compute the tag during
  12343. compilation.}
  12344. %
  12345. The type annotation in the \code{allocate} form is used to determine
  12346. the pointer mask region of the tag.
  12347. %
  12348. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12349. address of the \code{free\_ptr} global variable using a special
  12350. instruction-pointer-relative addressing mode of the x86-64 processor.
  12351. In particular, the assembler computes the distance $d$ between the
  12352. address of \code{free\_ptr} and where the \code{rip} would be at that
  12353. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12354. \code{$d$(\%rip)}, which at runtime will compute the address of
  12355. \code{free\_ptr}.
  12356. %
  12357. {\if\edition\racketEd
  12358. \begin{lstlisting}
  12359. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12360. |$\Longrightarrow$|
  12361. movq free_ptr(%rip), %r11
  12362. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12363. movq $|$\itm{tag}$|, 0(%r11)
  12364. movq %r11, |$\itm{lhs}'$|
  12365. \end{lstlisting}
  12366. \fi}
  12367. {\if\edition\pythonEd\pythonColor
  12368. \begin{lstlisting}
  12369. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12370. |$\Longrightarrow$|
  12371. movq free_ptr(%rip), %r11
  12372. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12373. movq $|$\itm{tag}$|, 0(%r11)
  12374. movq %r11, |$\itm{lhs}'$|
  12375. \end{lstlisting}
  12376. \fi}
  12377. %
  12378. The \code{collect} form is compiled to a call to the \code{collect}
  12379. function in the runtime. The arguments to \code{collect} are (1) the
  12380. top of the root stack, and (2) the number of bytes that need to be
  12381. allocated. We use another dedicated register, \code{r15}, to store
  12382. the pointer to the top of the root stack. Therefore \code{r15} is not
  12383. available for use by the register allocator.
  12384. %
  12385. {\if\edition\racketEd
  12386. \begin{lstlisting}
  12387. (collect |$\itm{bytes}$|)
  12388. |$\Longrightarrow$|
  12389. movq %r15, %rdi
  12390. movq $|\itm{bytes}|, %rsi
  12391. callq collect
  12392. \end{lstlisting}
  12393. \fi}
  12394. {\if\edition\pythonEd\pythonColor
  12395. \begin{lstlisting}
  12396. collect(|$\itm{bytes}$|)
  12397. |$\Longrightarrow$|
  12398. movq %r15, %rdi
  12399. movq $|\itm{bytes}|, %rsi
  12400. callq collect
  12401. \end{lstlisting}
  12402. \fi}
  12403. \newcommand{\GrammarXGlobal}{
  12404. \begin{array}{lcl}
  12405. \Arg &::=& \itm{label} \key{(\%rip)}
  12406. \end{array}
  12407. }
  12408. \newcommand{\ASTXGlobalRacket}{
  12409. \begin{array}{lcl}
  12410. \Arg &::=& \GLOBAL{\itm{label}}
  12411. \end{array}
  12412. }
  12413. \begin{figure}[tp]
  12414. \begin{tcolorbox}[colback=white]
  12415. \[
  12416. \begin{array}{l}
  12417. \gray{\GrammarXInt} \\ \hline
  12418. \gray{\GrammarXIf} \\ \hline
  12419. \GrammarXGlobal \\
  12420. \begin{array}{lcl}
  12421. \LangXGlobalM{} &::= & \key{.globl main} \\
  12422. & & \key{main:} \; \Instr^{*}
  12423. \end{array}
  12424. \end{array}
  12425. \]
  12426. \end{tcolorbox}
  12427. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12428. \label{fig:x86-2-concrete}
  12429. \end{figure}
  12430. \begin{figure}[tp]
  12431. \begin{tcolorbox}[colback=white]
  12432. \small
  12433. {\if\edition\racketEd
  12434. \[
  12435. \begin{array}{l}
  12436. \gray{\ASTXIntRacket} \\ \hline
  12437. \gray{\ASTXIfRacket} \\ \hline
  12438. \ASTXGlobalRacket \\
  12439. \begin{array}{lcl}
  12440. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12441. \end{array}
  12442. \end{array}
  12443. \]
  12444. \fi}
  12445. {\if\edition\pythonEd\pythonColor
  12446. \[
  12447. \begin{array}{l}
  12448. \gray{\ASTXIntPython} \\ \hline
  12449. \gray{\ASTXIfPython} \\ \hline
  12450. \ASTXGlobalRacket \\
  12451. \begin{array}{lcl}
  12452. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12453. \end{array}
  12454. \end{array}
  12455. \]
  12456. \fi}
  12457. \end{tcolorbox}
  12458. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12459. \label{fig:x86-2}
  12460. \end{figure}
  12461. The definitions of the concrete and abstract syntax of the
  12462. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12463. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12464. of global variables.
  12465. %
  12466. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12467. \code{select\_instructions} pass on the running example.
  12468. \begin{figure}[tbp]
  12469. \centering
  12470. \begin{tcolorbox}[colback=white]
  12471. {\if\edition\racketEd
  12472. % tests/s2_17.rkt
  12473. \begin{tabular}{lll}
  12474. \begin{minipage}{0.5\textwidth}
  12475. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12476. start:
  12477. tmp9 = (global-value free_ptr);
  12478. tmp0 = (+ tmp9 16);
  12479. tmp1 = (global-value fromspace_end);
  12480. if (< tmp0 tmp1)
  12481. goto block0;
  12482. else
  12483. goto block1;
  12484. block0:
  12485. _4 = (void);
  12486. goto block9;
  12487. block1:
  12488. (collect 16)
  12489. goto block9;
  12490. block9:
  12491. alloc2 = (allocate 1 (Vector Integer));
  12492. _3 = (vector-set! alloc2 0 42);
  12493. vecinit6 = alloc2;
  12494. tmp2 = (global-value free_ptr);
  12495. tmp3 = (+ tmp2 16);
  12496. tmp4 = (global-value fromspace_end);
  12497. if (< tmp3 tmp4)
  12498. goto block7;
  12499. else
  12500. goto block8;
  12501. block7:
  12502. _8 = (void);
  12503. goto block6;
  12504. block8:
  12505. (collect 16)
  12506. goto block6;
  12507. block6:
  12508. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12509. _7 = (vector-set! alloc5 0 vecinit6);
  12510. tmp5 = (vector-ref alloc5 0);
  12511. return (vector-ref tmp5 0);
  12512. \end{lstlisting}
  12513. \end{minipage}
  12514. &$\Rightarrow$&
  12515. \begin{minipage}{0.4\textwidth}
  12516. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12517. start:
  12518. movq free_ptr(%rip), tmp9
  12519. movq tmp9, tmp0
  12520. addq $16, tmp0
  12521. movq fromspace_end(%rip), tmp1
  12522. cmpq tmp1, tmp0
  12523. jl block0
  12524. jmp block1
  12525. block0:
  12526. movq $0, _4
  12527. jmp block9
  12528. block1:
  12529. movq %r15, %rdi
  12530. movq $16, %rsi
  12531. callq collect
  12532. jmp block9
  12533. block9:
  12534. movq free_ptr(%rip), %r11
  12535. addq $16, free_ptr(%rip)
  12536. movq $3, 0(%r11)
  12537. movq %r11, alloc2
  12538. movq alloc2, %r11
  12539. movq $42, 8(%r11)
  12540. movq $0, _3
  12541. movq alloc2, vecinit6
  12542. movq free_ptr(%rip), tmp2
  12543. movq tmp2, tmp3
  12544. addq $16, tmp3
  12545. movq fromspace_end(%rip), tmp4
  12546. cmpq tmp4, tmp3
  12547. jl block7
  12548. jmp block8
  12549. block7:
  12550. movq $0, _8
  12551. jmp block6
  12552. block8:
  12553. movq %r15, %rdi
  12554. movq $16, %rsi
  12555. callq collect
  12556. jmp block6
  12557. block6:
  12558. movq free_ptr(%rip), %r11
  12559. addq $16, free_ptr(%rip)
  12560. movq $131, 0(%r11)
  12561. movq %r11, alloc5
  12562. movq alloc5, %r11
  12563. movq vecinit6, 8(%r11)
  12564. movq $0, _7
  12565. movq alloc5, %r11
  12566. movq 8(%r11), tmp5
  12567. movq tmp5, %r11
  12568. movq 8(%r11), %rax
  12569. jmp conclusion
  12570. \end{lstlisting}
  12571. \end{minipage}
  12572. \end{tabular}
  12573. \fi}
  12574. {\if\edition\pythonEd
  12575. % tests/tuple/get_get.py
  12576. \begin{tabular}{lll}
  12577. \begin{minipage}{0.5\textwidth}
  12578. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12579. start:
  12580. init.514 = 42
  12581. tmp.517 = free_ptr
  12582. tmp.518 = (tmp.517 + 16)
  12583. tmp.519 = fromspace_end
  12584. if tmp.518 < tmp.519:
  12585. goto block.529
  12586. else:
  12587. goto block.530
  12588. block.529:
  12589. goto block.528
  12590. block.530:
  12591. collect(16)
  12592. goto block.528
  12593. block.528:
  12594. alloc.513 = allocate(1,tuple[int])
  12595. alloc.513:tuple[int][0] = init.514
  12596. v1 = alloc.513
  12597. init.516 = v1
  12598. tmp.520 = free_ptr
  12599. tmp.521 = (tmp.520 + 16)
  12600. tmp.522 = fromspace_end
  12601. if tmp.521 < tmp.522:
  12602. goto block.526
  12603. else:
  12604. goto block.527
  12605. block.526:
  12606. goto block.525
  12607. block.527:
  12608. collect(16)
  12609. goto block.525
  12610. block.525:
  12611. alloc.515 = allocate(1,tuple[tuple[int]])
  12612. alloc.515:tuple[tuple[int]][0] = init.516
  12613. v2 = alloc.515
  12614. tmp.523 = v2[0]
  12615. tmp.524 = tmp.523[0]
  12616. print(tmp.524)
  12617. return 0
  12618. \end{lstlisting}
  12619. \end{minipage}
  12620. &$\Rightarrow$&
  12621. \begin{minipage}{0.4\textwidth}
  12622. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12623. start:
  12624. movq $42, init.514
  12625. movq free_ptr(%rip), tmp.517
  12626. movq tmp.517, tmp.518
  12627. addq $16, tmp.518
  12628. movq fromspace_end(%rip), tmp.519
  12629. cmpq tmp.519, tmp.518
  12630. jl block.529
  12631. jmp block.530
  12632. block.529:
  12633. jmp block.528
  12634. block.530:
  12635. movq %r15, %rdi
  12636. movq $16, %rsi
  12637. callq collect
  12638. jmp block.528
  12639. block.528:
  12640. movq free_ptr(%rip), %r11
  12641. addq $16, free_ptr(%rip)
  12642. movq $3, 0(%r11)
  12643. movq %r11, alloc.513
  12644. movq alloc.513, %r11
  12645. movq init.514, 8(%r11)
  12646. movq alloc.513, v1
  12647. movq v1, init.516
  12648. movq free_ptr(%rip), tmp.520
  12649. movq tmp.520, tmp.521
  12650. addq $16, tmp.521
  12651. movq fromspace_end(%rip), tmp.522
  12652. cmpq tmp.522, tmp.521
  12653. jl block.526
  12654. jmp block.527
  12655. block.526:
  12656. jmp block.525
  12657. block.527:
  12658. movq %r15, %rdi
  12659. movq $16, %rsi
  12660. callq collect
  12661. jmp block.525
  12662. block.525:
  12663. movq free_ptr(%rip), %r11
  12664. addq $16, free_ptr(%rip)
  12665. movq $131, 0(%r11)
  12666. movq %r11, alloc.515
  12667. movq alloc.515, %r11
  12668. movq init.516, 8(%r11)
  12669. movq alloc.515, v2
  12670. movq v2, %r11
  12671. movq 8(%r11), %r11
  12672. movq %r11, tmp.523
  12673. movq tmp.523, %r11
  12674. movq 8(%r11), %r11
  12675. movq %r11, tmp.524
  12676. movq tmp.524, %rdi
  12677. callq print_int
  12678. movq $0, %rax
  12679. jmp conclusion
  12680. \end{lstlisting}
  12681. \end{minipage}
  12682. \end{tabular}
  12683. \fi}
  12684. \end{tcolorbox}
  12685. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12686. \code{select\_instructions} (\emph{right}) on the running example.}
  12687. \label{fig:select-instr-output-gc}
  12688. \end{figure}
  12689. \clearpage
  12690. \section{Register Allocation}
  12691. \label{sec:reg-alloc-gc}
  12692. \index{subject}{register allocation}
  12693. As discussed previously in this chapter, the garbage collector needs to
  12694. access all the pointers in the root set, that is, all variables that
  12695. are tuples. It will be the responsibility of the register allocator
  12696. to make sure that
  12697. \begin{enumerate}
  12698. \item the root stack is used for spilling tuple-typed variables, and
  12699. \item if a tuple-typed variable is live during a call to the
  12700. collector, it must be spilled to ensure that it is visible to the
  12701. collector.
  12702. \end{enumerate}
  12703. The latter responsibility can be handled during construction of the
  12704. interference graph, by adding interference edges between the call-live
  12705. tuple-typed variables and all the callee-saved registers. (They
  12706. already interfere with the caller-saved registers.)
  12707. %
  12708. \racket{The type information for variables is in the \code{Program}
  12709. form, so we recommend adding another parameter to the
  12710. \code{build\_interference} function to communicate this alist.}
  12711. %
  12712. \python{The type information for variables is generated by the type
  12713. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12714. the \code{CProgram} AST mode. You'll need to propagate that
  12715. information so that it is available in this pass.}
  12716. The spilling of tuple-typed variables to the root stack can be handled
  12717. after graph coloring, in choosing how to assign the colors
  12718. (integers) to registers and stack locations. The
  12719. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12720. changes to also record the number of spills to the root stack.
  12721. % build-interference
  12722. %
  12723. % callq
  12724. % extra parameter for var->type assoc. list
  12725. % update 'program' and 'if'
  12726. % allocate-registers
  12727. % allocate spilled vectors to the rootstack
  12728. % don't change color-graph
  12729. % TODO:
  12730. %\section{Patch Instructions}
  12731. %[mention that global variables are memory references]
  12732. \section{Prelude and Conclusion}
  12733. \label{sec:print-x86-gc}
  12734. \label{sec:prelude-conclusion-x86-gc}
  12735. \index{subject}{prelude}\index{subject}{conclusion}
  12736. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12737. \code{prelude\_and\_conclusion} pass on the running example. In the
  12738. prelude of the \code{main} function, we allocate space
  12739. on the root stack to make room for the spills of tuple-typed
  12740. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12741. taking care that the root stack grows up instead of down. For the
  12742. running example, there was just one spill, so we increment \code{r15}
  12743. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12744. One issue that deserves special care is that there may be a call to
  12745. \code{collect} prior to the initializing assignments for all the
  12746. variables in the root stack. We do not want the garbage collector to
  12747. mistakenly determine that some uninitialized variable is a pointer that
  12748. needs to be followed. Thus, we zero out all locations on the root
  12749. stack in the prelude of \code{main}. In
  12750. figure~\ref{fig:print-x86-output-gc}, the instruction
  12751. %
  12752. \lstinline{movq $0, 0(%r15)}
  12753. %
  12754. is sufficient to accomplish this task because there is only one spill.
  12755. In general, we have to clear as many words as there are spills of
  12756. tuple-typed variables. The garbage collector tests each root to see
  12757. if it is null prior to dereferencing it.
  12758. \begin{figure}[htbp]
  12759. \begin{tcolorbox}[colback=white]
  12760. {\if\edition\racketEd
  12761. \begin{minipage}[t]{0.5\textwidth}
  12762. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12763. .globl main
  12764. main:
  12765. pushq %rbp
  12766. movq %rsp, %rbp
  12767. subq $0, %rsp
  12768. movq $65536, %rdi
  12769. movq $65536, %rsi
  12770. callq initialize
  12771. movq rootstack_begin(%rip), %r15
  12772. movq $0, 0(%r15)
  12773. addq $8, %r15
  12774. jmp start
  12775. conclusion:
  12776. subq $8, %r15
  12777. addq $0, %rsp
  12778. popq %rbp
  12779. retq
  12780. \end{lstlisting}
  12781. \end{minipage}
  12782. \fi}
  12783. {\if\edition\pythonEd
  12784. \begin{minipage}[t]{0.5\textwidth}
  12785. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12786. .globl main
  12787. main:
  12788. pushq %rbp
  12789. movq %rsp, %rbp
  12790. pushq %rbx
  12791. subq $8, %rsp
  12792. movq $65536, %rdi
  12793. movq $16, %rsi
  12794. callq initialize
  12795. movq rootstack_begin(%rip), %r15
  12796. movq $0, 0(%r15)
  12797. addq $8, %r15
  12798. jmp start
  12799. conclusion:
  12800. subq $8, %r15
  12801. addq $8, %rsp
  12802. popq %rbx
  12803. popq %rbp
  12804. retq
  12805. \end{lstlisting}
  12806. \end{minipage}
  12807. \fi}
  12808. \end{tcolorbox}
  12809. \caption{The prelude and conclusion for the running example.}
  12810. \label{fig:print-x86-output-gc}
  12811. \end{figure}
  12812. \begin{figure}[tbp]
  12813. \begin{tcolorbox}[colback=white]
  12814. {\if\edition\racketEd
  12815. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12816. \node (Lvec) at (0,2) {\large \LangVec{}};
  12817. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12818. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12819. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12820. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12821. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12822. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12823. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12824. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12825. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12826. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12827. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12828. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12829. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12830. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12831. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12832. \path[->,bend left=15] (Lvec-4) edge [right] node
  12833. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12834. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12835. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12836. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12837. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12838. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12839. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12840. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12841. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12842. \end{tikzpicture}
  12843. \fi}
  12844. {\if\edition\pythonEd\pythonColor
  12845. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12846. \node (Lvec) at (0,2) {\large \LangVec{}};
  12847. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12848. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12849. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12850. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12851. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12852. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12853. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12854. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12855. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12856. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12857. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12858. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12859. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12860. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12861. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12862. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12863. \end{tikzpicture}
  12864. \fi}
  12865. \end{tcolorbox}
  12866. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12867. \label{fig:Lvec-passes}
  12868. \end{figure}
  12869. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12870. for the compilation of \LangVec{}.
  12871. \clearpage
  12872. {\if\edition\racketEd
  12873. \section{Challenge: Simple Structures}
  12874. \label{sec:simple-structures}
  12875. \index{subject}{struct}
  12876. \index{subject}{structure}
  12877. The language \LangStruct{} extends \LangVec{} with support for simple
  12878. structures. The definition of its concrete syntax is shown in
  12879. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12880. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12881. in Typed Racket is a user-defined data type that contains named fields
  12882. and that is heap allocated\index{subject}{heap allocated},
  12883. similarly to a vector. The following is an
  12884. example of a structure definition, in this case the definition of a
  12885. \code{point} type:
  12886. \begin{lstlisting}
  12887. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12888. \end{lstlisting}
  12889. \newcommand{\LstructGrammarRacket}{
  12890. \begin{array}{lcl}
  12891. \Type &::=& \Var \\
  12892. \Exp &::=& (\Var\;\Exp \ldots)\\
  12893. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12894. \end{array}
  12895. }
  12896. \newcommand{\LstructASTRacket}{
  12897. \begin{array}{lcl}
  12898. \Type &::=& \VAR{\Var} \\
  12899. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12900. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12901. \end{array}
  12902. }
  12903. \begin{figure}[tbp]
  12904. \centering
  12905. \begin{tcolorbox}[colback=white]
  12906. \[
  12907. \begin{array}{l}
  12908. \gray{\LintGrammarRacket{}} \\ \hline
  12909. \gray{\LvarGrammarRacket{}} \\ \hline
  12910. \gray{\LifGrammarRacket{}} \\ \hline
  12911. \gray{\LwhileGrammarRacket} \\ \hline
  12912. \gray{\LtupGrammarRacket} \\ \hline
  12913. \LstructGrammarRacket \\
  12914. \begin{array}{lcl}
  12915. \LangStruct{} &::=& \Def \ldots \; \Exp
  12916. \end{array}
  12917. \end{array}
  12918. \]
  12919. \end{tcolorbox}
  12920. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12921. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12922. \label{fig:Lstruct-concrete-syntax}
  12923. \end{figure}
  12924. \begin{figure}[tbp]
  12925. \centering
  12926. \begin{tcolorbox}[colback=white]
  12927. \small
  12928. \[
  12929. \begin{array}{l}
  12930. \gray{\LintASTRacket{}} \\ \hline
  12931. \gray{\LvarASTRacket{}} \\ \hline
  12932. \gray{\LifASTRacket{}} \\ \hline
  12933. \gray{\LwhileASTRacket} \\ \hline
  12934. \gray{\LtupASTRacket} \\ \hline
  12935. \LstructASTRacket \\
  12936. \begin{array}{lcl}
  12937. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12938. \end{array}
  12939. \end{array}
  12940. \]
  12941. \end{tcolorbox}
  12942. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12943. (figure~\ref{fig:Lvec-syntax}).}
  12944. \label{fig:Lstruct-syntax}
  12945. \end{figure}
  12946. An instance of a structure is created using function-call syntax, with
  12947. the name of the structure in the function position, as follows:
  12948. \begin{lstlisting}
  12949. (point 7 12)
  12950. \end{lstlisting}
  12951. Function-call syntax is also used to read a field of a structure. The
  12952. function name is formed by the structure name, a dash, and the field
  12953. name. The following example uses \code{point-x} and \code{point-y} to
  12954. access the \code{x} and \code{y} fields of two point instances:
  12955. \begin{center}
  12956. \begin{lstlisting}
  12957. (let ([pt1 (point 7 12)])
  12958. (let ([pt2 (point 4 3)])
  12959. (+ (- (point-x pt1) (point-x pt2))
  12960. (- (point-y pt1) (point-y pt2)))))
  12961. \end{lstlisting}
  12962. \end{center}
  12963. Similarly, to write to a field of a structure, use its set function,
  12964. whose name starts with \code{set-}, followed by the structure name,
  12965. then a dash, then the field name, and finally with an exclamation
  12966. mark. The following example uses \code{set-point-x!} to change the
  12967. \code{x} field from \code{7} to \code{42}:
  12968. \begin{center}
  12969. \begin{lstlisting}
  12970. (let ([pt (point 7 12)])
  12971. (let ([_ (set-point-x! pt 42)])
  12972. (point-x pt)))
  12973. \end{lstlisting}
  12974. \end{center}
  12975. \begin{exercise}\normalfont\normalsize
  12976. Create a type checker for \LangStruct{} by extending the type
  12977. checker for \LangVec{}. Extend your compiler with support for simple
  12978. structures, compiling \LangStruct{} to x86 assembly code. Create
  12979. five new test cases that use structures, and test your compiler.
  12980. \end{exercise}
  12981. % TODO: create an interpreter for L_struct
  12982. \clearpage
  12983. \fi}
  12984. \section{Challenge: Arrays}
  12985. \label{sec:arrays}
  12986. % TODO mention trapped-error
  12987. In this chapter we have studied tuples, that is, heterogeneous
  12988. sequences of elements whose length is determined at compile time. This
  12989. challenge is also about sequences, but this time the length is
  12990. determined at runtime and all the elements have the same type (they
  12991. are homogeneous). We use the term \emph{array} for this latter kind of
  12992. sequence.
  12993. %
  12994. \racket{
  12995. The Racket language does not distinguish between tuples and arrays;
  12996. they are both represented by vectors. However, Typed Racket
  12997. distinguishes between tuples and arrays: the \code{Vector} type is for
  12998. tuples, and the \code{Vectorof} type is for arrays.}%
  12999. \python{Arrays correspond to the \code{list} type in the Python language.}
  13000. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13001. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13002. presents the definition of the abstract syntax, extending \LangVec{}
  13003. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13004. \racket{\code{make-vector} primitive operator for creating an array,
  13005. whose arguments are the length of the array and an initial value for
  13006. all the elements in the array.}%
  13007. \python{bracket notation for creating an array literal.}
  13008. \racket{The \code{vector-length},
  13009. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13010. for tuples become overloaded for use with arrays.}
  13011. \python{
  13012. The subscript operator becomes overloaded for use with arrays and tuples
  13013. and now may appear on the left-hand side of an assignment.
  13014. Note that the index of the subscript, when applied to an array, may be an
  13015. arbitrary expression and not exclusively a constant integer.
  13016. The \code{len} function is also applicable to arrays.
  13017. }
  13018. %
  13019. We include integer multiplication in \LangArray{} because it is
  13020. useful in many examples involving arrays such as computing the
  13021. inner product of two arrays (figure~\ref{fig:inner_product}).
  13022. \newcommand{\LarrayGrammarRacket}{
  13023. \begin{array}{lcl}
  13024. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13025. \Exp &::=& \CMUL{\Exp}{\Exp}
  13026. \MID \CMAKEVEC{\Exp}{\Exp}
  13027. \end{array}
  13028. }
  13029. \newcommand{\LarrayASTRacket}{
  13030. \begin{array}{lcl}
  13031. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13032. \Exp &::=& \MUL{\Exp}{\Exp}
  13033. \MID \MAKEVEC{\Exp}{\Exp}
  13034. \end{array}
  13035. }
  13036. \newcommand{\LarrayGrammarPython}{
  13037. \begin{array}{lcl}
  13038. \Type &::=& \key{list}\LS\Type\RS \\
  13039. \Exp &::=& \CMUL{\Exp}{\Exp}
  13040. \MID \CGET{\Exp}{\Exp}
  13041. \MID \LS \Exp \code{,} \ldots \RS \\
  13042. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13043. \end{array}
  13044. }
  13045. \newcommand{\LarrayASTPython}{
  13046. \begin{array}{lcl}
  13047. \Type &::=& \key{ListType}\LP\Type\RP \\
  13048. \Exp &::=& \MUL{\Exp}{\Exp}
  13049. \MID \GET{\Exp}{\Exp} \\
  13050. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13051. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13052. \end{array}
  13053. }
  13054. \begin{figure}[tp]
  13055. \centering
  13056. \begin{tcolorbox}[colback=white]
  13057. \small
  13058. {\if\edition\racketEd
  13059. \[
  13060. \begin{array}{l}
  13061. \gray{\LintGrammarRacket{}} \\ \hline
  13062. \gray{\LvarGrammarRacket{}} \\ \hline
  13063. \gray{\LifGrammarRacket{}} \\ \hline
  13064. \gray{\LwhileGrammarRacket} \\ \hline
  13065. \gray{\LtupGrammarRacket} \\ \hline
  13066. \LarrayGrammarRacket \\
  13067. \begin{array}{lcl}
  13068. \LangArray{} &::=& \Exp
  13069. \end{array}
  13070. \end{array}
  13071. \]
  13072. \fi}
  13073. {\if\edition\pythonEd\pythonColor
  13074. \[
  13075. \begin{array}{l}
  13076. \gray{\LintGrammarPython{}} \\ \hline
  13077. \gray{\LvarGrammarPython{}} \\ \hline
  13078. \gray{\LifGrammarPython{}} \\ \hline
  13079. \gray{\LwhileGrammarPython} \\ \hline
  13080. \gray{\LtupGrammarPython} \\ \hline
  13081. \LarrayGrammarPython \\
  13082. \begin{array}{rcl}
  13083. \LangArrayM{} &::=& \Stmt^{*}
  13084. \end{array}
  13085. \end{array}
  13086. \]
  13087. \fi}
  13088. \end{tcolorbox}
  13089. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13090. \label{fig:Lvecof-concrete-syntax}
  13091. \end{figure}
  13092. \begin{figure}[tp]
  13093. \centering
  13094. \begin{tcolorbox}[colback=white]
  13095. \small
  13096. {\if\edition\racketEd
  13097. \[
  13098. \begin{array}{l}
  13099. \gray{\LintASTRacket{}} \\ \hline
  13100. \gray{\LvarASTRacket{}} \\ \hline
  13101. \gray{\LifASTRacket{}} \\ \hline
  13102. \gray{\LwhileASTRacket} \\ \hline
  13103. \gray{\LtupASTRacket} \\ \hline
  13104. \LarrayASTRacket \\
  13105. \begin{array}{lcl}
  13106. \LangArray{} &::=& \Exp
  13107. \end{array}
  13108. \end{array}
  13109. \]
  13110. \fi}
  13111. {\if\edition\pythonEd\pythonColor
  13112. \[
  13113. \begin{array}{l}
  13114. \gray{\LintASTPython{}} \\ \hline
  13115. \gray{\LvarASTPython{}} \\ \hline
  13116. \gray{\LifASTPython{}} \\ \hline
  13117. \gray{\LwhileASTPython} \\ \hline
  13118. \gray{\LtupASTPython} \\ \hline
  13119. \LarrayASTPython \\
  13120. \begin{array}{rcl}
  13121. \LangArrayM{} &::=& \Stmt^{*}
  13122. \end{array}
  13123. \end{array}
  13124. \]
  13125. \fi}
  13126. \end{tcolorbox}
  13127. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13128. \label{fig:Lvecof-syntax}
  13129. \end{figure}
  13130. \begin{figure}[tp]
  13131. \begin{tcolorbox}[colback=white]
  13132. {\if\edition\racketEd
  13133. % TODO: remove the function from the following example, like the python version -Jeremy
  13134. \begin{lstlisting}
  13135. (let ([A (make-vector 2 2)])
  13136. (let ([B (make-vector 2 3)])
  13137. (let ([i 0])
  13138. (let ([prod 0])
  13139. (begin
  13140. (while (< i n)
  13141. (begin
  13142. (set! prod (+ prod (* (vector-ref A i)
  13143. (vector-ref B i))))
  13144. (set! i (+ i 1))))
  13145. prod)))))
  13146. \end{lstlisting}
  13147. \fi}
  13148. {\if\edition\pythonEd\pythonColor
  13149. \begin{lstlisting}
  13150. A = [2, 2]
  13151. B = [3, 3]
  13152. i = 0
  13153. prod = 0
  13154. while i != len(A):
  13155. prod = prod + A[i] * B[i]
  13156. i = i + 1
  13157. print(prod)
  13158. \end{lstlisting}
  13159. \fi}
  13160. \end{tcolorbox}
  13161. \caption{Example program that computes the inner product.}
  13162. \label{fig:inner_product}
  13163. \end{figure}
  13164. {\if\edition\racketEd
  13165. %
  13166. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13167. checker for \LangArray{}. The result type of
  13168. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13169. of the initializing expression. The length expression is required to
  13170. have type \code{Integer}. The type checking of the operators
  13171. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13172. updated to handle the situation in which the vector has type
  13173. \code{Vectorof}. In these cases we translate the operators to their
  13174. \code{vectorof} form so that later passes can easily distinguish
  13175. between operations on tuples versus arrays. We override the
  13176. \code{operator-types} method to provide the type signature for
  13177. multiplication: it takes two integers and returns an integer. \fi}
  13178. {\if\edition\pythonEd\pythonColor
  13179. %
  13180. The type checker for \LangArray{} is defined in
  13181. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  13182. is \code{list[T]}, where \code{T} is the type of the initializing
  13183. expressions. The type checking of the \code{len} function and the
  13184. subscript operator are updated to handle lists. The type checker now
  13185. also handles a subscript on the left-hand side of an assignment.
  13186. Regarding multiplication, it takes two integers and returns an
  13187. integer.
  13188. %
  13189. \fi}
  13190. \begin{figure}[tbp]
  13191. \begin{tcolorbox}[colback=white]
  13192. {\if\edition\racketEd
  13193. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13194. (define type-check-Lvecof-class
  13195. (class type-check-Lvec-class
  13196. (super-new)
  13197. (inherit check-type-equal?)
  13198. (define/override (operator-types)
  13199. (append '((* . ((Integer Integer) . Integer)))
  13200. (super operator-types)))
  13201. (define/override (type-check-exp env)
  13202. (lambda (e)
  13203. (define recur (type-check-exp env))
  13204. (match e
  13205. [(Prim 'make-vector (list e1 e2))
  13206. (define-values (e1^ t1) (recur e1))
  13207. (define-values (e2^ elt-type) (recur e2))
  13208. (define vec-type `(Vectorof ,elt-type))
  13209. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13210. [(Prim 'vector-ref (list e1 e2))
  13211. (define-values (e1^ t1) (recur e1))
  13212. (define-values (e2^ t2) (recur e2))
  13213. (match* (t1 t2)
  13214. [(`(Vectorof ,elt-type) 'Integer)
  13215. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13216. [(other wise) ((super type-check-exp env) e)])]
  13217. [(Prim 'vector-set! (list e1 e2 e3) )
  13218. (define-values (e-vec t-vec) (recur e1))
  13219. (define-values (e2^ t2) (recur e2))
  13220. (define-values (e-arg^ t-arg) (recur e3))
  13221. (match t-vec
  13222. [`(Vectorof ,elt-type)
  13223. (check-type-equal? elt-type t-arg e)
  13224. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13225. [else ((super type-check-exp env) e)])]
  13226. [(Prim 'vector-length (list e1))
  13227. (define-values (e1^ t1) (recur e1))
  13228. (match t1
  13229. [`(Vectorof ,t)
  13230. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13231. [else ((super type-check-exp env) e)])]
  13232. [else ((super type-check-exp env) e)])))
  13233. ))
  13234. (define (type-check-Lvecof p)
  13235. (send (new type-check-Lvecof-class) type-check-program p))
  13236. \end{lstlisting}
  13237. \fi}
  13238. {\if\edition\pythonEd\pythonColor
  13239. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13240. class TypeCheckLarray(TypeCheckLtup):
  13241. def type_check_exp(self, e, env):
  13242. match e:
  13243. case ast.List(es, Load()):
  13244. ts = [self.type_check_exp(e, env) for e in es]
  13245. elt_ty = ts[0]
  13246. for (ty, elt) in zip(ts, es):
  13247. self.check_type_equal(elt_ty, ty, elt)
  13248. e.has_type = ListType(elt_ty)
  13249. return e.has_type
  13250. case Call(Name('len'), [tup]):
  13251. tup_t = self.type_check_exp(tup, env)
  13252. tup.has_type = tup_t
  13253. match tup_t:
  13254. case TupleType(ts):
  13255. return IntType()
  13256. case ListType(ty):
  13257. return IntType()
  13258. case _:
  13259. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13260. case Subscript(tup, index, Load()):
  13261. tup_ty = self.type_check_exp(tup, env)
  13262. index_ty = self.type_check_exp(index, env)
  13263. self.check_type_equal(index_ty, IntType(), index)
  13264. match tup_ty:
  13265. case TupleType(ts):
  13266. match index:
  13267. case Constant(i):
  13268. return ts[i]
  13269. case _:
  13270. raise Exception('subscript required constant integer index')
  13271. case ListType(ty):
  13272. return ty
  13273. case _:
  13274. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13275. case BinOp(left, Mult(), right):
  13276. l = self.type_check_exp(left, env)
  13277. self.check_type_equal(l, IntType(), left)
  13278. r = self.type_check_exp(right, env)
  13279. self.check_type_equal(r, IntType(), right)
  13280. return IntType()
  13281. case _:
  13282. return super().type_check_exp(e, env)
  13283. \end{lstlisting}
  13284. \fi}
  13285. \end{tcolorbox}
  13286. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13287. \label{fig:type-check-Lvecof}
  13288. \end{figure}
  13289. {\if\edition\pythonEd
  13290. \begin{figure}[tbp]
  13291. \begin{tcolorbox}[colback=white]
  13292. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13293. def type_check_stmts(self, ss, env):
  13294. if len(ss) == 0:
  13295. return VoidType()
  13296. match ss[0]:
  13297. case Assign([Subscript(tup, index, Store())], value):
  13298. tup_t = self.type_check_exp(tup, env)
  13299. value_t = self.type_check_exp(value, env)
  13300. index_ty = self.type_check_exp(index, env)
  13301. self.check_type_equal(index_ty, IntType(), index)
  13302. match tup_t:
  13303. case ListType(ty):
  13304. self.check_type_equal(ty, value_t, ss[0])
  13305. case TupleType(ts):
  13306. return self.type_check_stmts(ss, env)
  13307. case _:
  13308. raise Exception('type_check_stmts: '
  13309. 'expected tuple or list, not ' + repr(tup_t))
  13310. return self.type_check_stmts(ss[1:], env)
  13311. case _:
  13312. return super().type_check_stmts(ss, env)
  13313. \end{lstlisting}
  13314. \end{tcolorbox}
  13315. \caption{Type checker for the \LangArray{} language, part 2.}
  13316. \label{fig:type-check-Lvecof-part2}
  13317. \end{figure}
  13318. \fi}
  13319. The definition of the interpreter for \LangArray{} is shown in
  13320. \racket{figure~\ref{fig:interp-Lvecof}}
  13321. \python{figures~\ref{fig:interp-Lvecof} and \ref{fig:type-check-Lvecof-part2}}.
  13322. \racket{The \code{make-vector} operator is
  13323. interpreted using Racket's \code{make-vector} function,
  13324. and multiplication is interpreted using \code{fx*},
  13325. which is multiplication for \code{fixnum} integers.
  13326. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13327. we translate array access operations
  13328. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13329. which we interpret using \code{vector} operations with additional
  13330. bounds checks that signal a \code{trapped-error}.
  13331. }
  13332. %
  13333. \python{We implement list creation with a Python list comprehension,
  13334. and multiplication is implemented with 64-bit multiplication. We
  13335. add a case to handle a subscript on the left-hand side of
  13336. assignment. Other uses of subscript can be handled by the existing
  13337. code for tuples.}
  13338. \begin{figure}[tbp]
  13339. \begin{tcolorbox}[colback=white]
  13340. {\if\edition\racketEd
  13341. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13342. (define interp-Lvecof-class
  13343. (class interp-Lvec-class
  13344. (super-new)
  13345. (define/override (interp-op op)
  13346. (match op
  13347. ['make-vector make-vector]
  13348. ['vectorof-length vector-length]
  13349. ['vectorof-ref
  13350. (lambda (v i)
  13351. (if (< i (vector-length v))
  13352. (vector-ref v i)
  13353. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13354. ['vectorof-set!
  13355. (lambda (v i e)
  13356. (if (< i (vector-length v))
  13357. (vector-set! v i e)
  13358. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13359. [else (super interp-op op)]))
  13360. ))
  13361. (define (interp-Lvecof p)
  13362. (send (new interp-Lvecof-class) interp-program p))
  13363. \end{lstlisting}
  13364. \fi}
  13365. {\if\edition\pythonEd\pythonColor
  13366. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13367. class InterpLarray(InterpLtup):
  13368. def interp_exp(self, e, env):
  13369. match e:
  13370. case ast.List(es, Load()):
  13371. return [self.interp_exp(e, env) for e in es]
  13372. case BinOp(left, Mult(), right):
  13373. l = self.interp_exp(left, env)
  13374. r = self.interp_exp(right, env)
  13375. return mul64(l, r)
  13376. case Subscript(tup, index, Load()):
  13377. t = self.interp_exp(tup, env)
  13378. n = self.interp_exp(index, env)
  13379. if n < len(t):
  13380. return t[n]
  13381. else:
  13382. raise TrappedError('array index out of bounds')
  13383. case _:
  13384. return super().interp_exp(e, env)
  13385. def interp_stmt(self, s, env, cont):
  13386. match s:
  13387. case Assign([Subscript(tup, index)], value):
  13388. t = self.interp_exp(tup, env)
  13389. n = self.interp_exp(index, env)
  13390. if n < len(t):
  13391. t[n] = self.interp_exp(value, env)
  13392. else:
  13393. raise TrappedError('array index out of bounds')
  13394. return self.interp_stmts(cont, env)
  13395. case _:
  13396. return super().interp_stmt(s, env, cont)
  13397. \end{lstlisting}
  13398. \fi}
  13399. \end{tcolorbox}
  13400. \caption{Interpreter for \LangArray{}.}
  13401. \label{fig:interp-Lvecof}
  13402. \end{figure}
  13403. \subsection{Data Representation}
  13404. \label{sec:array-rep}
  13405. Just as with tuples, we store arrays on the heap, which means that the
  13406. garbage collector will need to inspect arrays. An immediate thought is
  13407. to use the same representation for arrays that we use for tuples.
  13408. However, we limit tuples to a length of fifty so that their length and
  13409. pointer mask can fit into the 64-bit tag at the beginning of each
  13410. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13411. millions of elements, so we need more bits to store the length.
  13412. However, because arrays are homogeneous, we need only 1 bit for the
  13413. pointer mask instead of 1 bit per array element. Finally, the
  13414. garbage collector must be able to distinguish between tuples
  13415. and arrays, so we need to reserve one bit for that purpose. We
  13416. arrive at the following layout for the 64-bit tag at the beginning of
  13417. an array:
  13418. \begin{itemize}
  13419. \item The right-most bit is the forwarding bit, just as in a tuple.
  13420. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13421. that it is not.
  13422. \item The next bit to the left is the pointer mask. A $0$ indicates
  13423. that none of the elements are pointers to the heap, and a $1$
  13424. indicates that all the elements are pointers.
  13425. \item The next $60$ bits store the length of the array.
  13426. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13427. and an array ($1$).
  13428. \item The left-most bit is reserved as explained in
  13429. chapter~\ref{ch:Lgrad}.
  13430. \end{itemize}
  13431. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13432. %% differentiate the kinds of values that have been injected into the
  13433. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13434. %% to indicate that the value is an array.
  13435. In the following subsections we provide hints regarding how to update
  13436. the passes to handle arrays.
  13437. \subsection{Overload Resolution}
  13438. \label{sec:array-resolution}
  13439. As noted previously, with the addition of arrays, several operators
  13440. have become \emph{overloaded}; that is, they can be applied to values
  13441. of more than one type. In this case, the element access and length
  13442. operators can be applied to both tuples and arrays. This kind of
  13443. overloading is quite common in programming languages, so many
  13444. compilers perform \emph{overload resolution}\index{subject}{overload
  13445. resolution} to handle it. The idea is to translate each overloaded
  13446. operator into different operators for the different types.
  13447. Implement a new pass named \code{resolve}.
  13448. Translate the reading of an array element
  13449. into a call to
  13450. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13451. and the writing of an array element to
  13452. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13453. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13454. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13455. When these operators are applied to tuples, leave them as is.
  13456. %
  13457. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13458. field, which can be inspected to determine whether the operator
  13459. is applied to a tuple or an array.}
  13460. \subsection{Bounds Checking}
  13461. Recall that the interpreter for \LangArray{} signals a
  13462. \code{trapped-error} when there is an array access that is out of
  13463. bounds. Therefore your compiler is obliged to also catch these errors
  13464. during execution and halt, signaling an error. We recommend inserting
  13465. a new pass named \code{check\_bounds} that inserts code around each
  13466. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13467. \python{subscript} operation to ensure that the index is greater than
  13468. or equal to zero and less than the array's length. If not, the program
  13469. should halt, for which we recommend using a new primitive operation
  13470. named \code{exit}.
  13471. %% \subsection{Reveal Casts}
  13472. %% The array-access operators \code{vectorof-ref} and
  13473. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13474. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13475. %% that the type checker cannot tell whether the index will be in bounds,
  13476. %% so the bounds check must be performed at run time. Recall that the
  13477. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13478. %% an \code{If} around a vector reference for update to check whether
  13479. %% the index is less than the length. You should do the same for
  13480. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13481. %% In addition, the handling of the \code{any-vector} operators in
  13482. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13483. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13484. %% generated code should test whether the tag is for tuples (\code{010})
  13485. %% or arrays (\code{110}) and then dispatch to either
  13486. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13487. %% we add a case in \code{select\_instructions} to generate the
  13488. %% appropriate instructions for accessing the array length from the
  13489. %% header of an array.
  13490. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13491. %% the generated code needs to check that the index is less than the
  13492. %% vector length, so like the code for \code{any-vector-length}, check
  13493. %% the tag to determine whether to use \code{any-vector-length} or
  13494. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13495. %% is complete, the generated code can use \code{any-vector-ref} and
  13496. %% \code{any-vector-set!} for both tuples and arrays because the
  13497. %% instructions used for those operators do not look at the tag at the
  13498. %% front of the tuple or array.
  13499. \subsection{Expose Allocation}
  13500. This pass should translate array creation into lower-level
  13501. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13502. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13503. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13504. array. The \code{AllocateArray} AST node allocates an array of the
  13505. length specified by the $\Exp$ (of type \INTTY), but does not
  13506. initialize the elements of the array. Generate code in this pass to
  13507. initialize the elements analogous to the case for tuples.
  13508. {\if\edition\racketEd
  13509. \subsection{Uncover \texttt{get!}}
  13510. \label{sec:uncover-get-bang-vecof}
  13511. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13512. \code{uncover-get!-exp}.
  13513. \fi}
  13514. \subsection{Remove Complex Operands}
  13515. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13516. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13517. complex, and its subexpression must be atomic.
  13518. \subsection{Explicate Control}
  13519. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13520. \code{explicate\_assign}.
  13521. \subsection{Select Instructions}
  13522. \index{subject}{select instructions}
  13523. Generate instructions for \code{AllocateArray} similar to those for
  13524. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13525. except that the tag at the front of the array should instead use the
  13526. representation discussed in section~\ref{sec:array-rep}.
  13527. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13528. extract the length from the tag.
  13529. The instructions generated for accessing an element of an array differ
  13530. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13531. that the index is not a constant so you need to generate instructions
  13532. that compute the offset at runtime.
  13533. Compile the \code{exit} primitive into a call to the \code{exit}
  13534. function of the C standard library, with an argument of $255$.
  13535. %% Also, note that assignment to an array element may appear in
  13536. %% as a stand-alone statement, so make sure to handle that situation in
  13537. %% this pass.
  13538. %% Finally, the instructions for \code{any-vectorof-length} should be
  13539. %% similar to those for \code{vectorof-length}, except that one must
  13540. %% first project the array by writing zeroes into the $3$-bit tag
  13541. \begin{exercise}\normalfont\normalsize
  13542. Implement a compiler for the \LangArray{} language by extending your
  13543. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13544. programs, including the one shown in figure~\ref{fig:inner_product}
  13545. and also a program that multiplies two matrices. Note that although
  13546. matrices are two-dimensional arrays, they can be encoded into
  13547. one-dimensional arrays by laying out each row in the array, one after
  13548. the next.
  13549. \end{exercise}
  13550. {\if\edition\racketEd
  13551. \section{Challenge: Generational Collection}
  13552. The copying collector described in section~\ref{sec:GC} can incur
  13553. significant runtime overhead because the call to \code{collect} takes
  13554. time proportional to all the live data. One way to reduce this
  13555. overhead is to reduce how much data is inspected in each call to
  13556. \code{collect}. In particular, researchers have observed that recently
  13557. allocated data is more likely to become garbage then data that has
  13558. survived one or more previous calls to \code{collect}. This insight
  13559. motivated the creation of \emph{generational garbage collectors}
  13560. \index{subject}{generational garbage collector} that
  13561. (1) segregate data according to its age into two or more generations;
  13562. (2) allocate less space for younger generations, so collecting them is
  13563. faster, and more space for the older generations; and (3) perform
  13564. collection on the younger generations more frequently than on older
  13565. generations~\citep{Wilson:1992fk}.
  13566. For this challenge assignment, the goal is to adapt the copying
  13567. collector implemented in \code{runtime.c} to use two generations, one
  13568. for young data and one for old data. Each generation consists of a
  13569. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13570. \code{collect} function to use the two generations:
  13571. \begin{enumerate}
  13572. \item Copy the young generation's FromSpace to its ToSpace and then
  13573. switch the role of the ToSpace and FromSpace.
  13574. \item If there is enough space for the requested number of bytes in
  13575. the young FromSpace, then return from \code{collect}.
  13576. \item If there is not enough space in the young FromSpace for the
  13577. requested bytes, then move the data from the young generation to the
  13578. old one with the following steps:
  13579. \begin{enumerate}
  13580. \item[a.] If there is enough room in the old FromSpace, copy the young
  13581. FromSpace to the old FromSpace and then return.
  13582. \item[b.] If there is not enough room in the old FromSpace, then collect
  13583. the old generation by copying the old FromSpace to the old ToSpace
  13584. and swap the roles of the old FromSpace and ToSpace.
  13585. \item[c.] If there is enough room now, copy the young FromSpace to the
  13586. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13587. and ToSpace for the old generation. Copy the young FromSpace and
  13588. the old FromSpace into the larger FromSpace for the old
  13589. generation and then return.
  13590. \end{enumerate}
  13591. \end{enumerate}
  13592. We recommend that you generalize the \code{cheney} function so that it
  13593. can be used for all the copies mentioned: between the young FromSpace
  13594. and ToSpace, between the old FromSpace and ToSpace, and between the
  13595. young FromSpace and old FromSpace. This can be accomplished by adding
  13596. parameters to \code{cheney} that replace its use of the global
  13597. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13598. \code{tospace\_begin}, and \code{tospace\_end}.
  13599. Note that the collection of the young generation does not traverse the
  13600. old generation. This introduces a potential problem: there may be
  13601. young data that is reachable only through pointers in the old
  13602. generation. If these pointers are not taken into account, the
  13603. collector could throw away young data that is live! One solution,
  13604. called \emph{pointer recording}, is to maintain a set of all the
  13605. pointers from the old generation into the new generation and consider
  13606. this set as part of the root set. To maintain this set, the compiler
  13607. must insert extra instructions around every \code{vector-set!}. If the
  13608. vector being modified is in the old generation, and if the value being
  13609. written is a pointer into the new generation, then that pointer must
  13610. be added to the set. Also, if the value being overwritten was a
  13611. pointer into the new generation, then that pointer should be removed
  13612. from the set.
  13613. \begin{exercise}\normalfont\normalsize
  13614. Adapt the \code{collect} function in \code{runtime.c} to implement
  13615. generational garbage collection, as outlined in this section.
  13616. Update the code generation for \code{vector-set!} to implement
  13617. pointer recording. Make sure that your new compiler and runtime
  13618. execute without error on your test suite.
  13619. \end{exercise}
  13620. \fi}
  13621. \section{Further Reading}
  13622. \citet{Appel90} describes many data representation approaches
  13623. including the ones used in the compilation of Standard ML.
  13624. There are many alternatives to copying collectors (and their bigger
  13625. siblings, the generational collectors) with regard to garbage
  13626. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13627. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13628. collectors are that allocation is fast (just a comparison and pointer
  13629. increment), there is no fragmentation, cyclic garbage is collected,
  13630. and the time complexity of collection depends only on the amount of
  13631. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13632. main disadvantages of a two-space copying collector is that it uses a
  13633. lot of extra space and takes a long time to perform the copy, though
  13634. these problems are ameliorated in generational collectors.
  13635. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13636. small objects and generate a lot of garbage, so copying and
  13637. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13638. Garbage collection is an active research topic, especially concurrent
  13639. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13640. developing new techniques and revisiting old
  13641. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13642. meet every year at the International Symposium on Memory Management to
  13643. present these findings.
  13644. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13645. \chapter{Functions}
  13646. \label{ch:Lfun}
  13647. \index{subject}{function}
  13648. \setcounter{footnote}{0}
  13649. This chapter studies the compilation of a subset of \racket{Typed
  13650. Racket}\python{Python} in which only top-level function definitions
  13651. are allowed. This kind of function appears in the C programming
  13652. language, and it serves as an important stepping-stone to implementing
  13653. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13654. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13655. \section{The \LangFun{} Language}
  13656. The concrete syntax and abstract syntax for function definitions and
  13657. function application are shown in
  13658. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13659. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13660. with zero or more function definitions. The function names from these
  13661. definitions are in scope for the entire program, including all the
  13662. function definitions, and therefore the ordering of function
  13663. definitions does not matter.
  13664. %
  13665. \python{The abstract syntax for function parameters in
  13666. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13667. consists of a parameter name and its type. This design differs from
  13668. Python's \code{ast} module, which has a more complex structure for
  13669. function parameters to handle keyword parameters,
  13670. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13671. complex Python abstract syntax into the simpler syntax shown in
  13672. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13673. \code{FunctionDef} constructor are for decorators and a type
  13674. comment, neither of which are used by our compiler. We recommend
  13675. replacing them with \code{None} in the \code{shrink} pass.
  13676. }
  13677. %
  13678. The concrete syntax for function application
  13679. \index{subject}{function application}
  13680. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13681. where the first expression
  13682. must evaluate to a function and the remaining expressions are the arguments. The
  13683. abstract syntax for function application is
  13684. $\APPLY{\Exp}{\Exp^*}$.
  13685. %% The syntax for function application does not include an explicit
  13686. %% keyword, which is error prone when using \code{match}. To alleviate
  13687. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13688. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13689. Functions are first-class in the sense that a function pointer
  13690. \index{subject}{function pointer} is data and can be stored in memory or passed
  13691. as a parameter to another function. Thus, there is a function
  13692. type, written
  13693. {\if\edition\racketEd
  13694. \begin{lstlisting}
  13695. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13696. \end{lstlisting}
  13697. \fi}
  13698. {\if\edition\pythonEd\pythonColor
  13699. \begin{lstlisting}
  13700. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13701. \end{lstlisting}
  13702. \fi}
  13703. %
  13704. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13705. through $\Type_n$ and whose return type is $\Type_R$. The main
  13706. limitation of these functions (with respect to
  13707. \racket{Racket}\python{Python} functions) is that they are not
  13708. lexically scoped. That is, the only external entities that can be
  13709. referenced from inside a function body are other globally defined
  13710. functions. The syntax of \LangFun{} prevents function definitions from
  13711. being nested inside each other.
  13712. \newcommand{\LfunGrammarRacket}{
  13713. \begin{array}{lcl}
  13714. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13715. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13716. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13717. \end{array}
  13718. }
  13719. \newcommand{\LfunASTRacket}{
  13720. \begin{array}{lcl}
  13721. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13722. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13723. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13724. \end{array}
  13725. }
  13726. \newcommand{\LfunGrammarPython}{
  13727. \begin{array}{lcl}
  13728. \Type &::=& \key{int}
  13729. \MID \key{bool} \MID \key{void}
  13730. \MID \key{tuple}\LS \Type^+ \RS
  13731. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13732. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13733. \Stmt &::=& \CRETURN{\Exp} \\
  13734. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13735. \end{array}
  13736. }
  13737. \newcommand{\LfunASTPython}{
  13738. \begin{array}{lcl}
  13739. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13740. \MID \key{TupleType}\LS\Type^+\RS\\
  13741. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13742. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13743. \Stmt &::=& \RETURN{\Exp} \\
  13744. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13745. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13746. \end{array}
  13747. }
  13748. \begin{figure}[tp]
  13749. \centering
  13750. \begin{tcolorbox}[colback=white]
  13751. \small
  13752. {\if\edition\racketEd
  13753. \[
  13754. \begin{array}{l}
  13755. \gray{\LintGrammarRacket{}} \\ \hline
  13756. \gray{\LvarGrammarRacket{}} \\ \hline
  13757. \gray{\LifGrammarRacket{}} \\ \hline
  13758. \gray{\LwhileGrammarRacket} \\ \hline
  13759. \gray{\LtupGrammarRacket} \\ \hline
  13760. \LfunGrammarRacket \\
  13761. \begin{array}{lcl}
  13762. \LangFunM{} &::=& \Def \ldots \; \Exp
  13763. \end{array}
  13764. \end{array}
  13765. \]
  13766. \fi}
  13767. {\if\edition\pythonEd\pythonColor
  13768. \[
  13769. \begin{array}{l}
  13770. \gray{\LintGrammarPython{}} \\ \hline
  13771. \gray{\LvarGrammarPython{}} \\ \hline
  13772. \gray{\LifGrammarPython{}} \\ \hline
  13773. \gray{\LwhileGrammarPython} \\ \hline
  13774. \gray{\LtupGrammarPython} \\ \hline
  13775. \LfunGrammarPython \\
  13776. \begin{array}{rcl}
  13777. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13778. \end{array}
  13779. \end{array}
  13780. \]
  13781. \fi}
  13782. \end{tcolorbox}
  13783. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13784. \label{fig:Lfun-concrete-syntax}
  13785. \end{figure}
  13786. \begin{figure}[tp]
  13787. \centering
  13788. \begin{tcolorbox}[colback=white]
  13789. \small
  13790. {\if\edition\racketEd
  13791. \[
  13792. \begin{array}{l}
  13793. \gray{\LintOpAST} \\ \hline
  13794. \gray{\LvarASTRacket{}} \\ \hline
  13795. \gray{\LifASTRacket{}} \\ \hline
  13796. \gray{\LwhileASTRacket{}} \\ \hline
  13797. \gray{\LtupASTRacket{}} \\ \hline
  13798. \LfunASTRacket \\
  13799. \begin{array}{lcl}
  13800. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13801. \end{array}
  13802. \end{array}
  13803. \]
  13804. \fi}
  13805. {\if\edition\pythonEd\pythonColor
  13806. \[
  13807. \begin{array}{l}
  13808. \gray{\LintASTPython{}} \\ \hline
  13809. \gray{\LvarASTPython{}} \\ \hline
  13810. \gray{\LifASTPython{}} \\ \hline
  13811. \gray{\LwhileASTPython} \\ \hline
  13812. \gray{\LtupASTPython} \\ \hline
  13813. \LfunASTPython \\
  13814. \begin{array}{rcl}
  13815. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13816. \end{array}
  13817. \end{array}
  13818. \]
  13819. \fi}
  13820. \end{tcolorbox}
  13821. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13822. \label{fig:Lfun-syntax}
  13823. \end{figure}
  13824. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13825. representative example of defining and using functions in \LangFun{}.
  13826. We define a function \code{map} that applies some other function
  13827. \code{f} to both elements of a tuple and returns a new tuple
  13828. containing the results. We also define a function \code{inc}. The
  13829. program applies \code{map} to \code{inc} and
  13830. %
  13831. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13832. %
  13833. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13834. %
  13835. from which we return \code{42}.
  13836. \begin{figure}[tbp]
  13837. \begin{tcolorbox}[colback=white]
  13838. {\if\edition\racketEd
  13839. \begin{lstlisting}
  13840. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13841. : (Vector Integer Integer)
  13842. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13843. (define (inc [x : Integer]) : Integer
  13844. (+ x 1))
  13845. (vector-ref (map inc (vector 0 41)) 1)
  13846. \end{lstlisting}
  13847. \fi}
  13848. {\if\edition\pythonEd\pythonColor
  13849. \begin{lstlisting}
  13850. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13851. return f(v[0]), f(v[1])
  13852. def inc(x : int) -> int:
  13853. return x + 1
  13854. print(map(inc, (0, 41))[1])
  13855. \end{lstlisting}
  13856. \fi}
  13857. \end{tcolorbox}
  13858. \caption{Example of using functions in \LangFun{}.}
  13859. \label{fig:Lfun-function-example}
  13860. \end{figure}
  13861. The definitional interpreter for \LangFun{} is shown in
  13862. figure~\ref{fig:interp-Lfun}. The case for the
  13863. %
  13864. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13865. %
  13866. AST is responsible for setting up the mutual recursion between the
  13867. top-level function definitions.
  13868. %
  13869. \racket{We use the classic back-patching
  13870. \index{subject}{back-patching} approach that uses mutable variables
  13871. and makes two passes over the function
  13872. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13873. top-level environment using a mutable cons cell for each function
  13874. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13875. for each function is incomplete; it does not yet include the environment.
  13876. Once the top-level environment has been constructed, we iterate over it and
  13877. update the \code{lambda} values to use the top-level environment.}
  13878. %
  13879. \python{We create a dictionary named \code{env} and fill it in
  13880. by mapping each function name to a new \code{Function} value,
  13881. each of which stores a reference to the \code{env}.
  13882. (We define the class \code{Function} for this purpose.)}
  13883. %
  13884. To interpret a function \racket{application}\python{call}, we match
  13885. the result of the function expression to obtain a function value. We
  13886. then extend the function's environment with the mapping of parameters to
  13887. argument values. Finally, we interpret the body of the function in
  13888. this extended environment.
  13889. \begin{figure}[tp]
  13890. \begin{tcolorbox}[colback=white]
  13891. {\if\edition\racketEd
  13892. \begin{lstlisting}
  13893. (define interp-Lfun-class
  13894. (class interp-Lvec-class
  13895. (super-new)
  13896. (define/override ((interp-exp env) e)
  13897. (define recur (interp-exp env))
  13898. (match e
  13899. [(Apply fun args)
  13900. (define fun-val (recur fun))
  13901. (define arg-vals (for/list ([e args]) (recur e)))
  13902. (match fun-val
  13903. [`(function (,xs ...) ,body ,fun-env)
  13904. (define params-args (for/list ([x xs] [arg arg-vals])
  13905. (cons x (box arg))))
  13906. (define new-env (append params-args fun-env))
  13907. ((interp-exp new-env) body)]
  13908. [else
  13909. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13910. [else ((super interp-exp env) e)]
  13911. ))
  13912. (define/public (interp-def d)
  13913. (match d
  13914. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13915. (cons f (box `(function ,xs ,body ())))]))
  13916. (define/override (interp-program p)
  13917. (match p
  13918. [(ProgramDefsExp info ds body)
  13919. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13920. (for/list ([f (in-dict-values top-level)])
  13921. (set-box! f (match (unbox f)
  13922. [`(function ,xs ,body ())
  13923. `(function ,xs ,body ,top-level)])))
  13924. ((interp-exp top-level) body))]))
  13925. ))
  13926. (define (interp-Lfun p)
  13927. (send (new interp-Lfun-class) interp-program p))
  13928. \end{lstlisting}
  13929. \fi}
  13930. {\if\edition\pythonEd\pythonColor
  13931. \begin{lstlisting}
  13932. class InterpLfun(InterpLtup):
  13933. def apply_fun(self, fun, args, e):
  13934. match fun:
  13935. case Function(name, xs, body, env):
  13936. new_env = env.copy().update(zip(xs, args))
  13937. return self.interp_stmts(body, new_env)
  13938. case _:
  13939. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13940. def interp_exp(self, e, env):
  13941. match e:
  13942. case Call(Name('input_int'), []):
  13943. return super().interp_exp(e, env)
  13944. case Call(func, args):
  13945. f = self.interp_exp(func, env)
  13946. vs = [self.interp_exp(arg, env) for arg in args]
  13947. return self.apply_fun(f, vs, e)
  13948. case _:
  13949. return super().interp_exp(e, env)
  13950. def interp_stmt(self, s, env, cont):
  13951. match s:
  13952. case Return(value):
  13953. return self.interp_exp(value, env)
  13954. case FunctionDef(name, params, bod, dl, returns, comment):
  13955. if isinstance(params, ast.arguments):
  13956. ps = [p.arg for p in params.args]
  13957. else:
  13958. ps = [x for (x,t) in params]
  13959. env[name] = Function(name, ps, bod, env)
  13960. return self.interp_stmts(cont, env)
  13961. case _:
  13962. return super().interp_stmt(s, env, cont)
  13963. def interp(self, p):
  13964. match p:
  13965. case Module(ss):
  13966. env = {}
  13967. self.interp_stmts(ss, env)
  13968. if 'main' in env.keys():
  13969. self.apply_fun(env['main'], [], None)
  13970. case _:
  13971. raise Exception('interp: unexpected ' + repr(p))
  13972. \end{lstlisting}
  13973. \fi}
  13974. \end{tcolorbox}
  13975. \caption{Interpreter for the \LangFun{} language.}
  13976. \label{fig:interp-Lfun}
  13977. \end{figure}
  13978. %\margincomment{TODO: explain type checker}
  13979. The type checker for \LangFun{} is shown in
  13980. figure~\ref{fig:type-check-Lfun}.
  13981. %
  13982. \python{(We omit the code that parses function parameters into the
  13983. simpler abstract syntax.)}
  13984. %
  13985. Similarly to the interpreter, the case for the
  13986. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13987. %
  13988. AST is responsible for setting up the mutual recursion between the
  13989. top-level function definitions. We begin by create a mapping
  13990. \code{env} from every function name to its type. We then type check
  13991. the program using this mapping.
  13992. %
  13993. In the case for function \racket{application}\python{call}, we match
  13994. the type of the function expression to a function type and check that
  13995. the types of the argument expressions are equal to the function's
  13996. parameter types. The type of the \racket{application}\python{call} as
  13997. a whole is the return type from the function type.
  13998. \begin{figure}[tp]
  13999. \begin{tcolorbox}[colback=white]
  14000. {\if\edition\racketEd
  14001. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14002. (define type-check-Lfun-class
  14003. (class type-check-Lvec-class
  14004. (super-new)
  14005. (inherit check-type-equal?)
  14006. (define/public (type-check-apply env e es)
  14007. (define-values (e^ ty) ((type-check-exp env) e))
  14008. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14009. ((type-check-exp env) e)))
  14010. (match ty
  14011. [`(,ty^* ... -> ,rt)
  14012. (for ([arg-ty ty*] [param-ty ty^*])
  14013. (check-type-equal? arg-ty param-ty (Apply e es)))
  14014. (values e^ e* rt)]))
  14015. (define/override (type-check-exp env)
  14016. (lambda (e)
  14017. (match e
  14018. [(FunRef f n)
  14019. (values (FunRef f n) (dict-ref env f))]
  14020. [(Apply e es)
  14021. (define-values (e^ es^ rt) (type-check-apply env e es))
  14022. (values (Apply e^ es^) rt)]
  14023. [(Call e es)
  14024. (define-values (e^ es^ rt) (type-check-apply env e es))
  14025. (values (Call e^ es^) rt)]
  14026. [else ((super type-check-exp env) e)])))
  14027. (define/public (type-check-def env)
  14028. (lambda (e)
  14029. (match e
  14030. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14031. (define new-env (append (map cons xs ps) env))
  14032. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14033. (check-type-equal? ty^ rt body)
  14034. (Def f p:t* rt info body^)])))
  14035. (define/public (fun-def-type d)
  14036. (match d
  14037. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14038. (define/override (type-check-program e)
  14039. (match e
  14040. [(ProgramDefsExp info ds body)
  14041. (define env (for/list ([d ds])
  14042. (cons (Def-name d) (fun-def-type d))))
  14043. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14044. (define-values (body^ ty) ((type-check-exp env) body))
  14045. (check-type-equal? ty 'Integer body)
  14046. (ProgramDefsExp info ds^ body^)]))))
  14047. (define (type-check-Lfun p)
  14048. (send (new type-check-Lfun-class) type-check-program p))
  14049. \end{lstlisting}
  14050. \fi}
  14051. {\if\edition\pythonEd\pythonColor
  14052. \begin{lstlisting}
  14053. class TypeCheckLfun(TypeCheckLtup):
  14054. def type_check_exp(self, e, env):
  14055. match e:
  14056. case Call(Name('input_int'), []):
  14057. return super().type_check_exp(e, env)
  14058. case Call(func, args):
  14059. func_t = self.type_check_exp(func, env)
  14060. args_t = [self.type_check_exp(arg, env) for arg in args]
  14061. match func_t:
  14062. case FunctionType(params_t, return_t):
  14063. for (arg_t, param_t) in zip(args_t, params_t):
  14064. check_type_equal(param_t, arg_t, e)
  14065. return return_t
  14066. case _:
  14067. raise Exception('type_check_exp: in call, unexpected ' +
  14068. repr(func_t))
  14069. case _:
  14070. return super().type_check_exp(e, env)
  14071. def type_check_stmts(self, ss, env):
  14072. if len(ss) == 0:
  14073. return
  14074. match ss[0]:
  14075. case FunctionDef(name, params, body, dl, returns, comment):
  14076. new_env = env.copy().update(params)
  14077. rt = self.type_check_stmts(body, new_env)
  14078. check_type_equal(returns, rt, ss[0])
  14079. return self.type_check_stmts(ss[1:], env)
  14080. case Return(value):
  14081. return self.type_check_exp(value, env)
  14082. case _:
  14083. return super().type_check_stmts(ss, env)
  14084. def type_check(self, p):
  14085. match p:
  14086. case Module(body):
  14087. env = {}
  14088. for s in body:
  14089. match s:
  14090. case FunctionDef(name, params, bod, dl, returns, comment):
  14091. if name in env:
  14092. raise Exception('type_check: function ' +
  14093. repr(name) + ' defined twice')
  14094. params_t = [t for (x,t) in params]
  14095. env[name] = FunctionType(params_t, returns)
  14096. self.type_check_stmts(body, env)
  14097. case _:
  14098. raise Exception('type_check: unexpected ' + repr(p))
  14099. \end{lstlisting}
  14100. \fi}
  14101. \end{tcolorbox}
  14102. \caption{Type checker for the \LangFun{} language.}
  14103. \label{fig:type-check-Lfun}
  14104. \end{figure}
  14105. \clearpage
  14106. \section{Functions in x86}
  14107. \label{sec:fun-x86}
  14108. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14109. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14110. %% \margincomment{\tiny Talk about the return address on the
  14111. %% stack and what callq and retq does.\\ --Jeremy }
  14112. The x86 architecture provides a few features to support the
  14113. implementation of functions. We have already seen that there are
  14114. labels in x86 so that one can refer to the location of an instruction,
  14115. as is needed for jump instructions. Labels can also be used to mark
  14116. the beginning of the instructions for a function. Going further, we
  14117. can obtain the address of a label by using the \key{leaq}
  14118. instruction. For example, the following puts the address of the
  14119. \code{inc} label into the \code{rbx} register:
  14120. \begin{lstlisting}
  14121. leaq inc(%rip), %rbx
  14122. \end{lstlisting}
  14123. Recall from section~\ref{sec:select-instructions-gc} that
  14124. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14125. addressing.
  14126. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14127. to functions whose locations were given by a label, such as
  14128. \code{read\_int}. To support function calls in this chapter we instead
  14129. jump to functions whose location are given by an address in
  14130. a register; that is, we use \emph{indirect function calls}. The
  14131. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14132. before the register name.\index{subject}{indirect function call}
  14133. \begin{lstlisting}
  14134. callq *%rbx
  14135. \end{lstlisting}
  14136. \subsection{Calling Conventions}
  14137. \label{sec:calling-conventions-fun}
  14138. \index{subject}{calling conventions}
  14139. The \code{callq} instruction provides partial support for implementing
  14140. functions: it pushes the return address on the stack and it jumps to
  14141. the target. However, \code{callq} does not handle
  14142. \begin{enumerate}
  14143. \item parameter passing,
  14144. \item pushing frames on the procedure call stack and popping them off,
  14145. or
  14146. \item determining how registers are shared by different functions.
  14147. \end{enumerate}
  14148. Regarding parameter passing, recall that the x86-64 calling
  14149. convention for Unix-based systems uses the following six registers to
  14150. pass arguments to a function, in the given order:
  14151. \begin{lstlisting}
  14152. rdi rsi rdx rcx r8 r9
  14153. \end{lstlisting}
  14154. If there are more than six arguments, then the calling convention
  14155. mandates using space on the frame of the caller for the rest of the
  14156. arguments. However, to ease the implementation of efficient tail calls
  14157. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14158. arguments.
  14159. %
  14160. The return value of the function is stored in register \code{rax}.
  14161. Regarding frames \index{subject}{frame} and the procedure call stack,
  14162. \index{subject}{procedure call stack} recall from
  14163. section~\ref{sec:x86} that the stack grows down and each function call
  14164. uses a chunk of space on the stack called a frame. The caller sets the
  14165. stack pointer, register \code{rsp}, to the last data item in its
  14166. frame. The callee must not change anything in the caller's frame, that
  14167. is, anything that is at or above the stack pointer. The callee is free
  14168. to use locations that are below the stack pointer.
  14169. Recall that we store variables of tuple type on the root stack. So,
  14170. the prelude\index{subject}{prelude} of a function needs to move the
  14171. root stack pointer \code{r15} up according to the number of variables
  14172. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14173. move the root stack pointer back down. Also, the prelude must
  14174. initialize to \code{0} this frame's slots in the root stack to signal
  14175. to the garbage collector that those slots do not yet contain a valid
  14176. pointer. Otherwise the garbage collector will interpret the garbage
  14177. bits in those slots as memory addresses and try to traverse them,
  14178. causing serious mayhem!
  14179. Regarding the sharing of registers between different functions, recall
  14180. from section~\ref{sec:calling-conventions} that the registers are
  14181. divided into two groups, the caller-saved registers and the
  14182. callee-saved registers. The caller should assume that all the
  14183. caller-saved registers are overwritten with arbitrary values by the
  14184. callee. For that reason we recommend in
  14185. section~\ref{sec:calling-conventions} that variables that are live
  14186. during a function call should not be assigned to caller-saved
  14187. registers.
  14188. On the flip side, if the callee wants to use a callee-saved register,
  14189. the callee must save the contents of those registers on their stack
  14190. frame and then put them back prior to returning to the caller. For
  14191. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14192. the register allocator assigns a variable to a callee-saved register,
  14193. then the prelude of the \code{main} function must save that register
  14194. to the stack and the conclusion of \code{main} must restore it. This
  14195. recommendation now generalizes to all functions.
  14196. Recall that the base pointer, register \code{rbp}, is used as a
  14197. point of reference within a frame, so that each local variable can be
  14198. accessed at a fixed offset from the base pointer
  14199. (section~\ref{sec:x86}).
  14200. %
  14201. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14202. frames.
  14203. \begin{figure}[tbp]
  14204. \centering
  14205. \begin{tcolorbox}[colback=white]
  14206. \begin{tabular}{r|r|l|l} \hline
  14207. Caller View & Callee View & Contents & Frame \\ \hline
  14208. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14209. 0(\key{\%rbp}) & & old \key{rbp} \\
  14210. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14211. \ldots & & \ldots \\
  14212. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14213. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14214. \ldots & & \ldots \\
  14215. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14216. %% & & \\
  14217. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14218. %% & \ldots & \ldots \\
  14219. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14220. \hline
  14221. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14222. & 0(\key{\%rbp}) & old \key{rbp} \\
  14223. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14224. & \ldots & \ldots \\
  14225. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14226. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14227. & \ldots & \ldots \\
  14228. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14229. \end{tabular}
  14230. \end{tcolorbox}
  14231. \caption{Memory layout of caller and callee frames.}
  14232. \label{fig:call-frames}
  14233. \end{figure}
  14234. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14235. %% local variables and for storing the values of callee-saved registers
  14236. %% (we shall refer to all of these collectively as ``locals''), and that
  14237. %% at the beginning of a function we move the stack pointer \code{rsp}
  14238. %% down to make room for them.
  14239. %% We recommend storing the local variables
  14240. %% first and then the callee-saved registers, so that the local variables
  14241. %% can be accessed using \code{rbp} the same as before the addition of
  14242. %% functions.
  14243. %% To make additional room for passing arguments, we shall
  14244. %% move the stack pointer even further down. We count how many stack
  14245. %% arguments are needed for each function call that occurs inside the
  14246. %% body of the function and find their maximum. Adding this number to the
  14247. %% number of locals gives us how much the \code{rsp} should be moved at
  14248. %% the beginning of the function. In preparation for a function call, we
  14249. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14250. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14251. %% so on.
  14252. %% Upon calling the function, the stack arguments are retrieved by the
  14253. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14254. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14255. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14256. %% the layout of the caller and callee frames. Notice how important it is
  14257. %% that we correctly compute the maximum number of arguments needed for
  14258. %% function calls; if that number is too small then the arguments and
  14259. %% local variables will smash into each other!
  14260. \subsection{Efficient Tail Calls}
  14261. \label{sec:tail-call}
  14262. In general, the amount of stack space used by a program is determined
  14263. by the longest chain of nested function calls. That is, if function
  14264. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14265. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14266. large if functions are recursive. However, in some cases we can
  14267. arrange to use only a constant amount of space for a long chain of
  14268. nested function calls.
  14269. A \emph{tail call}\index{subject}{tail call} is a function call that
  14270. happens as the last action in a function body. For example, in the
  14271. following program, the recursive call to \code{tail\_sum} is a tail
  14272. call:
  14273. \begin{center}
  14274. {\if\edition\racketEd
  14275. \begin{lstlisting}
  14276. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14277. (if (eq? n 0)
  14278. r
  14279. (tail_sum (- n 1) (+ n r))))
  14280. (+ (tail_sum 3 0) 36)
  14281. \end{lstlisting}
  14282. \fi}
  14283. {\if\edition\pythonEd\pythonColor
  14284. \begin{lstlisting}
  14285. def tail_sum(n : int, r : int) -> int:
  14286. if n == 0:
  14287. return r
  14288. else:
  14289. return tail_sum(n - 1, n + r)
  14290. print(tail_sum(3, 0) + 36)
  14291. \end{lstlisting}
  14292. \fi}
  14293. \end{center}
  14294. At a tail call, the frame of the caller is no longer needed, so we can
  14295. pop the caller's frame before making the tail call. With this
  14296. approach, a recursive function that makes only tail calls ends up
  14297. using a constant amount of stack space. Functional languages like
  14298. Racket rely heavily on recursive functions, so the definition of
  14299. Racket \emph{requires} that all tail calls be optimized in this way.
  14300. \index{subject}{frame}
  14301. Some care is needed with regard to argument passing in tail calls. As
  14302. mentioned, for arguments beyond the sixth, the convention is to use
  14303. space in the caller's frame for passing arguments. However, for a
  14304. tail call we pop the caller's frame and can no longer use it. An
  14305. alternative is to use space in the callee's frame for passing
  14306. arguments. However, this option is also problematic because the caller
  14307. and callee's frames overlap in memory. As we begin to copy the
  14308. arguments from their sources in the caller's frame, the target
  14309. locations in the callee's frame might collide with the sources for
  14310. later arguments! We solve this problem by using the heap instead of
  14311. the stack for passing more than six arguments
  14312. (section~\ref{sec:limit-functions-r4}).
  14313. As mentioned, for a tail call we pop the caller's frame prior to
  14314. making the tail call. The instructions for popping a frame are the
  14315. instructions that we usually place in the conclusion of a
  14316. function. Thus, we also need to place such code immediately before
  14317. each tail call. These instructions include restoring the callee-saved
  14318. registers, so it is fortunate that the argument passing registers are
  14319. all caller-saved registers.
  14320. One note remains regarding which instruction to use to make the tail
  14321. call. When the callee is finished, it should not return to the current
  14322. function but instead return to the function that called the current
  14323. one. Thus, the return address that is already on the stack is the
  14324. right one, and we should not use \key{callq} to make the tail call
  14325. because that would overwrite the return address. Instead we simply use
  14326. the \key{jmp} instruction. As with the indirect function call, we write
  14327. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14328. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14329. jump target because the conclusion can overwrite just about everything
  14330. else.
  14331. \begin{lstlisting}
  14332. jmp *%rax
  14333. \end{lstlisting}
  14334. \section{Shrink \LangFun{}}
  14335. \label{sec:shrink-r4}
  14336. The \code{shrink} pass performs a minor modification to ease the
  14337. later passes. This pass introduces an explicit \code{main} function
  14338. that gobbles up all the top-level statements of the module.
  14339. %
  14340. \racket{It also changes the top \code{ProgramDefsExp} form to
  14341. \code{ProgramDefs}.}
  14342. {\if\edition\racketEd
  14343. \begin{lstlisting}
  14344. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14345. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14346. \end{lstlisting}
  14347. where $\itm{mainDef}$ is
  14348. \begin{lstlisting}
  14349. (Def 'main '() 'Integer '() |$\Exp'$|)
  14350. \end{lstlisting}
  14351. \fi}
  14352. {\if\edition\pythonEd\pythonColor
  14353. \begin{lstlisting}
  14354. Module(|$\Def\ldots\Stmt\ldots$|)
  14355. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14356. \end{lstlisting}
  14357. where $\itm{mainDef}$ is
  14358. \begin{lstlisting}
  14359. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14360. \end{lstlisting}
  14361. \fi}
  14362. \section{Reveal Functions and the \LangFunRef{} Language}
  14363. \label{sec:reveal-functions-r4}
  14364. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14365. in that it conflates the use of function names and local
  14366. variables. This is a problem because we need to compile the use of a
  14367. function name differently from the use of a local variable. In
  14368. particular, we use \code{leaq} to convert the function name (a label
  14369. in x86) to an address in a register. Thus, we create a new pass that
  14370. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14371. $n$ is the arity of the function.\python{\footnote{The arity is not
  14372. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14373. This pass is named \code{reveal\_functions} and the output language
  14374. is \LangFunRef{}.
  14375. %is defined in figure~\ref{fig:f1-syntax}.
  14376. %% The concrete syntax for a
  14377. %% function reference is $\CFUNREF{f}$.
  14378. %% \begin{figure}[tp]
  14379. %% \centering
  14380. %% \fbox{
  14381. %% \begin{minipage}{0.96\textwidth}
  14382. %% {\if\edition\racketEd
  14383. %% \[
  14384. %% \begin{array}{lcl}
  14385. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14386. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14387. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14388. %% \end{array}
  14389. %% \]
  14390. %% \fi}
  14391. %% {\if\edition\pythonEd\pythonColor
  14392. %% \[
  14393. %% \begin{array}{lcl}
  14394. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14395. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14396. %% \end{array}
  14397. %% \]
  14398. %% \fi}
  14399. %% \end{minipage}
  14400. %% }
  14401. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14402. %% (figure~\ref{fig:Lfun-syntax}).}
  14403. %% \label{fig:f1-syntax}
  14404. %% \end{figure}
  14405. %% Distinguishing between calls in tail position and non-tail position
  14406. %% requires the pass to have some notion of context. We recommend using
  14407. %% two mutually recursive functions, one for processing expressions in
  14408. %% tail position and another for the rest.
  14409. \racket{Placing this pass after \code{uniquify} will make sure that
  14410. there are no local variables and functions that share the same
  14411. name.}
  14412. %
  14413. The \code{reveal\_functions} pass should come before the
  14414. \code{remove\_complex\_operands} pass because function references
  14415. should be categorized as complex expressions.
  14416. \section{Limit Functions}
  14417. \label{sec:limit-functions-r4}
  14418. Recall that we wish to limit the number of function parameters to six
  14419. so that we do not need to use the stack for argument passing, which
  14420. makes it easier to implement efficient tail calls. However, because
  14421. the input language \LangFun{} supports arbitrary numbers of function
  14422. arguments, we have some work to do! The \code{limit\_functions} pass
  14423. transforms functions and function calls that involve more than six
  14424. arguments to pass the first five arguments as usual, but it packs the
  14425. rest of the arguments into a tuple and passes it as the sixth
  14426. argument.\footnote{The implementation this pass can be postponed to
  14427. last because you can test the rest of the passes on functions with
  14428. six or fewer parameters.}
  14429. Each function definition with seven or more parameters is transformed as
  14430. follows:
  14431. {\if\edition\racketEd
  14432. \begin{lstlisting}
  14433. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14434. |$\Rightarrow$|
  14435. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14436. \end{lstlisting}
  14437. \fi}
  14438. {\if\edition\pythonEd\pythonColor
  14439. \begin{lstlisting}
  14440. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14441. |$\Rightarrow$|
  14442. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14443. |$T_r$|, None, |$\itm{body}'$|, None)
  14444. \end{lstlisting}
  14445. \fi}
  14446. %
  14447. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14448. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14449. the $k$th element of the tuple, where $k = i - 6$.
  14450. %
  14451. {\if\edition\racketEd
  14452. \begin{lstlisting}
  14453. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14454. \end{lstlisting}
  14455. \fi}
  14456. {\if\edition\pythonEd\pythonColor
  14457. \begin{lstlisting}
  14458. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14459. \end{lstlisting}
  14460. \fi}
  14461. For function calls with too many arguments, the \code{limit\_functions}
  14462. pass transforms them in the following way:
  14463. \begin{tabular}{lll}
  14464. \begin{minipage}{0.3\textwidth}
  14465. {\if\edition\racketEd
  14466. \begin{lstlisting}
  14467. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14468. \end{lstlisting}
  14469. \fi}
  14470. {\if\edition\pythonEd\pythonColor
  14471. \begin{lstlisting}
  14472. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14473. \end{lstlisting}
  14474. \fi}
  14475. \end{minipage}
  14476. &
  14477. $\Rightarrow$
  14478. &
  14479. \begin{minipage}{0.5\textwidth}
  14480. {\if\edition\racketEd
  14481. \begin{lstlisting}
  14482. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14483. \end{lstlisting}
  14484. \fi}
  14485. {\if\edition\pythonEd\pythonColor
  14486. \begin{lstlisting}
  14487. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14488. \end{lstlisting}
  14489. \fi}
  14490. \end{minipage}
  14491. \end{tabular}
  14492. \section{Remove Complex Operands}
  14493. \label{sec:rco-r4}
  14494. The primary decisions to make for this pass are whether to classify
  14495. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14496. atomic or complex expressions. Recall that an atomic expression
  14497. ends up as an immediate argument of an x86 instruction. Function
  14498. application translates to a sequence of instructions, so
  14499. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14500. a complex expression. On the other hand, the arguments of
  14501. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14502. expressions.
  14503. %
  14504. Regarding \code{FunRef}, as discussed previously, the function label
  14505. needs to be converted to an address using the \code{leaq}
  14506. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14507. needs to be classified as a complex expression so that we generate an
  14508. assignment statement with a left-hand side that can serve as the
  14509. target of the \code{leaq}.
  14510. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14511. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14512. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14513. and augments programs to include a list of function definitions.
  14514. %
  14515. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14516. \newcommand{\LfunMonadASTRacket}{
  14517. \begin{array}{lcl}
  14518. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14519. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14520. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14521. \end{array}
  14522. }
  14523. \newcommand{\LfunMonadASTPython}{
  14524. \begin{array}{lcl}
  14525. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14526. \MID \key{TupleType}\LS\Type^+\RS\\
  14527. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14528. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14529. \Stmt &::=& \RETURN{\Exp} \\
  14530. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14531. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14532. \end{array}
  14533. }
  14534. \begin{figure}[tp]
  14535. \centering
  14536. \begin{tcolorbox}[colback=white]
  14537. \small
  14538. {\if\edition\racketEd
  14539. \[
  14540. \begin{array}{l}
  14541. \gray{\LvarMonadASTRacket} \\ \hline
  14542. \gray{\LifMonadASTRacket} \\ \hline
  14543. \gray{\LwhileMonadASTRacket} \\ \hline
  14544. \gray{\LtupMonadASTRacket} \\ \hline
  14545. \LfunMonadASTRacket \\
  14546. \begin{array}{rcl}
  14547. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14548. \end{array}
  14549. \end{array}
  14550. \]
  14551. \fi}
  14552. {\if\edition\pythonEd\pythonColor
  14553. \[
  14554. \begin{array}{l}
  14555. \gray{\LvarMonadASTPython} \\ \hline
  14556. \gray{\LifMonadASTPython} \\ \hline
  14557. \gray{\LwhileMonadASTPython} \\ \hline
  14558. \gray{\LtupMonadASTPython} \\ \hline
  14559. \LfunMonadASTPython \\
  14560. \begin{array}{rcl}
  14561. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14562. \end{array}
  14563. \end{array}
  14564. \]
  14565. \fi}
  14566. \end{tcolorbox}
  14567. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14568. \label{fig:Lfun-anf-syntax}
  14569. \end{figure}
  14570. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14571. %% \LangFunANF{} of this pass.
  14572. %% \begin{figure}[tp]
  14573. %% \centering
  14574. %% \fbox{
  14575. %% \begin{minipage}{0.96\textwidth}
  14576. %% \small
  14577. %% \[
  14578. %% \begin{array}{rcl}
  14579. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14580. %% \MID \VOID{} } \\
  14581. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14582. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14583. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14584. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14585. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14586. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14587. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14588. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14589. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14590. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14591. %% \end{array}
  14592. %% \]
  14593. %% \end{minipage}
  14594. %% }
  14595. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14596. %% \label{fig:Lfun-anf-syntax}
  14597. %% \end{figure}
  14598. \section{Explicate Control and the \LangCFun{} Language}
  14599. \label{sec:explicate-control-r4}
  14600. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14601. output of \code{explicate\_control}.
  14602. %
  14603. %% \racket{(The concrete syntax is given in
  14604. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14605. %
  14606. The auxiliary functions for assignment\racket{ and tail contexts} should
  14607. be updated with cases for
  14608. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14609. function for predicate context should be updated for
  14610. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14611. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14612. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14613. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14614. auxiliary function for processing function definitions. This code is
  14615. similar to the case for \code{Program} in \LangVec{}. The top-level
  14616. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14617. form of \LangFun{} can then apply this new function to all the
  14618. function definitions.
  14619. {\if\edition\pythonEd\pythonColor
  14620. The translation of \code{Return} statements requires a new auxiliary
  14621. function to handle expressions in tail context, called
  14622. \code{explicate\_tail}. The function should take an expression and the
  14623. dictionary of basic blocks and produce a list of statements in the
  14624. \LangCFun{} language. The \code{explicate\_tail} function should
  14625. include cases for \code{Begin}, \code{IfExp}, \code{Let}, and \code{Call},
  14626. and a default case for other kinds of expressions. The default case
  14627. should produce a \code{Return} statement. The case for \code{Call}
  14628. should change it into \code{TailCall}. The other cases should
  14629. recursively process their subexpressions and statements, choosing the
  14630. appropriate explicate functions for the various contexts.
  14631. \fi}
  14632. \newcommand{\CfunASTRacket}{
  14633. \begin{array}{lcl}
  14634. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14635. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14636. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14637. \end{array}
  14638. }
  14639. \newcommand{\CfunASTPython}{
  14640. \begin{array}{lcl}
  14641. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14642. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14643. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14644. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14645. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14646. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14647. \end{array}
  14648. }
  14649. \begin{figure}[tp]
  14650. \begin{tcolorbox}[colback=white]
  14651. \small
  14652. {\if\edition\racketEd
  14653. \[
  14654. \begin{array}{l}
  14655. \gray{\CvarASTRacket} \\ \hline
  14656. \gray{\CifASTRacket} \\ \hline
  14657. \gray{\CloopASTRacket} \\ \hline
  14658. \gray{\CtupASTRacket} \\ \hline
  14659. \CfunASTRacket \\
  14660. \begin{array}{lcl}
  14661. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14662. \end{array}
  14663. \end{array}
  14664. \]
  14665. \fi}
  14666. {\if\edition\pythonEd\pythonColor
  14667. \[
  14668. \begin{array}{l}
  14669. \gray{\CifASTPython} \\ \hline
  14670. \gray{\CtupASTPython} \\ \hline
  14671. \CfunASTPython \\
  14672. \begin{array}{lcl}
  14673. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14674. \end{array}
  14675. \end{array}
  14676. \]
  14677. \fi}
  14678. \end{tcolorbox}
  14679. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14680. \label{fig:c3-syntax}
  14681. \end{figure}
  14682. \clearpage
  14683. \section{Select Instructions and the \LangXIndCall{} Language}
  14684. \label{sec:select-r4}
  14685. \index{subject}{select instructions}
  14686. The output of select instructions is a program in the \LangXIndCall{}
  14687. language; the definition of its concrete syntax is shown in
  14688. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14689. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14690. directive on the labels of function definitions to make sure the
  14691. bottom three bits are zero, which we put to use in
  14692. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14693. this section. \index{subject}{x86}
  14694. \newcommand{\GrammarXIndCall}{
  14695. \begin{array}{lcl}
  14696. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14697. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14698. \Block &::= & \Instr^{+} \\
  14699. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14700. \end{array}
  14701. }
  14702. \newcommand{\ASTXIndCallRacket}{
  14703. \begin{array}{lcl}
  14704. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14705. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14706. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14707. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14708. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14709. \end{array}
  14710. }
  14711. \begin{figure}[tp]
  14712. \begin{tcolorbox}[colback=white]
  14713. \small
  14714. \[
  14715. \begin{array}{l}
  14716. \gray{\GrammarXInt} \\ \hline
  14717. \gray{\GrammarXIf} \\ \hline
  14718. \gray{\GrammarXGlobal} \\ \hline
  14719. \GrammarXIndCall \\
  14720. \begin{array}{lcl}
  14721. \LangXIndCallM{} &::= & \Def^{*}
  14722. \end{array}
  14723. \end{array}
  14724. \]
  14725. \end{tcolorbox}
  14726. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14727. \label{fig:x86-3-concrete}
  14728. \end{figure}
  14729. \begin{figure}[tp]
  14730. \begin{tcolorbox}[colback=white]
  14731. \small
  14732. {\if\edition\racketEd
  14733. \[\arraycolsep=3pt
  14734. \begin{array}{l}
  14735. \gray{\ASTXIntRacket} \\ \hline
  14736. \gray{\ASTXIfRacket} \\ \hline
  14737. \gray{\ASTXGlobalRacket} \\ \hline
  14738. \ASTXIndCallRacket \\
  14739. \begin{array}{lcl}
  14740. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14741. \end{array}
  14742. \end{array}
  14743. \]
  14744. \fi}
  14745. {\if\edition\pythonEd\pythonColor
  14746. \[
  14747. \begin{array}{lcl}
  14748. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14749. \MID \BYTEREG{\Reg} } \\
  14750. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14751. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14752. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14753. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14754. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14755. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14756. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14757. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14758. \end{array}
  14759. \]
  14760. \fi}
  14761. \end{tcolorbox}
  14762. \caption{The abstract syntax of \LangXIndCall{} (extends
  14763. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14764. \label{fig:x86-3}
  14765. \end{figure}
  14766. An assignment of a function reference to a variable becomes a
  14767. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14768. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14769. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14770. node, whose concrete syntax is instruction-pointer-relative
  14771. addressing.
  14772. \begin{center}
  14773. \begin{tabular}{lcl}
  14774. \begin{minipage}{0.35\textwidth}
  14775. {\if\edition\racketEd
  14776. \begin{lstlisting}
  14777. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14778. \end{lstlisting}
  14779. \fi}
  14780. {\if\edition\pythonEd\pythonColor
  14781. \begin{lstlisting}
  14782. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14783. \end{lstlisting}
  14784. \fi}
  14785. \end{minipage}
  14786. &
  14787. $\Rightarrow$\qquad\qquad
  14788. &
  14789. \begin{minipage}{0.3\textwidth}
  14790. \begin{lstlisting}
  14791. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14792. \end{lstlisting}
  14793. \end{minipage}
  14794. \end{tabular}
  14795. \end{center}
  14796. Regarding function definitions, we need to remove the parameters and
  14797. instead perform parameter passing using the conventions discussed in
  14798. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14799. registers. We recommend turning the parameters into local variables
  14800. and generating instructions at the beginning of the function to move
  14801. from the argument-passing registers
  14802. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14803. {\if\edition\racketEd
  14804. \begin{lstlisting}
  14805. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14806. |$\Rightarrow$|
  14807. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14808. \end{lstlisting}
  14809. \fi}
  14810. {\if\edition\pythonEd\pythonColor
  14811. \begin{lstlisting}
  14812. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14813. |$\Rightarrow$|
  14814. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14815. \end{lstlisting}
  14816. \fi}
  14817. The basic blocks $B'$ are the same as $B$ except that the
  14818. \code{start} block is modified to add the instructions for moving from
  14819. the argument registers to the parameter variables. So the \code{start}
  14820. block of $B$ shown on the left of the following is changed to the code
  14821. on the right:
  14822. \begin{center}
  14823. \begin{minipage}{0.3\textwidth}
  14824. \begin{lstlisting}
  14825. start:
  14826. |$\itm{instr}_1$|
  14827. |$\cdots$|
  14828. |$\itm{instr}_n$|
  14829. \end{lstlisting}
  14830. \end{minipage}
  14831. $\Rightarrow$
  14832. \begin{minipage}{0.3\textwidth}
  14833. \begin{lstlisting}
  14834. |$f$|start:
  14835. movq %rdi, |$x_1$|
  14836. movq %rsi, |$x_2$|
  14837. |$\cdots$|
  14838. |$\itm{instr}_1$|
  14839. |$\cdots$|
  14840. |$\itm{instr}_n$|
  14841. \end{lstlisting}
  14842. \end{minipage}
  14843. \end{center}
  14844. Recall that we use the label \code{start} for the initial block of a
  14845. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14846. the conclusion of the program with \code{conclusion}, so that
  14847. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14848. by a jump to \code{conclusion}. With the addition of function
  14849. definitions, there is a start block and conclusion for each function,
  14850. but their labels need to be unique. We recommend prepending the
  14851. function's name to \code{start} and \code{conclusion}, respectively,
  14852. to obtain unique labels.
  14853. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14854. number of parameters the function expects, but the parameters are no
  14855. longer in the syntax of function definitions. Instead, add an entry
  14856. to $\itm{info}$ that maps \code{num-params} to the number of
  14857. parameters to construct $\itm{info}'$.}
  14858. By changing the parameters to local variables, we are giving the
  14859. register allocator control over which registers or stack locations to
  14860. use for them. If you implement the move-biasing challenge
  14861. (section~\ref{sec:move-biasing}), the register allocator will try to
  14862. assign the parameter variables to the corresponding argument register,
  14863. in which case the \code{patch\_instructions} pass will remove the
  14864. \code{movq} instruction. This happens in the example translation given
  14865. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14866. the \code{add} function.
  14867. %
  14868. Also, note that the register allocator will perform liveness analysis
  14869. on this sequence of move instructions and build the interference
  14870. graph. So, for example, $x_1$ will be marked as interfering with
  14871. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14872. which is good because otherwise the first \code{movq} would overwrite
  14873. the argument in \code{rsi} that is needed for $x_2$.
  14874. Next, consider the compilation of function calls. In the mirror image
  14875. of the handling of parameters in function definitions, the arguments
  14876. are moved to the argument-passing registers. Note that the function
  14877. is not given as a label, but its address is produced by the argument
  14878. $\itm{arg}_0$. So, we translate the call into an indirect function
  14879. call. The return value from the function is stored in \code{rax}, so
  14880. it needs to be moved into the \itm{lhs}.
  14881. \begin{lstlisting}
  14882. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14883. |$\Rightarrow$|
  14884. movq |$\itm{arg}_1$|, %rdi
  14885. movq |$\itm{arg}_2$|, %rsi
  14886. |$\vdots$|
  14887. callq *|$\itm{arg}_0$|
  14888. movq %rax, |$\itm{lhs}$|
  14889. \end{lstlisting}
  14890. The \code{IndirectCallq} AST node includes an integer for the arity of
  14891. the function, that is, the number of parameters. That information is
  14892. useful in the \code{uncover\_live} pass for determining which
  14893. argument-passing registers are potentially read during the call.
  14894. For tail calls, the parameter passing is the same as non-tail calls:
  14895. generate instructions to move the arguments into the argument-passing
  14896. registers. After that we need to pop the frame from the procedure
  14897. call stack. However, we do not yet know how big the frame is; that
  14898. gets determined during register allocation. So, instead of generating
  14899. those instructions here, we invent a new instruction that means ``pop
  14900. the frame and then do an indirect jump,'' which we name
  14901. \code{TailJmp}. The abstract syntax for this instruction includes an
  14902. argument that specifies where to jump and an integer that represents
  14903. the arity of the function being called.
  14904. \section{Register Allocation}
  14905. \label{sec:register-allocation-r4}
  14906. The addition of functions requires some changes to all three aspects
  14907. of register allocation, which we discuss in the following subsections.
  14908. \subsection{Liveness Analysis}
  14909. \label{sec:liveness-analysis-r4}
  14910. \index{subject}{liveness analysis}
  14911. %% The rest of the passes need only minor modifications to handle the new
  14912. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14913. %% \code{leaq}.
  14914. The \code{IndirectCallq} instruction should be treated like
  14915. \code{Callq} regarding its written locations $W$, in that they should
  14916. include all the caller-saved registers. Recall that the reason for
  14917. that is to force variables that are live across a function call to be assigned to callee-saved
  14918. registers or to be spilled to the stack.
  14919. Regarding the set of read locations $R$, the arity fields of
  14920. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14921. argument-passing registers should be considered as read by those
  14922. instructions. Also, the target field of \code{TailJmp} and
  14923. \code{IndirectCallq} should be included in the set of read locations
  14924. $R$.
  14925. \subsection{Build Interference Graph}
  14926. \label{sec:build-interference-r4}
  14927. With the addition of function definitions, we compute a separate interference
  14928. graph for each function (not just one for the whole program).
  14929. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14930. spill tuple-typed variables that are live during a call to
  14931. \code{collect}, the garbage collector. With the addition of functions
  14932. to our language, we need to revisit this issue. Functions that perform
  14933. allocation contain calls to the collector. Thus, we should not only
  14934. spill a tuple-typed variable when it is live during a call to
  14935. \code{collect}, but we should spill the variable if it is live during
  14936. a call to any user-defined function. Thus, in the
  14937. \code{build\_interference} pass, we recommend adding interference
  14938. edges between call-live tuple-typed variables and the callee-saved
  14939. registers (in addition to creating edges between
  14940. call-live variables and the caller-saved registers).
  14941. \subsection{Allocate Registers}
  14942. The primary change to the \code{allocate\_registers} pass is adding an
  14943. auxiliary function for handling definitions (the \Def{} nonterminal
  14944. shown in figure~\ref{fig:x86-3}) with one case for function
  14945. definitions. The logic is the same as described in
  14946. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14947. allocation is performed many times, once for each function definition,
  14948. instead of just once for the whole program.
  14949. \section{Patch Instructions}
  14950. In \code{patch\_instructions}, you should deal with the x86
  14951. idiosyncrasy that the destination argument of \code{leaq} must be a
  14952. register. Additionally, you should ensure that the argument of
  14953. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14954. trample many other registers before the tail call, as explained in the
  14955. next section.
  14956. \section{Prelude and Conclusion}
  14957. Now that register allocation is complete, we can translate the
  14958. \code{TailJmp} into a sequence of instructions. A naive translation of
  14959. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14960. before the jump we need to pop the current frame to achieve efficient
  14961. tail calls. This sequence of instructions is the same as the code for
  14962. the conclusion of a function, except that the \code{retq} is replaced with
  14963. \code{jmp *$\itm{arg}$}.
  14964. Regarding function definitions, we generate a prelude and conclusion
  14965. for each one. This code is similar to the prelude and conclusion
  14966. generated for the \code{main} function presented in
  14967. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14968. carry out the following steps:
  14969. % TODO: .align the functions!
  14970. \begin{enumerate}
  14971. %% \item Start with \code{.global} and \code{.align} directives followed
  14972. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14973. %% example.)
  14974. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14975. pointer.
  14976. \item Push to the stack all the callee-saved registers that were
  14977. used for register allocation.
  14978. \item Move the stack pointer \code{rsp} down to make room for the
  14979. regular spills (aligned to 16 bytes).
  14980. \item Move the root stack pointer \code{r15} up by the size of the
  14981. root-stack frame for this function, which depends on the number of
  14982. spilled tuple-typed variables. \label{root-stack-init}
  14983. \item Initialize to zero all new entries in the root-stack frame.
  14984. \item Jump to the start block.
  14985. \end{enumerate}
  14986. The prelude of the \code{main} function has an additional task: call
  14987. the \code{initialize} function to set up the garbage collector, and
  14988. then move the value of the global \code{rootstack\_begin} in
  14989. \code{r15}. This initialization should happen before step
  14990. \ref{root-stack-init}, which depends on \code{r15}.
  14991. The conclusion of every function should do the following:
  14992. \begin{enumerate}
  14993. \item Move the stack pointer back up past the regular spills.
  14994. \item Restore the callee-saved registers by popping them from the
  14995. stack.
  14996. \item Move the root stack pointer back down by the size of the
  14997. root-stack frame for this function.
  14998. \item Restore \code{rbp} by popping it from the stack.
  14999. \item Return to the caller with the \code{retq} instruction.
  15000. \end{enumerate}
  15001. The output of this pass is \LangXIndCallFlat{}, which differs from
  15002. \LangXIndCall{} in that there is no longer an AST node for function
  15003. definitions. Instead, a program is just an association list of basic
  15004. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15005. \[
  15006. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15007. \]
  15008. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15009. compiling \LangFun{} to x86.
  15010. \begin{exercise}\normalfont\normalsize
  15011. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15012. Create eight new programs that use functions including examples that
  15013. pass functions and return functions from other functions, recursive
  15014. functions, functions that create vectors, and functions that make tail
  15015. calls. Test your compiler on these new programs and all your
  15016. previously created test programs.
  15017. \end{exercise}
  15018. \begin{figure}[tbp]
  15019. \begin{tcolorbox}[colback=white]
  15020. {\if\edition\racketEd
  15021. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15022. \node (Lfun) at (0,2) {\large \LangFun{}};
  15023. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15024. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15025. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15026. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15027. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15028. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15029. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15030. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15031. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15032. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15033. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15034. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15035. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15036. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15037. \path[->,bend left=15] (Lfun) edge [above] node
  15038. {\ttfamily\footnotesize shrink} (Lfun-1);
  15039. \path[->,bend left=15] (Lfun-1) edge [above] node
  15040. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15041. \path[->,bend left=15] (Lfun-2) edge [above] node
  15042. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15043. \path[->,bend left=15] (F1-1) edge [left] node
  15044. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15045. \path[->,bend left=15] (F1-2) edge [below] node
  15046. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15047. \path[->,bend left=15] (F1-3) edge [below] node
  15048. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15049. \path[->,bend right=15] (F1-4) edge [above] node
  15050. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15051. \path[->,bend right=15] (F1-5) edge [right] node
  15052. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15053. \path[->,bend right=15] (C3-2) edge [right] node
  15054. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15055. \path[->,bend left=15] (x86-2) edge [right] node
  15056. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15057. \path[->,bend right=15] (x86-2-1) edge [below] node
  15058. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15059. \path[->,bend right=15] (x86-2-2) edge [right] node
  15060. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15061. \path[->,bend left=15] (x86-3) edge [above] node
  15062. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15063. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15064. \end{tikzpicture}
  15065. \fi}
  15066. {\if\edition\pythonEd\pythonColor
  15067. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15068. \node (Lfun) at (0,2) {\large \LangFun{}};
  15069. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15070. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15071. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15072. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15073. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15074. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15075. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15076. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15077. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15078. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15079. \path[->,bend left=15] (Lfun) edge [above] node
  15080. {\ttfamily\footnotesize shrink} (Lfun-2);
  15081. \path[->,bend left=15] (Lfun-2) edge [above] node
  15082. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15083. \path[->,bend left=15] (F1-1) edge [above] node
  15084. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15085. \path[->,bend left=15] (F1-2) edge [right] node
  15086. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15087. \path[->,bend right=15] (F1-4) edge [above] node
  15088. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15089. \path[->,bend right=15] (F1-5) edge [right] node
  15090. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15091. \path[->,bend left=15] (C3-2) edge [right] node
  15092. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15093. \path[->,bend right=15] (x86-2) edge [below] node
  15094. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15095. \path[->,bend left=15] (x86-3) edge [above] node
  15096. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15097. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15098. \end{tikzpicture}
  15099. \fi}
  15100. \end{tcolorbox}
  15101. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15102. \label{fig:Lfun-passes}
  15103. \end{figure}
  15104. \section{An Example Translation}
  15105. \label{sec:functions-example}
  15106. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15107. function in \LangFun{} to x86. The figure includes the results of
  15108. \code{explicate\_control} and \code{select\_instructions}.
  15109. \begin{figure}[hbtp]
  15110. \begin{tcolorbox}[colback=white]
  15111. \begin{tabular}{ll}
  15112. \begin{minipage}{0.4\textwidth}
  15113. % s3_2.rkt
  15114. {\if\edition\racketEd
  15115. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15116. (define (add [x : Integer]
  15117. [y : Integer])
  15118. : Integer
  15119. (+ x y))
  15120. (add 40 2)
  15121. \end{lstlisting}
  15122. \fi}
  15123. {\if\edition\pythonEd\pythonColor
  15124. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15125. def add(x:int, y:int) -> int:
  15126. return x + y
  15127. print(add(40, 2))
  15128. \end{lstlisting}
  15129. \fi}
  15130. $\Downarrow$
  15131. {\if\edition\racketEd
  15132. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15133. (define (add86 [x87 : Integer]
  15134. [y88 : Integer])
  15135. : Integer
  15136. add86start:
  15137. return (+ x87 y88);
  15138. )
  15139. (define (main) : Integer ()
  15140. mainstart:
  15141. tmp89 = (fun-ref add86 2);
  15142. (tail-call tmp89 40 2)
  15143. )
  15144. \end{lstlisting}
  15145. \fi}
  15146. {\if\edition\pythonEd\pythonColor
  15147. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15148. def add(x:int, y:int) -> int:
  15149. addstart:
  15150. return x + y
  15151. def main() -> int:
  15152. mainstart:
  15153. fun.0 = add
  15154. tmp.1 = fun.0(40, 2)
  15155. print(tmp.1)
  15156. return 0
  15157. \end{lstlisting}
  15158. \fi}
  15159. \end{minipage}
  15160. &
  15161. $\Rightarrow$
  15162. \begin{minipage}{0.5\textwidth}
  15163. {\if\edition\racketEd
  15164. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15165. (define (add86) : Integer
  15166. add86start:
  15167. movq %rdi, x87
  15168. movq %rsi, y88
  15169. movq x87, %rax
  15170. addq y88, %rax
  15171. jmp inc1389conclusion
  15172. )
  15173. (define (main) : Integer
  15174. mainstart:
  15175. leaq (fun-ref add86 2), tmp89
  15176. movq $40, %rdi
  15177. movq $2, %rsi
  15178. tail-jmp tmp89
  15179. )
  15180. \end{lstlisting}
  15181. \fi}
  15182. {\if\edition\pythonEd\pythonColor
  15183. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15184. def add() -> int:
  15185. addstart:
  15186. movq %rdi, x
  15187. movq %rsi, y
  15188. movq x, %rax
  15189. addq y, %rax
  15190. jmp addconclusion
  15191. def main() -> int:
  15192. mainstart:
  15193. leaq add, fun.0
  15194. movq $40, %rdi
  15195. movq $2, %rsi
  15196. callq *fun.0
  15197. movq %rax, tmp.1
  15198. movq tmp.1, %rdi
  15199. callq print_int
  15200. movq $0, %rax
  15201. jmp mainconclusion
  15202. \end{lstlisting}
  15203. \fi}
  15204. $\Downarrow$
  15205. \end{minipage}
  15206. \end{tabular}
  15207. \begin{tabular}{ll}
  15208. \begin{minipage}{0.3\textwidth}
  15209. {\if\edition\racketEd
  15210. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15211. .globl add86
  15212. .align 8
  15213. add86:
  15214. pushq %rbp
  15215. movq %rsp, %rbp
  15216. jmp add86start
  15217. add86start:
  15218. movq %rdi, %rax
  15219. addq %rsi, %rax
  15220. jmp add86conclusion
  15221. add86conclusion:
  15222. popq %rbp
  15223. retq
  15224. \end{lstlisting}
  15225. \fi}
  15226. {\if\edition\pythonEd\pythonColor
  15227. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15228. .align 8
  15229. add:
  15230. pushq %rbp
  15231. movq %rsp, %rbp
  15232. subq $0, %rsp
  15233. jmp addstart
  15234. addstart:
  15235. movq %rdi, %rdx
  15236. movq %rsi, %rcx
  15237. movq %rdx, %rax
  15238. addq %rcx, %rax
  15239. jmp addconclusion
  15240. addconclusion:
  15241. subq $0, %r15
  15242. addq $0, %rsp
  15243. popq %rbp
  15244. retq
  15245. \end{lstlisting}
  15246. \fi}
  15247. \end{minipage}
  15248. &
  15249. \begin{minipage}{0.5\textwidth}
  15250. {\if\edition\racketEd
  15251. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15252. .globl main
  15253. .align 8
  15254. main:
  15255. pushq %rbp
  15256. movq %rsp, %rbp
  15257. movq $16384, %rdi
  15258. movq $16384, %rsi
  15259. callq initialize
  15260. movq rootstack_begin(%rip), %r15
  15261. jmp mainstart
  15262. mainstart:
  15263. leaq add86(%rip), %rcx
  15264. movq $40, %rdi
  15265. movq $2, %rsi
  15266. movq %rcx, %rax
  15267. popq %rbp
  15268. jmp *%rax
  15269. mainconclusion:
  15270. popq %rbp
  15271. retq
  15272. \end{lstlisting}
  15273. \fi}
  15274. {\if\edition\pythonEd\pythonColor
  15275. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15276. .globl main
  15277. .align 8
  15278. main:
  15279. pushq %rbp
  15280. movq %rsp, %rbp
  15281. subq $0, %rsp
  15282. movq $65536, %rdi
  15283. movq $65536, %rsi
  15284. callq initialize
  15285. movq rootstack_begin(%rip), %r15
  15286. jmp mainstart
  15287. mainstart:
  15288. leaq add(%rip), %rcx
  15289. movq $40, %rdi
  15290. movq $2, %rsi
  15291. callq *%rcx
  15292. movq %rax, %rcx
  15293. movq %rcx, %rdi
  15294. callq print_int
  15295. movq $0, %rax
  15296. jmp mainconclusion
  15297. mainconclusion:
  15298. subq $0, %r15
  15299. addq $0, %rsp
  15300. popq %rbp
  15301. retq
  15302. \end{lstlisting}
  15303. \fi}
  15304. \end{minipage}
  15305. \end{tabular}
  15306. \end{tcolorbox}
  15307. \caption{Example compilation of a simple function to x86.}
  15308. \label{fig:add-fun}
  15309. \end{figure}
  15310. % Challenge idea: inlining! (simple version)
  15311. % Further Reading
  15312. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15313. \chapter{Lexically Scoped Functions}
  15314. \label{ch:Llambda}
  15315. \setcounter{footnote}{0}
  15316. This chapter studies lexically scoped functions. Lexical
  15317. scoping\index{subject}{lexical scoping} means that a function's body
  15318. may refer to variables whose binding site is outside of the function,
  15319. in an enclosing scope.
  15320. %
  15321. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15322. in \LangLam{}, which extends \LangFun{} with the
  15323. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15324. functions. The body of the \key{lambda} refers to three variables:
  15325. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15326. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15327. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15328. function \code{f}}, and \code{x} is a parameter of function
  15329. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15330. result value. The main expression of the program includes two calls to
  15331. \code{f} with different arguments for \code{x}: first \code{5} and
  15332. then \code{3}. The functions returned from \code{f} are bound to
  15333. variables \code{g} and \code{h}. Even though these two functions were
  15334. created by the same \code{lambda}, they are really different functions
  15335. because they use different values for \code{x}. Applying \code{g} to
  15336. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15337. produces \code{22}, so the result of the program is \code{42}.
  15338. \begin{figure}[btp]
  15339. \begin{tcolorbox}[colback=white]
  15340. {\if\edition\racketEd
  15341. % lambda_test_21.rkt
  15342. \begin{lstlisting}
  15343. (define (f [x : Integer]) : (Integer -> Integer)
  15344. (let ([y 4])
  15345. (lambda: ([z : Integer]) : Integer
  15346. (+ x (+ y z)))))
  15347. (let ([g (f 5)])
  15348. (let ([h (f 3)])
  15349. (+ (g 11) (h 15))))
  15350. \end{lstlisting}
  15351. \fi}
  15352. {\if\edition\pythonEd\pythonColor
  15353. \begin{lstlisting}
  15354. def f(x : int) -> Callable[[int], int]:
  15355. y = 4
  15356. return lambda z: x + y + z
  15357. g = f(5)
  15358. h = f(3)
  15359. print(g(11) + h(15))
  15360. \end{lstlisting}
  15361. \fi}
  15362. \end{tcolorbox}
  15363. \caption{Example of a lexically scoped function.}
  15364. \label{fig:lexical-scoping}
  15365. \end{figure}
  15366. The approach that we take for implementing lexically scoped functions
  15367. is to compile them into top-level function definitions, translating
  15368. from \LangLam{} into \LangFun{}. However, the compiler must give
  15369. special treatment to variable occurrences such as \code{x} and
  15370. \code{y} in the body of the \code{lambda} shown in
  15371. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15372. may not refer to variables defined outside of it. To identify such
  15373. variable occurrences, we review the standard notion of free variable.
  15374. \begin{definition}\normalfont
  15375. A variable is \emph{free in expression} $e$ if the variable occurs
  15376. inside $e$ but does not have an enclosing definition that is also in
  15377. $e$.\index{subject}{free variable}
  15378. \end{definition}
  15379. For example, in the expression
  15380. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15381. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15382. only \code{x} and \code{y} are free in the following expression,
  15383. because \code{z} is defined by the \code{lambda}
  15384. {\if\edition\racketEd
  15385. \begin{lstlisting}
  15386. (lambda: ([z : Integer]) : Integer
  15387. (+ x (+ y z)))
  15388. \end{lstlisting}
  15389. \fi}
  15390. {\if\edition\pythonEd\pythonColor
  15391. \begin{lstlisting}
  15392. lambda z: x + y + z
  15393. \end{lstlisting}
  15394. \fi}
  15395. %
  15396. \noindent Thus the free variables of a \code{lambda} are the ones that
  15397. need special treatment. We need to transport at runtime the values
  15398. of those variables from the point where the \code{lambda} was created
  15399. to the point where the \code{lambda} is applied. An efficient solution
  15400. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15401. values of the free variables together with a function pointer into a
  15402. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15403. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15404. closure}
  15405. %
  15406. By design, we have all the ingredients to make closures:
  15407. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15408. function pointers. The function pointer resides at index $0$, and the
  15409. values for the free variables fill in the rest of the tuple.
  15410. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15411. to see how closures work. It is a three-step dance. The program calls
  15412. function \code{f}, which creates a closure for the \code{lambda}. The
  15413. closure is a tuple whose first element is a pointer to the top-level
  15414. function that we will generate for the \code{lambda}; the second
  15415. element is the value of \code{x}, which is \code{5}; and the third
  15416. element is \code{4}, the value of \code{y}. The closure does not
  15417. contain an element for \code{z} because \code{z} is not a free
  15418. variable of the \code{lambda}. Creating the closure is step 1 of the
  15419. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15420. shown in figure~\ref{fig:closures}.
  15421. %
  15422. The second call to \code{f} creates another closure, this time with
  15423. \code{3} in the second slot (for \code{x}). This closure is also
  15424. returned from \code{f} but bound to \code{h}, which is also shown in
  15425. figure~\ref{fig:closures}.
  15426. \begin{figure}[tbp]
  15427. \centering
  15428. \begin{minipage}{0.65\textwidth}
  15429. \begin{tcolorbox}[colback=white]
  15430. \includegraphics[width=\textwidth]{figs/closures}
  15431. \end{tcolorbox}
  15432. \end{minipage}
  15433. \caption{Flat closure representations for the two functions
  15434. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15435. \label{fig:closures}
  15436. \end{figure}
  15437. Continuing with the example, consider the application of \code{g} to
  15438. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15439. closure, we obtain the function pointer from the first element of the
  15440. closure and call it, passing in the closure itself and then the
  15441. regular arguments, in this case \code{11}. This technique for applying
  15442. a closure is step 2 of the dance.
  15443. %
  15444. But doesn't this \code{lambda} take only one argument, for parameter
  15445. \code{z}? The third and final step of the dance is generating a
  15446. top-level function for a \code{lambda}. We add an additional
  15447. parameter for the closure and insert an initialization at the beginning
  15448. of the function for each free variable, to bind those variables to the
  15449. appropriate elements from the closure parameter.
  15450. %
  15451. This three-step dance is known as \emph{closure
  15452. conversion}\index{subject}{closure conversion}. We discuss the
  15453. details of closure conversion in section~\ref{sec:closure-conversion}
  15454. and show the code generated from the example in
  15455. section~\ref{sec:example-lambda}. First, we define the syntax and
  15456. semantics of \LangLam{} in section~\ref{sec:r5}.
  15457. \section{The \LangLam{} Language}
  15458. \label{sec:r5}
  15459. The definitions of the concrete syntax and abstract syntax for
  15460. \LangLam{}, a language with anonymous functions and lexical scoping,
  15461. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15462. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15463. for \LangFun{}, which already has syntax for function application.
  15464. %
  15465. \python{The syntax also includes an assignment statement that includes
  15466. a type annotation for the variable on the left-hand side, which
  15467. facilitates the type checking of \code{lambda} expressions that we
  15468. discuss later in this section.}
  15469. %
  15470. \racket{The \code{procedure-arity} operation returns the number of parameters
  15471. of a given function, an operation that we need for the translation
  15472. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15473. %
  15474. \python{The \code{arity} operation returns the number of parameters of
  15475. a given function, an operation that we need for the translation
  15476. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15477. The \code{arity} operation is not in Python, but the same functionality
  15478. is available in a more complex form. We include \code{arity} in the
  15479. \LangLam{} source language to enable testing.}
  15480. \newcommand{\LlambdaGrammarRacket}{
  15481. \begin{array}{lcl}
  15482. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15483. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15484. \end{array}
  15485. }
  15486. \newcommand{\LlambdaASTRacket}{
  15487. \begin{array}{lcl}
  15488. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15489. \itm{op} &::=& \code{procedure-arity}
  15490. \end{array}
  15491. }
  15492. \newcommand{\LlambdaGrammarPython}{
  15493. \begin{array}{lcl}
  15494. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15495. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15496. \end{array}
  15497. }
  15498. \newcommand{\LlambdaASTPython}{
  15499. \begin{array}{lcl}
  15500. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15501. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15502. \end{array}
  15503. }
  15504. % include AnnAssign in ASTPython
  15505. \begin{figure}[tp]
  15506. \centering
  15507. \begin{tcolorbox}[colback=white]
  15508. \small
  15509. {\if\edition\racketEd
  15510. \[
  15511. \begin{array}{l}
  15512. \gray{\LintGrammarRacket{}} \\ \hline
  15513. \gray{\LvarGrammarRacket{}} \\ \hline
  15514. \gray{\LifGrammarRacket{}} \\ \hline
  15515. \gray{\LwhileGrammarRacket} \\ \hline
  15516. \gray{\LtupGrammarRacket} \\ \hline
  15517. \gray{\LfunGrammarRacket} \\ \hline
  15518. \LlambdaGrammarRacket \\
  15519. \begin{array}{lcl}
  15520. \LangLamM{} &::=& \Def\ldots \; \Exp
  15521. \end{array}
  15522. \end{array}
  15523. \]
  15524. \fi}
  15525. {\if\edition\pythonEd\pythonColor
  15526. \[
  15527. \begin{array}{l}
  15528. \gray{\LintGrammarPython{}} \\ \hline
  15529. \gray{\LvarGrammarPython{}} \\ \hline
  15530. \gray{\LifGrammarPython{}} \\ \hline
  15531. \gray{\LwhileGrammarPython} \\ \hline
  15532. \gray{\LtupGrammarPython} \\ \hline
  15533. \gray{\LfunGrammarPython} \\ \hline
  15534. \LlambdaGrammarPython \\
  15535. \begin{array}{lcl}
  15536. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15537. \end{array}
  15538. \end{array}
  15539. \]
  15540. \fi}
  15541. \end{tcolorbox}
  15542. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15543. with \key{lambda}.}
  15544. \label{fig:Llam-concrete-syntax}
  15545. \end{figure}
  15546. \begin{figure}[tp]
  15547. \centering
  15548. \begin{tcolorbox}[colback=white]
  15549. \small
  15550. {\if\edition\racketEd
  15551. \[\arraycolsep=3pt
  15552. \begin{array}{l}
  15553. \gray{\LintOpAST} \\ \hline
  15554. \gray{\LvarASTRacket{}} \\ \hline
  15555. \gray{\LifASTRacket{}} \\ \hline
  15556. \gray{\LwhileASTRacket{}} \\ \hline
  15557. \gray{\LtupASTRacket{}} \\ \hline
  15558. \gray{\LfunASTRacket} \\ \hline
  15559. \LlambdaASTRacket \\
  15560. \begin{array}{lcl}
  15561. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15562. \end{array}
  15563. \end{array}
  15564. \]
  15565. \fi}
  15566. {\if\edition\pythonEd\pythonColor
  15567. \[
  15568. \begin{array}{l}
  15569. \gray{\LintASTPython} \\ \hline
  15570. \gray{\LvarASTPython{}} \\ \hline
  15571. \gray{\LifASTPython{}} \\ \hline
  15572. \gray{\LwhileASTPython{}} \\ \hline
  15573. \gray{\LtupASTPython{}} \\ \hline
  15574. \gray{\LfunASTPython} \\ \hline
  15575. \LlambdaASTPython \\
  15576. \begin{array}{lcl}
  15577. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15578. \end{array}
  15579. \end{array}
  15580. \]
  15581. \fi}
  15582. \end{tcolorbox}
  15583. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15584. \label{fig:Llam-syntax}
  15585. \end{figure}
  15586. Figure~\ref{fig:interp-Llambda} shows the definitional
  15587. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15588. \key{Lambda} saves the current environment inside the returned
  15589. function value. Recall that during function application, the
  15590. environment stored in the function value, extended with the mapping of
  15591. parameters to argument values, is used to interpret the body of the
  15592. function.
  15593. \begin{figure}[tbp]
  15594. \begin{tcolorbox}[colback=white]
  15595. {\if\edition\racketEd
  15596. \begin{lstlisting}
  15597. (define interp-Llambda-class
  15598. (class interp-Lfun-class
  15599. (super-new)
  15600. (define/override (interp-op op)
  15601. (match op
  15602. ['procedure-arity
  15603. (lambda (v)
  15604. (match v
  15605. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15606. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15607. [else (super interp-op op)]))
  15608. (define/override ((interp-exp env) e)
  15609. (define recur (interp-exp env))
  15610. (match e
  15611. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15612. `(function ,xs ,body ,env)]
  15613. [else ((super interp-exp env) e)]))
  15614. ))
  15615. (define (interp-Llambda p)
  15616. (send (new interp-Llambda-class) interp-program p))
  15617. \end{lstlisting}
  15618. \fi}
  15619. {\if\edition\pythonEd\pythonColor
  15620. \begin{lstlisting}
  15621. class InterpLlambda(InterpLfun):
  15622. def arity(self, v):
  15623. match v:
  15624. case Function(name, params, body, env):
  15625. return len(params)
  15626. case _:
  15627. raise Exception('Llambda arity unexpected ' + repr(v))
  15628. def interp_exp(self, e, env):
  15629. match e:
  15630. case Call(Name('arity'), [fun]):
  15631. f = self.interp_exp(fun, env)
  15632. return self.arity(f)
  15633. case Lambda(params, body):
  15634. return Function('lambda', params, [Return(body)], env)
  15635. case _:
  15636. return super().interp_exp(e, env)
  15637. def interp_stmt(self, s, env, cont):
  15638. match s:
  15639. case AnnAssign(lhs, typ, value, simple):
  15640. env[lhs.id] = self.interp_exp(value, env)
  15641. return self.interp_stmts(cont, env)
  15642. case Pass():
  15643. return self.interp_stmts(cont, env)
  15644. case _:
  15645. return super().interp_stmt(s, env, cont)
  15646. \end{lstlisting}
  15647. \fi}
  15648. \end{tcolorbox}
  15649. \caption{Interpreter for \LangLam{}.}
  15650. \label{fig:interp-Llambda}
  15651. \end{figure}
  15652. {\if\edition\racketEd
  15653. %
  15654. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15655. \key{lambda} form. The body of the \key{lambda} is checked in an
  15656. environment that includes the current environment (because it is
  15657. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15658. require the body's type to match the declared return type.
  15659. %
  15660. \fi}
  15661. {\if\edition\pythonEd\pythonColor
  15662. %
  15663. Figures~\ref{fig:type-check-Llambda} and
  15664. \ref{fig:type-check-Llambda-part2} define the type checker for
  15665. \LangLam{}, which is more complex than one might expect. The reason
  15666. for the added complexity is that the syntax of \key{lambda} does not
  15667. include type annotations for the parameters or return type. Instead
  15668. they must be inferred. There are many approaches to type inference
  15669. from which to choose, of varying degrees of complexity. We choose one
  15670. of the simpler approaches, bidirectional type
  15671. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15672. book is compilation, not type inference.
  15673. The main idea of bidirectional type inference is to add an auxiliary
  15674. function, here named \code{check\_exp}, that takes an expected type
  15675. and checks whether the given expression is of that type. Thus, in
  15676. \code{check\_exp}, type information flows in a top-down manner with
  15677. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15678. function, where type information flows in a primarily bottom-up
  15679. manner.
  15680. %
  15681. The idea then is to use \code{check\_exp} in all the places where we
  15682. already know what the type of an expression should be, such as in the
  15683. \code{return} statement of a top-level function definition or on the
  15684. right-hand side of an annotated assignment statement.
  15685. With regard to \code{lambda}, it is straightforward to check a
  15686. \code{lambda} inside \code{check\_exp} because the expected type
  15687. provides the parameter types and the return type. On the other hand,
  15688. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15689. that we do not allow \code{lambda} in contexts in which we don't already
  15690. know its type. This restriction does not incur a loss of
  15691. expressiveness for \LangLam{} because it is straightforward to modify
  15692. a program to sidestep the restriction, for example, by using an
  15693. annotated assignment statement to assign the \code{lambda} to a
  15694. temporary variable.
  15695. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15696. checker records their type in a \code{has\_type} field. This type
  15697. information is used further on in this chapter.
  15698. %
  15699. \fi}
  15700. \begin{figure}[tbp]
  15701. \begin{tcolorbox}[colback=white]
  15702. {\if\edition\racketEd
  15703. \begin{lstlisting}
  15704. (define (type-check-Llambda env)
  15705. (lambda (e)
  15706. (match e
  15707. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15708. (define-values (new-body bodyT)
  15709. ((type-check-exp (append (map cons xs Ts) env)) body))
  15710. (define ty `(,@Ts -> ,rT))
  15711. (cond
  15712. [(equal? rT bodyT)
  15713. (values (HasType (Lambda params rT new-body) ty) ty)]
  15714. [else
  15715. (error "mismatch in return type" bodyT rT)])]
  15716. ...
  15717. )))
  15718. \end{lstlisting}
  15719. \fi}
  15720. {\if\edition\pythonEd\pythonColor
  15721. \begin{lstlisting}
  15722. class TypeCheckLlambda(TypeCheckLfun):
  15723. def type_check_exp(self, e, env):
  15724. match e:
  15725. case Name(id):
  15726. e.has_type = env[id]
  15727. return env[id]
  15728. case Lambda(params, body):
  15729. raise Exception('cannot synthesize a type for a lambda')
  15730. case Call(Name('arity'), [func]):
  15731. func_t = self.type_check_exp(func, env)
  15732. match func_t:
  15733. case FunctionType(params_t, return_t):
  15734. return IntType()
  15735. case _:
  15736. raise Exception('in arity, unexpected ' + repr(func_t))
  15737. case _:
  15738. return super().type_check_exp(e, env)
  15739. def check_exp(self, e, ty, env):
  15740. match e:
  15741. case Lambda(params, body):
  15742. e.has_type = ty
  15743. match ty:
  15744. case FunctionType(params_t, return_t):
  15745. new_env = env.copy().update(zip(params, params_t))
  15746. self.check_exp(body, return_t, new_env)
  15747. case _:
  15748. raise Exception('lambda does not have type ' + str(ty))
  15749. case Call(func, args):
  15750. func_t = self.type_check_exp(func, env)
  15751. match func_t:
  15752. case FunctionType(params_t, return_t):
  15753. for (arg, param_t) in zip(args, params_t):
  15754. self.check_exp(arg, param_t, env)
  15755. self.check_type_equal(return_t, ty, e)
  15756. case _:
  15757. raise Exception('type_check_exp: in call, unexpected ' + \
  15758. repr(func_t))
  15759. case _:
  15760. t = self.type_check_exp(e, env)
  15761. self.check_type_equal(t, ty, e)
  15762. \end{lstlisting}
  15763. \fi}
  15764. \end{tcolorbox}
  15765. \caption{Type checking \LangLam{}\python{, part 1}.}
  15766. \label{fig:type-check-Llambda}
  15767. \end{figure}
  15768. {\if\edition\pythonEd\pythonColor
  15769. \begin{figure}[tbp]
  15770. \begin{tcolorbox}[colback=white]
  15771. \begin{lstlisting}
  15772. def check_stmts(self, ss, return_ty, env):
  15773. if len(ss) == 0:
  15774. return
  15775. match ss[0]:
  15776. case FunctionDef(name, params, body, dl, returns, comment):
  15777. new_env = env.copy().update(params)
  15778. rt = self.check_stmts(body, returns, new_env)
  15779. self.check_stmts(ss[1:], return_ty, env)
  15780. case Return(value):
  15781. self.check_exp(value, return_ty, env)
  15782. case Assign([Name(id)], value):
  15783. if id in env:
  15784. self.check_exp(value, env[id], env)
  15785. else:
  15786. env[id] = self.type_check_exp(value, env)
  15787. self.check_stmts(ss[1:], return_ty, env)
  15788. case Assign([Subscript(tup, Constant(index), Store())], value):
  15789. tup_t = self.type_check_exp(tup, env)
  15790. match tup_t:
  15791. case TupleType(ts):
  15792. self.check_exp(value, ts[index], env)
  15793. case _:
  15794. raise Exception('expected a tuple, not ' + repr(tup_t))
  15795. self.check_stmts(ss[1:], return_ty, env)
  15796. case AnnAssign(Name(id), ty_annot, value, simple):
  15797. ss[0].annotation = ty_annot
  15798. if id in env:
  15799. self.check_type_equal(env[id], ty_annot)
  15800. else:
  15801. env[id] = ty_annot
  15802. self.check_exp(value, ty_annot, env)
  15803. self.check_stmts(ss[1:], return_ty, env)
  15804. case _:
  15805. self.type_check_stmts(ss, env)
  15806. def type_check(self, p):
  15807. match p:
  15808. case Module(body):
  15809. env = {}
  15810. for s in body:
  15811. match s:
  15812. case FunctionDef(name, params, bod, dl, returns, comment):
  15813. params_t = [t for (x,t) in params]
  15814. env[name] = FunctionType(params_t, returns)
  15815. self.check_stmts(body, int, env)
  15816. \end{lstlisting}
  15817. \end{tcolorbox}
  15818. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15819. \label{fig:type-check-Llambda-part2}
  15820. \end{figure}
  15821. \fi}
  15822. \clearpage
  15823. \section{Assignment and Lexically Scoped Functions}
  15824. \label{sec:assignment-scoping}
  15825. The combination of lexically scoped functions and assignment to
  15826. variables raises a challenge with the flat-closure approach to
  15827. implementing lexically scoped functions. Consider the following
  15828. example in which function \code{f} has a free variable \code{x} that
  15829. is changed after \code{f} is created but before the call to \code{f}.
  15830. % loop_test_11.rkt
  15831. {\if\edition\racketEd
  15832. \begin{lstlisting}
  15833. (let ([x 0])
  15834. (let ([y 0])
  15835. (let ([z 20])
  15836. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15837. (begin
  15838. (set! x 10)
  15839. (set! y 12)
  15840. (f y))))))
  15841. \end{lstlisting}
  15842. \fi}
  15843. {\if\edition\pythonEd\pythonColor
  15844. % box_free_assign.py
  15845. \begin{lstlisting}
  15846. def g(z : int) -> int:
  15847. x = 0
  15848. y = 0
  15849. f : Callable[[int],int] = lambda a: a + x + z
  15850. x = 10
  15851. y = 12
  15852. return f(y)
  15853. print(g(20))
  15854. \end{lstlisting}
  15855. \fi} The correct output for this example is \code{42} because the call
  15856. to \code{f} is required to use the current value of \code{x} (which is
  15857. \code{10}). Unfortunately, the closure conversion pass
  15858. (section~\ref{sec:closure-conversion}) generates code for the
  15859. \code{lambda} that copies the old value of \code{x} into a
  15860. closure. Thus, if we naively applied closure conversion, the output of
  15861. this program would be \code{32}.
  15862. A first attempt at solving this problem would be to save a pointer to
  15863. \code{x} in the closure and change the occurrences of \code{x} inside
  15864. the lambda to dereference the pointer. Of course, this would require
  15865. assigning \code{x} to the stack and not to a register. However, the
  15866. problem goes a bit deeper.
  15867. Consider the following example that returns a function that refers to
  15868. a local variable of the enclosing function:
  15869. \begin{center}
  15870. \begin{minipage}{\textwidth}
  15871. {\if\edition\racketEd
  15872. \begin{lstlisting}
  15873. (define (f) : ( -> Integer)
  15874. (let ([x 0])
  15875. (let ([g (lambda: () : Integer x)])
  15876. (begin
  15877. (set! x 42)
  15878. g))))
  15879. ((f))
  15880. \end{lstlisting}
  15881. \fi}
  15882. {\if\edition\pythonEd\pythonColor
  15883. % counter.py
  15884. \begin{lstlisting}
  15885. def f():
  15886. x = 0
  15887. g = lambda: x
  15888. x = 42
  15889. return g
  15890. print(f()())
  15891. \end{lstlisting}
  15892. \fi}
  15893. \end{minipage}
  15894. \end{center}
  15895. In this example, the lifetime of \code{x} extends beyond the lifetime
  15896. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15897. stack frame for the call to \code{f}, it would be gone by the time we
  15898. called \code{g}, leaving us with dangling pointers for
  15899. \code{x}. This example demonstrates that when a variable occurs free
  15900. inside a function, its lifetime becomes indefinite. Thus, the value of
  15901. the variable needs to live on the heap. The verb
  15902. \emph{box}\index{subject}{box} is often used for allocating a single
  15903. value on the heap, producing a pointer, and
  15904. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15905. %
  15906. We introduce a new pass named \code{convert\_assignments} to address
  15907. this challenge.
  15908. %
  15909. \python{But before diving into that, we have one more
  15910. problem to discuss.}
  15911. {\if\edition\pythonEd\pythonColor
  15912. \section{Uniquify Variables}
  15913. \label{sec:uniquify-lambda}
  15914. With the addition of \code{lambda} we have a complication to deal
  15915. with: name shadowing. Consider the following program with a function
  15916. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15917. \code{lambda} expressions. The first \code{lambda} has a parameter
  15918. that is also named \code{x}.
  15919. \begin{lstlisting}
  15920. def f(x:int, y:int) -> Callable[[int], int]:
  15921. g : Callable[[int],int] = (lambda x: x + y)
  15922. h : Callable[[int],int] = (lambda y: x + y)
  15923. x = input_int()
  15924. return g
  15925. print(f(0, 10)(32))
  15926. \end{lstlisting}
  15927. Many of our compiler passes rely on being able to connect variable
  15928. uses with their definitions using just the name of the
  15929. variable. However, in the example above the name of the variable does
  15930. not uniquely determine its definition. To solve this problem we
  15931. recommend implementing a pass named \code{uniquify} that renames every
  15932. variable in the program to make sure that they are all unique.
  15933. The following shows the result of \code{uniquify} for the example
  15934. above. The \code{x} parameter of function \code{f} is renamed to
  15935. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15936. renamed to \code{x\_4}.
  15937. \begin{lstlisting}
  15938. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15939. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15940. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15941. x_0 = input_int()
  15942. return g_2
  15943. def main() -> int :
  15944. print(f(0, 10)(32))
  15945. return 0
  15946. \end{lstlisting}
  15947. \fi} % pythonEd
  15948. %% \section{Reveal Functions}
  15949. %% \label{sec:reveal-functions-r5}
  15950. %% \racket{To support the \code{procedure-arity} operator we need to
  15951. %% communicate the arity of a function to the point of closure
  15952. %% creation.}
  15953. %% %
  15954. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15955. %% function at runtime. Thus, we need to communicate the arity of a
  15956. %% function to the point of closure creation.}
  15957. %% %
  15958. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15959. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15960. %% \[
  15961. %% \begin{array}{lcl}
  15962. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15963. %% \end{array}
  15964. %% \]
  15965. \section{Assignment Conversion}
  15966. \label{sec:convert-assignments}
  15967. The purpose of the \code{convert\_assignments} pass is to address the
  15968. challenge regarding the interaction between variable assignments and
  15969. closure conversion. First we identify which variables need to be
  15970. boxed, and then we transform the program to box those variables. In
  15971. general, boxing introduces runtime overhead that we would like to
  15972. avoid, so we should box as few variables as possible. We recommend
  15973. boxing the variables in the intersection of the following two sets of
  15974. variables:
  15975. \begin{enumerate}
  15976. \item The variables that are free in a \code{lambda}.
  15977. \item The variables that appear on the left-hand side of an
  15978. assignment.
  15979. \end{enumerate}
  15980. The first condition is a must but the second condition is
  15981. conservative. It is possible to develop a more liberal condition using
  15982. static program analysis.
  15983. Consider again the first example from
  15984. section~\ref{sec:assignment-scoping}:
  15985. %
  15986. {\if\edition\racketEd
  15987. \begin{lstlisting}
  15988. (let ([x 0])
  15989. (let ([y 0])
  15990. (let ([z 20])
  15991. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15992. (begin
  15993. (set! x 10)
  15994. (set! y 12)
  15995. (f y))))))
  15996. \end{lstlisting}
  15997. \fi}
  15998. {\if\edition\pythonEd\pythonColor
  15999. \begin{lstlisting}
  16000. def g(z : int) -> int:
  16001. x = 0
  16002. y = 0
  16003. f : Callable[[int],int] = lambda a: a + x + z
  16004. x = 10
  16005. y = 12
  16006. return f(y)
  16007. print(g(20))
  16008. \end{lstlisting}
  16009. \fi}
  16010. %
  16011. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16012. side of assignments. The variables \code{x} and \code{z} occur free
  16013. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16014. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16015. three transformations: initialize \code{x} with a tuple whose elements
  16016. are uninitialized, replace reads from \code{x} with tuple reads, and
  16017. replace each assignment to \code{x} with a tuple write. The output of
  16018. \code{convert\_assignments} for this example is as follows:
  16019. %
  16020. {\if\edition\racketEd
  16021. \begin{lstlisting}
  16022. (define (main) : Integer
  16023. (let ([x0 (vector 0)])
  16024. (let ([y1 0])
  16025. (let ([z2 20])
  16026. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16027. (+ a3 (+ (vector-ref x0 0) z2)))])
  16028. (begin
  16029. (vector-set! x0 0 10)
  16030. (set! y1 12)
  16031. (f4 y1)))))))
  16032. \end{lstlisting}
  16033. \fi}
  16034. %
  16035. {\if\edition\pythonEd\pythonColor
  16036. \begin{lstlisting}
  16037. def g(z : int)-> int:
  16038. x = (uninitialized(int),)
  16039. x[0] = 0
  16040. y = 0
  16041. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16042. x[0] = 10
  16043. y = 12
  16044. return f(y)
  16045. def main() -> int:
  16046. print(g(20))
  16047. return 0
  16048. \end{lstlisting}
  16049. \fi}
  16050. To compute the free variables of all the \code{lambda} expressions, we
  16051. recommend defining the following two auxiliary functions:
  16052. \begin{enumerate}
  16053. \item \code{free\_variables} computes the free variables of an expression, and
  16054. \item \code{free\_in\_lambda} collects all the variables that are
  16055. free in any of the \code{lambda} expressions, using
  16056. \code{free\_variables} in the case for each \code{lambda}.
  16057. \end{enumerate}
  16058. {\if\edition\racketEd
  16059. %
  16060. To compute the variables that are assigned to, we recommend updating
  16061. the \code{collect-set!} function that we introduced in
  16062. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16063. as \code{Lambda}.
  16064. %
  16065. \fi}
  16066. {\if\edition\pythonEd\pythonColor
  16067. %
  16068. To compute the variables that are assigned to, we recommend defining
  16069. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16070. the set of variables that occur in the left-hand side of an assignment
  16071. statement and otherwise returns the empty set.
  16072. %
  16073. \fi}
  16074. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16075. free in a \code{lambda} and that are assigned to in the enclosing
  16076. function definition.
  16077. Next we discuss the \code{convert\_assignments} pass. In the case for
  16078. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16079. $\VAR{x}$ to a tuple read.
  16080. %
  16081. {\if\edition\racketEd
  16082. \begin{lstlisting}
  16083. (Var |$x$|)
  16084. |$\Rightarrow$|
  16085. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16086. \end{lstlisting}
  16087. \fi}
  16088. %
  16089. {\if\edition\pythonEd\pythonColor
  16090. \begin{lstlisting}
  16091. Name(|$x$|)
  16092. |$\Rightarrow$|
  16093. Subscript(Name(|$x$|), Constant(0), Load())
  16094. \end{lstlisting}
  16095. \fi}
  16096. %
  16097. \noindent In the case for assignment, recursively process the
  16098. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16099. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16100. as follows:
  16101. %
  16102. {\if\edition\racketEd
  16103. \begin{lstlisting}
  16104. (SetBang |$x$| |$\itm{rhs}$|)
  16105. |$\Rightarrow$|
  16106. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16107. \end{lstlisting}
  16108. \fi}
  16109. {\if\edition\pythonEd\pythonColor
  16110. \begin{lstlisting}
  16111. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16112. |$\Rightarrow$|
  16113. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16114. \end{lstlisting}
  16115. \fi}
  16116. %
  16117. {\if\edition\racketEd
  16118. The case for \code{Lambda} is nontrivial, but it is similar to the
  16119. case for function definitions, which we discuss next.
  16120. \fi}
  16121. %
  16122. To translate a function definition, we first compute $\mathit{AF}$,
  16123. the intersection of the variables that are free in a \code{lambda} and
  16124. that are assigned to. We then apply assignment conversion to the body
  16125. of the function definition. Finally, we box the parameters of this
  16126. function definition that are in $\mathit{AF}$. For example,
  16127. the parameter \code{x} of the following function \code{g}
  16128. needs to be boxed:
  16129. {\if\edition\racketEd
  16130. \begin{lstlisting}
  16131. (define (g [x : Integer]) : Integer
  16132. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16133. (begin
  16134. (set! x 10)
  16135. (f 32))))
  16136. \end{lstlisting}
  16137. \fi}
  16138. %
  16139. {\if\edition\pythonEd\pythonColor
  16140. \begin{lstlisting}
  16141. def g(x : int) -> int:
  16142. f : Callable[[int],int] = lambda a: a + x
  16143. x = 10
  16144. return f(32)
  16145. \end{lstlisting}
  16146. \fi}
  16147. %
  16148. \noindent We box parameter \code{x} by creating a local variable named
  16149. \code{x} that is initialized to a tuple whose contents is the value of
  16150. the parameter, which has been renamed to \code{x\_0}.
  16151. %
  16152. {\if\edition\racketEd
  16153. \begin{lstlisting}
  16154. (define (g [x_0 : Integer]) : Integer
  16155. (let ([x (vector x_0)])
  16156. (let ([f (lambda: ([a : Integer]) : Integer
  16157. (+ a (vector-ref x 0)))])
  16158. (begin
  16159. (vector-set! x 0 10)
  16160. (f 32)))))
  16161. \end{lstlisting}
  16162. \fi}
  16163. %
  16164. {\if\edition\pythonEd\pythonColor
  16165. \begin{lstlisting}
  16166. def g(x_0 : int)-> int:
  16167. x = (x_0,)
  16168. f : Callable[[int], int] = (lambda a: a + x[0])
  16169. x[0] = 10
  16170. return f(32)
  16171. \end{lstlisting}
  16172. \fi}
  16173. \section{Closure Conversion}
  16174. \label{sec:closure-conversion}
  16175. \index{subject}{closure conversion}
  16176. The compiling of lexically scoped functions into top-level function
  16177. definitions and flat closures is accomplished in the pass
  16178. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16179. and before \code{limit\_functions}.
  16180. As usual, we implement the pass as a recursive function over the
  16181. AST. The interesting cases are for \key{lambda} and function
  16182. application. We transform a \key{lambda} expression into an expression
  16183. that creates a closure, that is, a tuple for which the first element
  16184. is a function pointer and the rest of the elements are the values of
  16185. the free variables of the \key{lambda}.
  16186. %
  16187. However, we use the \code{Closure} AST node instead of using a tuple
  16188. so that we can record the arity.
  16189. %
  16190. In the generated code that follows, \itm{fvs} is the free variables of
  16191. the lambda and \itm{name} is a unique symbol generated to identify the
  16192. lambda.
  16193. %
  16194. \racket{The \itm{arity} is the number of parameters (the length of
  16195. \itm{ps}).}
  16196. %
  16197. {\if\edition\racketEd
  16198. \begin{lstlisting}
  16199. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16200. |$\Rightarrow$|
  16201. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16202. \end{lstlisting}
  16203. \fi}
  16204. %
  16205. {\if\edition\pythonEd\pythonColor
  16206. \begin{lstlisting}
  16207. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16208. |$\Rightarrow$|
  16209. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  16210. \end{lstlisting}
  16211. \fi}
  16212. %
  16213. In addition to transforming each \key{Lambda} AST node into a
  16214. tuple, we create a top-level function definition for each
  16215. \key{Lambda}, as shown next.\\
  16216. \begin{minipage}{0.8\textwidth}
  16217. {\if\edition\racketEd
  16218. \begin{lstlisting}
  16219. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16220. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16221. ...
  16222. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16223. |\itm{body'}|)...))
  16224. \end{lstlisting}
  16225. \fi}
  16226. {\if\edition\pythonEd\pythonColor
  16227. \begin{lstlisting}
  16228. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  16229. |$\itm{fvs}_1$| = clos[1]
  16230. |$\ldots$|
  16231. |$\itm{fvs}_n$| = clos[|$n$|]
  16232. |\itm{body'}|
  16233. \end{lstlisting}
  16234. \fi}
  16235. \end{minipage}\\
  16236. The \code{clos} parameter refers to the closure. Translate the type
  16237. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16238. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  16239. \itm{closTy} is a tuple type for which the first element type is
  16240. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  16241. the element types are the types of the free variables in the
  16242. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16243. is nontrivial to give a type to the function in the closure's type.%
  16244. %
  16245. \footnote{To give an accurate type to a closure, we would need to add
  16246. existential types to the type checker~\citep{Minamide:1996ys}.}
  16247. %
  16248. %% The dummy type is considered to be equal to any other type during type
  16249. %% checking.
  16250. The free variables become local variables that are initialized with
  16251. their values in the closure.
  16252. Closure conversion turns every function into a tuple, so the type
  16253. annotations in the program must also be translated. We recommend
  16254. defining an auxiliary recursive function for this purpose. Function
  16255. types should be translated as follows:
  16256. %
  16257. {\if\edition\racketEd
  16258. \begin{lstlisting}
  16259. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16260. |$\Rightarrow$|
  16261. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16262. \end{lstlisting}
  16263. \fi}
  16264. {\if\edition\pythonEd\pythonColor
  16265. \begin{lstlisting}
  16266. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16267. |$\Rightarrow$|
  16268. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16269. \end{lstlisting}
  16270. \fi}
  16271. %
  16272. This type indicates that the first thing in the tuple is a
  16273. function. The first parameter of the function is a tuple (a closure)
  16274. and the rest of the parameters are the ones from the original
  16275. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16276. omits the types of the free variables because (1) those types are not
  16277. available in this context, and (2) we do not need them in the code that
  16278. is generated for function application. So this type describes only the
  16279. first component of the closure tuple. At runtime the tuple may have
  16280. more components, but we ignore them at this point.
  16281. We transform function application into code that retrieves the
  16282. function from the closure and then calls the function, passing the
  16283. closure as the first argument. We place $e'$ in a temporary variable
  16284. to avoid code duplication.
  16285. \begin{center}
  16286. \begin{minipage}{\textwidth}
  16287. {\if\edition\racketEd
  16288. \begin{lstlisting}
  16289. (Apply |$e$| |$\itm{es}$|)
  16290. |$\Rightarrow$|
  16291. (Let |$\itm{tmp}$| |$e'$|
  16292. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16293. \end{lstlisting}
  16294. \fi}
  16295. %
  16296. {\if\edition\pythonEd\pythonColor
  16297. \begin{lstlisting}
  16298. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16299. |$\Rightarrow$|
  16300. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16301. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16302. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16303. \end{lstlisting}
  16304. \fi}
  16305. \end{minipage}
  16306. \end{center}
  16307. There is also the question of what to do with references to top-level
  16308. function definitions. To maintain a uniform translation of function
  16309. application, we turn function references into closures.
  16310. \begin{tabular}{lll}
  16311. \begin{minipage}{0.2\textwidth}
  16312. {\if\edition\racketEd
  16313. \begin{lstlisting}
  16314. (FunRef |$f$| |$n$|)
  16315. \end{lstlisting}
  16316. \fi}
  16317. {\if\edition\pythonEd\pythonColor
  16318. \begin{lstlisting}
  16319. FunRef(|$f$|, |$n$|)
  16320. \end{lstlisting}
  16321. \fi}
  16322. \end{minipage}
  16323. &
  16324. $\Rightarrow\qquad$
  16325. &
  16326. \begin{minipage}{0.5\textwidth}
  16327. {\if\edition\racketEd
  16328. \begin{lstlisting}
  16329. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16330. \end{lstlisting}
  16331. \fi}
  16332. {\if\edition\pythonEd\pythonColor
  16333. \begin{lstlisting}
  16334. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16335. \end{lstlisting}
  16336. \fi}
  16337. \end{minipage}
  16338. \end{tabular} \\
  16339. We no longer need the annotated assignment statement \code{AnnAssign}
  16340. to support the type checking of \code{lambda} expressions, so we
  16341. translate it to a regular \code{Assign} statement.
  16342. The top-level function definitions need to be updated to take an extra
  16343. closure parameter, but that parameter is ignored in the body of those
  16344. functions.
  16345. \section{An Example Translation}
  16346. \label{sec:example-lambda}
  16347. Figure~\ref{fig:lexical-functions-example} shows the result of
  16348. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16349. program demonstrating lexical scoping that we discussed at the
  16350. beginning of this chapter.
  16351. \begin{figure}[tbp]
  16352. \begin{tcolorbox}[colback=white]
  16353. \begin{minipage}{0.8\textwidth}
  16354. {\if\edition\racketEd
  16355. % tests/lambda_test_6.rkt
  16356. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16357. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16358. (let ([y8 4])
  16359. (lambda: ([z9 : Integer]) : Integer
  16360. (+ x7 (+ y8 z9)))))
  16361. (define (main) : Integer
  16362. (let ([g0 ((fun-ref f6 1) 5)])
  16363. (let ([h1 ((fun-ref f6 1) 3)])
  16364. (+ (g0 11) (h1 15)))))
  16365. \end{lstlisting}
  16366. $\Rightarrow$
  16367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16368. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16369. (let ([y8 4])
  16370. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16371. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16372. (let ([x7 (vector-ref fvs3 1)])
  16373. (let ([y8 (vector-ref fvs3 2)])
  16374. (+ x7 (+ y8 z9)))))
  16375. (define (main) : Integer
  16376. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16377. ((vector-ref clos5 0) clos5 5))])
  16378. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16379. ((vector-ref clos6 0) clos6 3))])
  16380. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16381. \end{lstlisting}
  16382. \fi}
  16383. %
  16384. {\if\edition\pythonEd\pythonColor
  16385. % free_var.py
  16386. \begin{lstlisting}
  16387. def f(x: int) -> Callable[[int],int]:
  16388. y = 4
  16389. return lambda z: x + y + z
  16390. g = f(5)
  16391. h = f(3)
  16392. print(g(11) + h(15))
  16393. \end{lstlisting}
  16394. $\Rightarrow$
  16395. \begin{lstlisting}
  16396. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16397. x = fvs_1[1]
  16398. y = fvs_1[2]
  16399. return (x + y[0] + z)
  16400. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16401. y = (uninitialized(int),)
  16402. y[0] = 4
  16403. return closure{1}({lambda_0}, x, y)
  16404. def main() -> int:
  16405. g = (begin: clos_3 = closure{1}({f})
  16406. clos_3[0](clos_3, 5))
  16407. h = (begin: clos_4 = closure{1}({f})
  16408. clos_4[0](clos_4, 3))
  16409. print((begin: clos_5 = g
  16410. clos_5[0](clos_5, 11))
  16411. + (begin: clos_6 = h
  16412. clos_6[0](clos_6, 15)))
  16413. return 0
  16414. \end{lstlisting}
  16415. \fi}
  16416. \end{minipage}
  16417. \end{tcolorbox}
  16418. \caption{Example of closure conversion.}
  16419. \label{fig:lexical-functions-example}
  16420. \end{figure}
  16421. \begin{exercise}\normalfont\normalsize
  16422. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16423. Create five new programs that use \key{lambda} functions and make use of
  16424. lexical scoping. Test your compiler on these new programs and all
  16425. your previously created test programs.
  16426. \end{exercise}
  16427. \section{Expose Allocation}
  16428. \label{sec:expose-allocation-r5}
  16429. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16430. that allocates and initializes a tuple, similar to the translation of
  16431. the tuple creation in section~\ref{sec:expose-allocation}.
  16432. The only difference is replacing the use of
  16433. \ALLOC{\itm{len}}{\itm{type}} with
  16434. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16435. \section{Explicate Control and \LangCLam{}}
  16436. \label{sec:explicate-r5}
  16437. The output language of \code{explicate\_control} is \LangCLam{}; the
  16438. definition of its abstract syntax is shown in
  16439. figure~\ref{fig:Clam-syntax}.
  16440. %
  16441. \racket{The only differences with respect to \LangCFun{} are the
  16442. addition of the \code{AllocateClosure} form to the grammar for
  16443. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16444. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16445. similar to the handling of other expressions such as primitive
  16446. operators.}
  16447. %
  16448. \python{The differences with respect to \LangCFun{} are the
  16449. additions of \code{Uninitialized}, \code{AllocateClosure},
  16450. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16451. \code{explicate\_control} pass is similar to the handling of other
  16452. expressions such as primitive operators.}
  16453. \newcommand{\ClambdaASTRacket}{
  16454. \begin{array}{lcl}
  16455. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16456. \itm{op} &::= & \code{procedure-arity}
  16457. \end{array}
  16458. }
  16459. \newcommand{\ClambdaASTPython}{
  16460. \begin{array}{lcl}
  16461. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16462. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16463. &\MID& \ARITY{\Atm}
  16464. \end{array}
  16465. }
  16466. \begin{figure}[tp]
  16467. \begin{tcolorbox}[colback=white]
  16468. \small
  16469. {\if\edition\racketEd
  16470. \[
  16471. \begin{array}{l}
  16472. \gray{\CvarASTRacket} \\ \hline
  16473. \gray{\CifASTRacket} \\ \hline
  16474. \gray{\CloopASTRacket} \\ \hline
  16475. \gray{\CtupASTRacket} \\ \hline
  16476. \gray{\CfunASTRacket} \\ \hline
  16477. \ClambdaASTRacket \\
  16478. \begin{array}{lcl}
  16479. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16480. \end{array}
  16481. \end{array}
  16482. \]
  16483. \fi}
  16484. {\if\edition\pythonEd\pythonColor
  16485. \[
  16486. \begin{array}{l}
  16487. \gray{\CifASTPython} \\ \hline
  16488. \gray{\CtupASTPython} \\ \hline
  16489. \gray{\CfunASTPython} \\ \hline
  16490. \ClambdaASTPython \\
  16491. \begin{array}{lcl}
  16492. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16493. \end{array}
  16494. \end{array}
  16495. \]
  16496. \fi}
  16497. \end{tcolorbox}
  16498. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16499. \label{fig:Clam-syntax}
  16500. \end{figure}
  16501. \section{Select Instructions}
  16502. \label{sec:select-instructions-Llambda}
  16503. \index{subject}{select instructions}
  16504. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16505. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16506. (section~\ref{sec:select-instructions-gc}). The only difference is
  16507. that you should place the \itm{arity} in the tag that is stored at
  16508. position $0$ of the tuple. Recall that in
  16509. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16510. was not used. We store the arity in the $5$ bits starting at position
  16511. $58$.
  16512. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16513. instructions that access the tag from position $0$ of the vector and
  16514. extract the $5$ bits starting at position $58$ from the tag.}
  16515. %
  16516. \python{Compile a call to the \code{arity} operator to a sequence of
  16517. instructions that access the tag from position $0$ of the tuple
  16518. (representing a closure) and extract the $5$ bits starting at position
  16519. $58$ from the tag.}
  16520. \begin{figure}[p]
  16521. \begin{tcolorbox}[colback=white]
  16522. {\if\edition\racketEd
  16523. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16524. \node (Lfun) at (0,2) {\large \LangLam{}};
  16525. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16526. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16527. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16528. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16529. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16530. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16531. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16532. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16533. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16534. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16535. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16536. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16537. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16538. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16539. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16540. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16541. \path[->,bend left=15] (Lfun) edge [above] node
  16542. {\ttfamily\footnotesize shrink} (Lfun-2);
  16543. \path[->,bend left=15] (Lfun-2) edge [above] node
  16544. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16545. \path[->,bend left=15] (Lfun-3) edge [above] node
  16546. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16547. \path[->,bend left=15] (F1-0) edge [left] node
  16548. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16549. \path[->,bend left=15] (F1-1) edge [below] node
  16550. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16551. \path[->,bend right=15] (F1-2) edge [above] node
  16552. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16553. \path[->,bend right=15] (F1-3) edge [above] node
  16554. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16555. \path[->,bend left=15] (F1-4) edge [right] node
  16556. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16557. \path[->,bend right=15] (F1-5) edge [below] node
  16558. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16559. \path[->,bend left=15] (F1-6) edge [above] node
  16560. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16561. \path[->] (C3-2) edge [right] node
  16562. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16563. \path[->,bend right=15] (x86-2) edge [right] node
  16564. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16565. \path[->,bend right=15] (x86-2-1) edge [below] node
  16566. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16567. \path[->,bend right=15] (x86-2-2) edge [right] node
  16568. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16569. \path[->,bend left=15] (x86-3) edge [above] node
  16570. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16571. \path[->,bend left=15] (x86-4) edge [right] node
  16572. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16573. \end{tikzpicture}
  16574. \fi}
  16575. {\if\edition\pythonEd\pythonColor
  16576. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16577. \node (Lfun) at (0,2) {\large \LangLam{}};
  16578. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16579. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16580. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16581. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16582. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16583. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16584. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16585. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16586. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16587. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16588. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16589. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16590. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16591. \path[->,bend left=15] (Lfun) edge [above] node
  16592. {\ttfamily\footnotesize shrink} (Lfun-2);
  16593. \path[->,bend left=15] (Lfun-2) edge [above] node
  16594. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16595. \path[->,bend left=15] (Lfun-3) edge [above] node
  16596. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16597. \path[->,bend left=15] (F1-0) edge [left] node
  16598. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16599. \path[->,bend left=15] (F1-1) edge [below] node
  16600. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16601. \path[->,bend left=15] (F1-2) edge [below] node
  16602. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16603. \path[->,bend right=15] (F1-3) edge [above] node
  16604. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16605. \path[->,bend right=15] (F1-5) edge [right] node
  16606. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16607. \path[->,bend left=15] (F1-6) edge [right] node
  16608. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16609. \path[->,bend right=15] (C3-2) edge [right] node
  16610. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16611. \path[->,bend right=15] (x86-2) edge [below] node
  16612. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16613. \path[->,bend right=15] (x86-3) edge [below] node
  16614. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16615. \path[->,bend left=15] (x86-4) edge [above] node
  16616. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16617. \end{tikzpicture}
  16618. \fi}
  16619. \end{tcolorbox}
  16620. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16621. functions.}
  16622. \label{fig:Llambda-passes}
  16623. \end{figure}
  16624. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16625. needed for the compilation of \LangLam{}.
  16626. \clearpage
  16627. \section{Challenge: Optimize Closures}
  16628. \label{sec:optimize-closures}
  16629. In this chapter we compile lexically scoped functions into a
  16630. relatively efficient representation: flat closures. However, even this
  16631. representation comes with some overhead. For example, consider the
  16632. following program with a function \code{tail\_sum} that does not have
  16633. any free variables and where all the uses of \code{tail\_sum} are in
  16634. applications in which we know that only \code{tail\_sum} is being applied
  16635. (and not any other functions):
  16636. \begin{center}
  16637. \begin{minipage}{0.95\textwidth}
  16638. {\if\edition\racketEd
  16639. \begin{lstlisting}
  16640. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16641. (if (eq? n 0)
  16642. s
  16643. (tail_sum (- n 1) (+ n s))))
  16644. (+ (tail_sum 3 0) 36)
  16645. \end{lstlisting}
  16646. \fi}
  16647. {\if\edition\pythonEd\pythonColor
  16648. \begin{lstlisting}
  16649. def tail_sum(n : int, s : int) -> int:
  16650. if n == 0:
  16651. return s
  16652. else:
  16653. return tail_sum(n - 1, n + s)
  16654. print(tail_sum(3, 0) + 36)
  16655. \end{lstlisting}
  16656. \fi}
  16657. \end{minipage}
  16658. \end{center}
  16659. As described in this chapter, we uniformly apply closure conversion to
  16660. all functions, obtaining the following output for this program:
  16661. \begin{center}
  16662. \begin{minipage}{0.95\textwidth}
  16663. {\if\edition\racketEd
  16664. \begin{lstlisting}
  16665. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16666. (if (eq? n2 0)
  16667. s3
  16668. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16669. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16670. (define (main) : Integer
  16671. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16672. ((vector-ref clos6 0) clos6 3 0)) 27))
  16673. \end{lstlisting}
  16674. \fi}
  16675. {\if\edition\pythonEd\pythonColor
  16676. \begin{lstlisting}
  16677. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16678. if n_0 == 0:
  16679. return s_1
  16680. else:
  16681. return (begin: clos_2 = (tail_sum,)
  16682. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16683. def main() -> int :
  16684. print((begin: clos_4 = (tail_sum,)
  16685. clos_4[0](clos_4, 3, 0)) + 36)
  16686. return 0
  16687. \end{lstlisting}
  16688. \fi}
  16689. \end{minipage}
  16690. \end{center}
  16691. If this program were compiled according to the previous chapter, there
  16692. would be no allocation and the calls to \code{tail\_sum} would be
  16693. direct calls. In contrast, the program presented here allocates memory
  16694. for each closure and the calls to \code{tail\_sum} are indirect. These
  16695. two differences incur considerable overhead in a program such as this,
  16696. in which the allocations and indirect calls occur inside a tight loop.
  16697. One might think that this problem is trivial to solve: can't we just
  16698. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16699. and compile them to direct calls instead of treating it like a call to
  16700. a closure? We would also drop the new \code{fvs} parameter of
  16701. \code{tail\_sum}.
  16702. %
  16703. However, this problem is not so trivial, because a global function may
  16704. \emph{escape} and become involved in applications that also involve
  16705. closures. Consider the following example in which the application
  16706. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16707. application because the \code{lambda} may flow into \code{f}, but the
  16708. \code{inc} function might also flow into \code{f}:
  16709. \begin{center}
  16710. \begin{minipage}{\textwidth}
  16711. % lambda_test_30.rkt
  16712. {\if\edition\racketEd
  16713. \begin{lstlisting}
  16714. (define (inc [x : Integer]) : Integer
  16715. (+ x 1))
  16716. (let ([y (read)])
  16717. (let ([f (if (eq? (read) 0)
  16718. inc
  16719. (lambda: ([x : Integer]) : Integer (- x y)))])
  16720. (f 41)))
  16721. \end{lstlisting}
  16722. \fi}
  16723. {\if\edition\pythonEd\pythonColor
  16724. \begin{lstlisting}
  16725. def add1(x : int) -> int:
  16726. return x + 1
  16727. y = input_int()
  16728. g : Callable[[int], int] = lambda x: x - y
  16729. f = add1 if input_int() == 0 else g
  16730. print(f(41))
  16731. \end{lstlisting}
  16732. \fi}
  16733. \end{minipage}
  16734. \end{center}
  16735. If a global function name is used in any way other than as the
  16736. operator in a direct call, then we say that the function
  16737. \emph{escapes}. If a global function does not escape, then we do not
  16738. need to perform closure conversion on the function.
  16739. \begin{exercise}\normalfont\normalsize
  16740. Implement an auxiliary function for detecting which global
  16741. functions escape. Using that function, implement an improved version
  16742. of closure conversion that does not apply closure conversion to
  16743. global functions that do not escape but instead compiles them as
  16744. regular functions. Create several new test cases that check whether
  16745. your compiler properly detects whether global functions escape or not.
  16746. \end{exercise}
  16747. So far we have reduced the overhead of calling global functions, but
  16748. it would also be nice to reduce the overhead of calling a
  16749. \code{lambda} when we can determine at compile time which
  16750. \code{lambda} will be called. We refer to such calls as \emph{known
  16751. calls}. Consider the following example in which a \code{lambda} is
  16752. bound to \code{f} and then applied.
  16753. {\if\edition\racketEd
  16754. % lambda_test_9.rkt
  16755. \begin{lstlisting}
  16756. (let ([y (read)])
  16757. (let ([f (lambda: ([x : Integer]) : Integer
  16758. (+ x y))])
  16759. (f 21)))
  16760. \end{lstlisting}
  16761. \fi}
  16762. {\if\edition\pythonEd\pythonColor
  16763. \begin{lstlisting}
  16764. y = input_int()
  16765. f : Callable[[int],int] = lambda x: x + y
  16766. print(f(21))
  16767. \end{lstlisting}
  16768. \fi}
  16769. %
  16770. \noindent Closure conversion compiles the application
  16771. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16772. %
  16773. {\if\edition\racketEd
  16774. \begin{lstlisting}
  16775. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16776. (let ([y2 (vector-ref fvs6 1)])
  16777. (+ x3 y2)))
  16778. (define (main) : Integer
  16779. (let ([y2 (read)])
  16780. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16781. ((vector-ref f4 0) f4 21))))
  16782. \end{lstlisting}
  16783. \fi}
  16784. {\if\edition\pythonEd\pythonColor
  16785. \begin{lstlisting}
  16786. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16787. y_1 = fvs_4[1]
  16788. return x_2 + y_1[0]
  16789. def main() -> int:
  16790. y_1 = (777,)
  16791. y_1[0] = input_int()
  16792. f_0 = (lambda_3, y_1)
  16793. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16794. return 0
  16795. \end{lstlisting}
  16796. \fi}
  16797. %
  16798. \noindent However, we can instead compile the application
  16799. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16800. %
  16801. {\if\edition\racketEd
  16802. \begin{lstlisting}
  16803. (define (main) : Integer
  16804. (let ([y2 (read)])
  16805. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16806. ((fun-ref lambda5 1) f4 21))))
  16807. \end{lstlisting}
  16808. \fi}
  16809. {\if\edition\pythonEd\pythonColor
  16810. \begin{lstlisting}
  16811. def main() -> int:
  16812. y_1 = (777,)
  16813. y_1[0] = input_int()
  16814. f_0 = (lambda_3, y_1)
  16815. print(lambda_3(f_0, 21))
  16816. return 0
  16817. \end{lstlisting}
  16818. \fi}
  16819. The problem of determining which \code{lambda} will be called from a
  16820. particular application is quite challenging in general and the topic
  16821. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16822. following exercise we recommend that you compile an application to a
  16823. direct call when the operator is a variable and \racket{the variable
  16824. is \code{let}-bound to a closure}\python{the previous assignment to
  16825. the variable is a closure}. This can be accomplished by maintaining
  16826. an environment that maps variables to function names. Extend the
  16827. environment whenever you encounter a closure on the right-hand side of
  16828. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16829. name of the global function for the closure. This pass should come
  16830. after closure conversion.
  16831. \begin{exercise}\normalfont\normalsize
  16832. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16833. compiles known calls into direct calls. Verify that your compiler is
  16834. successful in this regard on several example programs.
  16835. \end{exercise}
  16836. These exercises only scratch the surface of closure optimization. A
  16837. good next step for the interested reader is to look at the work of
  16838. \citet{Keep:2012ab}.
  16839. \section{Further Reading}
  16840. The notion of lexically scoped functions predates modern computers by
  16841. about a decade. They were invented by \citet{Church:1932aa}, who
  16842. proposed the lambda calculus as a foundation for logic. Anonymous
  16843. functions were included in the LISP~\citep{McCarthy:1960dz}
  16844. programming language but were initially dynamically scoped. The Scheme
  16845. dialect of LISP adopted lexical scoping, and
  16846. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16847. Scheme programs. However, environments were represented as linked
  16848. lists, so variable look-up was linear in the size of the
  16849. environment. \citet{Appel91} gives a detailed description of several
  16850. closure representations. In this chapter we represent environments
  16851. using flat closures, which were invented by
  16852. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16853. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16854. closures, variable look-up is constant time but the time to create a
  16855. closure is proportional to the number of its free variables. Flat
  16856. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16857. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16858. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16859. % compilers)
  16860. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16861. \chapter{Dynamic Typing}
  16862. \label{ch:Ldyn}
  16863. \index{subject}{dynamic typing}
  16864. \setcounter{footnote}{0}
  16865. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16866. typed language that is a subset of \racket{Racket}\python{Python}. The
  16867. focus on dynamic typing is in contrast to the previous chapters, which
  16868. have studied the compilation of statically typed languages. In
  16869. dynamically typed languages such as \LangDyn{}, a particular
  16870. expression may produce a value of a different type each time it is
  16871. executed. Consider the following example with a conditional \code{if}
  16872. expression that may return a Boolean or an integer depending on the
  16873. input to the program:
  16874. % part of dynamic_test_25.rkt
  16875. {\if\edition\racketEd
  16876. \begin{lstlisting}
  16877. (not (if (eq? (read) 1) #f 0))
  16878. \end{lstlisting}
  16879. \fi}
  16880. {\if\edition\pythonEd\pythonColor
  16881. \begin{lstlisting}
  16882. not (False if input_int() == 1 else 0)
  16883. \end{lstlisting}
  16884. \fi}
  16885. Languages that allow expressions to produce different kinds of values
  16886. are called \emph{polymorphic}, a word composed of the Greek roots
  16887. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16888. There are several kinds of polymorphism in programming languages, such as
  16889. subtype polymorphism\index{subject}{subtype polymorphism} and
  16890. parametric polymorphism\index{subject}{parametric polymorphism}
  16891. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16892. study in this chapter does not have a special name; it is the kind
  16893. that arises in dynamically typed languages.
  16894. Another characteristic of dynamically typed languages is that
  16895. their primitive operations, such as \code{not}, are often defined to operate
  16896. on many different types of values. In fact, in
  16897. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16898. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16899. given anything else it returns \FALSE{}.
  16900. Furthermore, even when primitive operations restrict their inputs to
  16901. values of a certain type, this restriction is enforced at runtime
  16902. instead of during compilation. For example, the tuple read
  16903. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16904. results in a runtime error because the first argument must
  16905. be a tuple, not a Boolean.
  16906. \section{The \LangDyn{} Language}
  16907. \newcommand{\LdynGrammarRacket}{
  16908. \begin{array}{rcl}
  16909. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16910. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16911. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16912. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16913. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16914. \end{array}
  16915. }
  16916. \newcommand{\LdynASTRacket}{
  16917. \begin{array}{lcl}
  16918. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16919. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16920. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16921. \end{array}
  16922. }
  16923. \begin{figure}[tp]
  16924. \centering
  16925. \begin{tcolorbox}[colback=white]
  16926. \small
  16927. {\if\edition\racketEd
  16928. \[
  16929. \begin{array}{l}
  16930. \gray{\LintGrammarRacket{}} \\ \hline
  16931. \gray{\LvarGrammarRacket{}} \\ \hline
  16932. \gray{\LifGrammarRacket{}} \\ \hline
  16933. \gray{\LwhileGrammarRacket} \\ \hline
  16934. \gray{\LtupGrammarRacket} \\ \hline
  16935. \LdynGrammarRacket \\
  16936. \begin{array}{rcl}
  16937. \LangDynM{} &::=& \Def\ldots\; \Exp
  16938. \end{array}
  16939. \end{array}
  16940. \]
  16941. \fi}
  16942. {\if\edition\pythonEd\pythonColor
  16943. \[
  16944. \begin{array}{rcl}
  16945. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16946. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16947. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16948. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16949. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16950. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16951. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16952. \MID \CLEN{\Exp} \\
  16953. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16954. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16955. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16956. \MID \Var\mathop{\key{=}}\Exp \\
  16957. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16958. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16959. &\MID& \CRETURN{\Exp} \\
  16960. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16961. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16962. \end{array}
  16963. \]
  16964. \fi}
  16965. \end{tcolorbox}
  16966. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16967. \label{fig:r7-concrete-syntax}
  16968. \end{figure}
  16969. \begin{figure}[tp]
  16970. \centering
  16971. \begin{tcolorbox}[colback=white]
  16972. \small
  16973. {\if\edition\racketEd
  16974. \[
  16975. \begin{array}{l}
  16976. \gray{\LintASTRacket{}} \\ \hline
  16977. \gray{\LvarASTRacket{}} \\ \hline
  16978. \gray{\LifASTRacket{}} \\ \hline
  16979. \gray{\LwhileASTRacket} \\ \hline
  16980. \gray{\LtupASTRacket} \\ \hline
  16981. \LdynASTRacket \\
  16982. \begin{array}{lcl}
  16983. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16984. \end{array}
  16985. \end{array}
  16986. \]
  16987. \fi}
  16988. {\if\edition\pythonEd\pythonColor
  16989. \[
  16990. \begin{array}{rcl}
  16991. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16992. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16993. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16994. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16995. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16996. &\MID & \code{Is()} \\
  16997. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16998. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16999. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  17000. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  17001. \MID \VAR{\Var{}} \\
  17002. &\MID& \BOOL{\itm{bool}}
  17003. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17004. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17005. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17006. &\MID& \LEN{\Exp} \\
  17007. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17008. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17009. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17010. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17011. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17012. &\MID& \RETURN{\Exp} \\
  17013. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17014. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17015. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17016. \end{array}
  17017. \]
  17018. \fi}
  17019. \end{tcolorbox}
  17020. \caption{The abstract syntax of \LangDyn{}.}
  17021. \label{fig:r7-syntax}
  17022. \end{figure}
  17023. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17024. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17025. %
  17026. There is no type checker for \LangDyn{} because it checks types only
  17027. at runtime.
  17028. The definitional interpreter for \LangDyn{} is presented in
  17029. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17030. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17031. \INT{n}. Instead of simply returning the integer \code{n} (as
  17032. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17033. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17034. value} that combines an underlying value with a tag that identifies
  17035. what kind of value it is. We define the following \racket{struct}\python{class}
  17036. to represent tagged values:
  17037. %
  17038. {\if\edition\racketEd
  17039. \begin{lstlisting}
  17040. (struct Tagged (value tag) #:transparent)
  17041. \end{lstlisting}
  17042. \fi}
  17043. {\if\edition\pythonEd\pythonColor
  17044. \begin{minipage}{\textwidth}
  17045. \begin{lstlisting}
  17046. @dataclass(eq=True)
  17047. class Tagged(Value):
  17048. value : Value
  17049. tag : str
  17050. def __str__(self):
  17051. return str(self.value)
  17052. \end{lstlisting}
  17053. \end{minipage}
  17054. \fi}
  17055. %
  17056. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17057. \code{Vector}, and \code{Procedure}.}
  17058. %
  17059. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17060. \skey{tuple}, and \skey{function}.}
  17061. %
  17062. Tags are closely related to types but do not always capture all the
  17063. information that a type does.
  17064. %
  17065. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17066. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17067. Any)} is tagged with \code{Procedure}.}
  17068. %
  17069. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17070. is tagged with \skey{tuple} and a function of type
  17071. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17072. is tagged with \skey{function}.}
  17073. Next consider the match case for accessing the element of a tuple.
  17074. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17075. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17076. argument is a tuple and the second is an integer.
  17077. \racket{
  17078. If they are not, a \code{trapped-error} is raised. Recall from
  17079. section~\ref{sec:interp_Lint} that when a definition interpreter
  17080. raises a \code{trapped-error} error, the compiled code must also
  17081. signal an error by exiting with return code \code{255}. A
  17082. \code{trapped-error} is also raised if the index is not less than the
  17083. length of the vector.
  17084. }
  17085. %
  17086. \python{If they are not, an exception is raised. The compiled code
  17087. must also signal an error by exiting with return code \code{255}. A
  17088. exception is also raised if the index is not less than the length of the
  17089. tuple or if it is negative.}
  17090. \begin{figure}[tbp]
  17091. \begin{tcolorbox}[colback=white]
  17092. {\if\edition\racketEd
  17093. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17094. (define ((interp-Ldyn-exp env) ast)
  17095. (define recur (interp-Ldyn-exp env))
  17096. (match ast
  17097. [(Var x) (dict-ref env x)]
  17098. [(Int n) (Tagged n 'Integer)]
  17099. [(Bool b) (Tagged b 'Boolean)]
  17100. [(Lambda xs rt body)
  17101. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17102. [(Prim 'vector es)
  17103. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17104. [(Prim 'vector-ref (list e1 e2))
  17105. (define vec (recur e1)) (define i (recur e2))
  17106. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17107. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17108. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17109. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17110. [(Prim 'vector-set! (list e1 e2 e3))
  17111. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17112. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17113. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17114. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17115. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17116. (Tagged (void) 'Void)]
  17117. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17118. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17119. [(Prim 'or (list e1 e2))
  17120. (define v1 (recur e1))
  17121. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17122. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17123. [(Prim op (list e1))
  17124. #:when (set-member? type-predicates op)
  17125. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17126. [(Prim op es)
  17127. (define args (map recur es))
  17128. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17129. (unless (for/or ([expected-tags (op-tags op)])
  17130. (equal? expected-tags tags))
  17131. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17132. (tag-value
  17133. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17134. [(If q t f)
  17135. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17136. [(Apply f es)
  17137. (define new-f (recur f)) (define args (map recur es))
  17138. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17139. (match f-val
  17140. [`(function ,xs ,body ,lam-env)
  17141. (unless (eq? (length xs) (length args))
  17142. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17143. (define new-env (append (map cons xs args) lam-env))
  17144. ((interp-Ldyn-exp new-env) body)]
  17145. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17146. \end{lstlisting}
  17147. \fi}
  17148. {\if\edition\pythonEd\pythonColor
  17149. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17150. class InterpLdyn(InterpLlambda):
  17151. def interp_exp(self, e, env):
  17152. match e:
  17153. case Constant(n):
  17154. return self.tag(super().interp_exp(e, env))
  17155. case Tuple(es, Load()):
  17156. return self.tag(super().interp_exp(e, env))
  17157. case Lambda(params, body):
  17158. return self.tag(super().interp_exp(e, env))
  17159. case Call(Name('input_int'), []):
  17160. return self.tag(super().interp_exp(e, env))
  17161. case BinOp(left, Add(), right):
  17162. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17163. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17164. case BinOp(left, Sub(), right):
  17165. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17166. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17167. case UnaryOp(USub(), e1):
  17168. v = self.interp_exp(e1, env)
  17169. return self.tag(- self.untag(v, 'int', e))
  17170. case IfExp(test, body, orelse):
  17171. v = self.interp_exp(test, env)
  17172. if self.untag(v, 'bool', e):
  17173. return self.interp_exp(body, env)
  17174. else:
  17175. return self.interp_exp(orelse, env)
  17176. case UnaryOp(Not(), e1):
  17177. v = self.interp_exp(e1, env)
  17178. return self.tag(not self.untag(v, 'bool', e))
  17179. case BoolOp(And(), values):
  17180. left = values[0]; right = values[1]
  17181. l = self.interp_exp(left, env)
  17182. if self.untag(l, 'bool', e):
  17183. return self.interp_exp(right, env)
  17184. else:
  17185. return self.tag(False)
  17186. case BoolOp(Or(), values):
  17187. left = values[0]; right = values[1]
  17188. l = self.interp_exp(left, env)
  17189. if self.untag(l, 'bool', e):
  17190. return self.tag(True)
  17191. else:
  17192. return self.interp_exp(right, env)
  17193. case Compare(left, [cmp], [right]):
  17194. l = self.interp_exp(left, env)
  17195. r = self.interp_exp(right, env)
  17196. if l.tag == r.tag:
  17197. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17198. else:
  17199. raise Exception('interp Compare unexpected '
  17200. + repr(l) + ' ' + repr(r))
  17201. case Subscript(tup, index, Load()):
  17202. t = self.interp_exp(tup, env)
  17203. n = self.interp_exp(index, env)
  17204. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17205. case Call(Name('len'), [tup]):
  17206. t = self.interp_exp(tup, env)
  17207. return self.tag(len(self.untag(t, 'tuple', e)))
  17208. case _:
  17209. return self.tag(super().interp_exp(e, env))
  17210. \end{lstlisting}
  17211. \fi}
  17212. \end{tcolorbox}
  17213. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17214. \label{fig:interp-Ldyn}
  17215. \end{figure}
  17216. {\if\edition\pythonEd\pythonColor
  17217. \begin{figure}[tbp]
  17218. \begin{tcolorbox}[colback=white]
  17219. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17220. class InterpLdyn(InterpLlambda):
  17221. def interp_stmt(self, s, env, cont):
  17222. match s:
  17223. case If(test, body, orelse):
  17224. v = self.interp_exp(test, env)
  17225. match self.untag(v, 'bool', s):
  17226. case True:
  17227. return self.interp_stmts(body + cont, env)
  17228. case False:
  17229. return self.interp_stmts(orelse + cont, env)
  17230. case While(test, body, []):
  17231. v = self.interp_exp(test, env)
  17232. if self.untag(v, 'bool', test):
  17233. self.interp_stmts(body + [s] + cont, env)
  17234. else:
  17235. return self.interp_stmts(cont, env)
  17236. case Assign([Subscript(tup, index)], value):
  17237. tup = self.interp_exp(tup, env)
  17238. index = self.interp_exp(index, env)
  17239. tup_v = self.untag(tup, 'tuple', s)
  17240. index_v = self.untag(index, 'int', s)
  17241. tup_v[index_v] = self.interp_exp(value, env)
  17242. return self.interp_stmts(cont, env)
  17243. case FunctionDef(name, params, bod, dl, returns, comment):
  17244. if isinstance(params, ast.arguments):
  17245. ps = [p.arg for p in params.args]
  17246. else:
  17247. ps = [x for (x,t) in params]
  17248. env[name] = self.tag(Function(name, ps, bod, env))
  17249. return self.interp_stmts(cont, env)
  17250. case _:
  17251. return super().interp_stmt(s, env, cont)
  17252. \end{lstlisting}
  17253. \end{tcolorbox}
  17254. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17255. \label{fig:interp-Ldyn-2}
  17256. \end{figure}
  17257. \fi}
  17258. \begin{figure}[tbp]
  17259. \begin{tcolorbox}[colback=white]
  17260. {\if\edition\racketEd
  17261. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17262. (define (interp-op op)
  17263. (match op
  17264. ['+ fx+]
  17265. ['- fx-]
  17266. ['read read-fixnum]
  17267. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  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. ['>= (lambda (v1 v2)
  17275. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17276. ['boolean? boolean?]
  17277. ['integer? fixnum?]
  17278. ['void? void?]
  17279. ['vector? vector?]
  17280. ['vector-length vector-length]
  17281. ['procedure? (match-lambda
  17282. [`(functions ,xs ,body ,env) #t] [else #f])]
  17283. [else (error 'interp-op "unknown operator" op)]))
  17284. (define (op-tags op)
  17285. (match op
  17286. ['+ '((Integer Integer))]
  17287. ['- '((Integer Integer) (Integer))]
  17288. ['read '(())]
  17289. ['not '((Boolean))]
  17290. ['< '((Integer Integer))]
  17291. ['<= '((Integer Integer))]
  17292. ['> '((Integer Integer))]
  17293. ['>= '((Integer Integer))]
  17294. ['vector-length '((Vector))]))
  17295. (define type-predicates
  17296. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17297. (define (tag-value v)
  17298. (cond [(boolean? v) (Tagged v 'Boolean)]
  17299. [(fixnum? v) (Tagged v 'Integer)]
  17300. [(procedure? v) (Tagged v 'Procedure)]
  17301. [(vector? v) (Tagged v 'Vector)]
  17302. [(void? v) (Tagged v 'Void)]
  17303. [else (error 'tag-value "unidentified value ~a" v)]))
  17304. (define (check-tag val expected ast)
  17305. (define tag (Tagged-tag val))
  17306. (unless (eq? tag expected)
  17307. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17308. \end{lstlisting}
  17309. \fi}
  17310. {\if\edition\pythonEd\pythonColor
  17311. \begin{lstlisting}
  17312. class InterpLdyn(InterpLlambda):
  17313. def tag(self, v):
  17314. if v is True or v is False:
  17315. return Tagged(v, 'bool')
  17316. elif isinstance(v, int):
  17317. return Tagged(v, 'int')
  17318. elif isinstance(v, Function):
  17319. return Tagged(v, 'function')
  17320. elif isinstance(v, tuple):
  17321. return Tagged(v, 'tuple')
  17322. elif isinstance(v, type(None)):
  17323. return Tagged(v, 'none')
  17324. else:
  17325. raise Exception('tag: unexpected ' + repr(v))
  17326. def untag(self, v, expected_tag, ast):
  17327. match v:
  17328. case Tagged(val, tag) if tag == expected_tag:
  17329. return val
  17330. case _:
  17331. raise TrappedError('expected Tagged value with '
  17332. + expected_tag + ', not ' + ' ' + repr(v))
  17333. def apply_fun(self, fun, args, e):
  17334. f = self.untag(fun, 'function', e)
  17335. return super().apply_fun(f, args, e)
  17336. \end{lstlisting}
  17337. \fi}
  17338. \end{tcolorbox}
  17339. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17340. \label{fig:interp-Ldyn-aux}
  17341. \end{figure}
  17342. \clearpage
  17343. \section{Representation of Tagged Values}
  17344. The interpreter for \LangDyn{} introduced a new kind of value: the
  17345. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17346. represent tagged values at the bit level. Because almost every
  17347. operation in \LangDyn{} involves manipulating tagged values, the
  17348. representation must be efficient. Recall that all our values are 64
  17349. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17350. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17351. $011$ for procedures, and $101$ for the void value\python{,
  17352. \key{None}}. We define the following auxiliary function for mapping
  17353. types to tag codes:
  17354. %
  17355. {\if\edition\racketEd
  17356. \begin{align*}
  17357. \itm{tagof}(\key{Integer}) &= 001 \\
  17358. \itm{tagof}(\key{Boolean}) &= 100 \\
  17359. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17360. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17361. \itm{tagof}(\key{Void}) &= 101
  17362. \end{align*}
  17363. \fi}
  17364. {\if\edition\pythonEd\pythonColor
  17365. \begin{align*}
  17366. \itm{tagof}(\key{IntType()}) &= 001 \\
  17367. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17368. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17369. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17370. \itm{tagof}(\key{type(None)}) &= 101
  17371. \end{align*}
  17372. \fi}
  17373. %
  17374. This stealing of 3 bits comes at some price: integers are now restricted
  17375. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17376. affect tuples and procedures because those values are addresses, and
  17377. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17378. they are always $000$. Thus, we do not lose information by overwriting
  17379. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17380. to recover the original address.
  17381. To make tagged values into first-class entities, we can give them a
  17382. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17383. operations such as \code{Inject} and \code{Project} for creating and
  17384. using them, yielding the statically typed \LangAny{} intermediate
  17385. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17386. section~\ref{sec:compile-r7}; in the next section we describe the
  17387. \LangAny{} language in greater detail.
  17388. \section{The \LangAny{} Language}
  17389. \label{sec:Rany-lang}
  17390. \newcommand{\LanyASTRacket}{
  17391. \begin{array}{lcl}
  17392. \Type &::= & \ANYTY \\
  17393. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17394. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17395. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17396. \itm{op} &::= & \code{any-vector-length}
  17397. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17398. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17399. \MID \code{procedure?} \MID \code{void?} \\
  17400. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17401. \end{array}
  17402. }
  17403. \newcommand{\LanyASTPython}{
  17404. \begin{array}{lcl}
  17405. \Type &::= & \key{AnyType()} \\
  17406. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17407. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17408. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17409. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17410. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17411. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17412. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17413. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17414. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17415. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17416. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17417. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17418. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17419. \end{array}
  17420. }
  17421. \begin{figure}[tp]
  17422. \centering
  17423. \begin{tcolorbox}[colback=white]
  17424. \small
  17425. {\if\edition\racketEd
  17426. \[
  17427. \begin{array}{l}
  17428. \gray{\LintOpAST} \\ \hline
  17429. \gray{\LvarASTRacket{}} \\ \hline
  17430. \gray{\LifASTRacket{}} \\ \hline
  17431. \gray{\LwhileASTRacket{}} \\ \hline
  17432. \gray{\LtupASTRacket{}} \\ \hline
  17433. \gray{\LfunASTRacket} \\ \hline
  17434. \gray{\LlambdaASTRacket} \\ \hline
  17435. \LanyASTRacket \\
  17436. \begin{array}{lcl}
  17437. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17438. \end{array}
  17439. \end{array}
  17440. \]
  17441. \fi}
  17442. {\if\edition\pythonEd\pythonColor
  17443. \[
  17444. \begin{array}{l}
  17445. \gray{\LintASTPython} \\ \hline
  17446. \gray{\LvarASTPython{}} \\ \hline
  17447. \gray{\LifASTPython{}} \\ \hline
  17448. \gray{\LwhileASTPython{}} \\ \hline
  17449. \gray{\LtupASTPython{}} \\ \hline
  17450. \gray{\LfunASTPython} \\ \hline
  17451. \gray{\LlambdaASTPython} \\ \hline
  17452. \LanyASTPython \\
  17453. \begin{array}{lcl}
  17454. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17455. \end{array}
  17456. \end{array}
  17457. \]
  17458. \fi}
  17459. \end{tcolorbox}
  17460. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17461. \label{fig:Lany-syntax}
  17462. \end{figure}
  17463. The definition of the abstract syntax of \LangAny{} is given in
  17464. figure~\ref{fig:Lany-syntax}.
  17465. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17466. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17467. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17468. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17469. converts the tagged value produced by expression $e$ into a value of
  17470. type $T$ or halts the program if the type tag does not match $T$.
  17471. %
  17472. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17473. restricted to be a flat type (the nonterminal $\FType$) which
  17474. simplifies the implementation and complies with the needs for
  17475. compiling \LangDyn{}.
  17476. The \racket{\code{any-vector}} operators
  17477. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17478. operations so that they can be applied to a value of type
  17479. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17480. tuple operations in that the index is not restricted to a literal
  17481. integer in the grammar but is allowed to be any expression.
  17482. \racket{The type predicates such as
  17483. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17484. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17485. the predicate and return {\FALSE} otherwise.}
  17486. The type checker for \LangAny{} is shown in
  17487. figure~\ref{fig:type-check-Lany}
  17488. %
  17489. \racket{ and uses the auxiliary functions presented in
  17490. figure~\ref{fig:type-check-Lany-aux}}.
  17491. %
  17492. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17493. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17494. \begin{figure}[btp]
  17495. \begin{tcolorbox}[colback=white]
  17496. {\if\edition\racketEd
  17497. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17498. (define type-check-Lany-class
  17499. (class type-check-Llambda-class
  17500. (super-new)
  17501. (inherit check-type-equal?)
  17502. (define/override (type-check-exp env)
  17503. (lambda (e)
  17504. (define recur (type-check-exp env))
  17505. (match e
  17506. [(Inject e1 ty)
  17507. (unless (flat-ty? ty)
  17508. (error 'type-check "may only inject from flat type, not ~a" ty))
  17509. (define-values (new-e1 e-ty) (recur e1))
  17510. (check-type-equal? e-ty ty e)
  17511. (values (Inject new-e1 ty) 'Any)]
  17512. [(Project e1 ty)
  17513. (unless (flat-ty? ty)
  17514. (error 'type-check "may only project to flat type, not ~a" ty))
  17515. (define-values (new-e1 e-ty) (recur e1))
  17516. (check-type-equal? e-ty 'Any e)
  17517. (values (Project new-e1 ty) ty)]
  17518. [(Prim 'any-vector-length (list e1))
  17519. (define-values (e1^ t1) (recur e1))
  17520. (check-type-equal? t1 'Any e)
  17521. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17522. [(Prim 'any-vector-ref (list e1 e2))
  17523. (define-values (e1^ t1) (recur e1))
  17524. (define-values (e2^ t2) (recur e2))
  17525. (check-type-equal? t1 'Any e)
  17526. (check-type-equal? t2 'Integer e)
  17527. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17528. [(Prim 'any-vector-set! (list e1 e2 e3))
  17529. (define-values (e1^ t1) (recur e1))
  17530. (define-values (e2^ t2) (recur e2))
  17531. (define-values (e3^ t3) (recur e3))
  17532. (check-type-equal? t1 'Any e)
  17533. (check-type-equal? t2 'Integer e)
  17534. (check-type-equal? t3 'Any e)
  17535. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17536. [(Prim pred (list e1))
  17537. #:when (set-member? (type-predicates) pred)
  17538. (define-values (new-e1 e-ty) (recur e1))
  17539. (check-type-equal? e-ty 'Any e)
  17540. (values (Prim pred (list new-e1)) 'Boolean)]
  17541. [(Prim 'eq? (list arg1 arg2))
  17542. (define-values (e1 t1) (recur arg1))
  17543. (define-values (e2 t2) (recur arg2))
  17544. (match* (t1 t2)
  17545. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17546. [(other wise) (check-type-equal? t1 t2 e)])
  17547. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17548. [else ((super type-check-exp env) e)])))
  17549. ))
  17550. \end{lstlisting}
  17551. \fi}
  17552. {\if\edition\pythonEd\pythonColor
  17553. \begin{lstlisting}
  17554. class TypeCheckLany(TypeCheckLlambda):
  17555. def type_check_exp(self, e, env):
  17556. match e:
  17557. case Inject(value, typ):
  17558. self.check_exp(value, typ, env)
  17559. return AnyType()
  17560. case Project(value, typ):
  17561. self.check_exp(value, AnyType(), env)
  17562. return typ
  17563. case Call(Name('any_tuple_load'), [tup, index]):
  17564. self.check_exp(tup, AnyType(), env)
  17565. self.check_exp(index, IntType(), env)
  17566. return AnyType()
  17567. case Call(Name('any_len'), [tup]):
  17568. self.check_exp(tup, AnyType(), env)
  17569. return IntType()
  17570. case Call(Name('arity'), [fun]):
  17571. ty = self.type_check_exp(fun, env)
  17572. match ty:
  17573. case FunctionType(ps, rt):
  17574. return IntType()
  17575. case TupleType([FunctionType(ps,rs)]):
  17576. return IntType()
  17577. case _:
  17578. raise Exception('type check arity unexpected ' + repr(ty))
  17579. case Call(Name('make_any'), [value, tag]):
  17580. self.type_check_exp(value, env)
  17581. self.check_exp(tag, IntType(), env)
  17582. return AnyType()
  17583. case AnnLambda(params, returns, body):
  17584. new_env = {x:t for (x,t) in env.items()}
  17585. for (x,t) in params:
  17586. new_env[x] = t
  17587. return_t = self.type_check_exp(body, new_env)
  17588. self.check_type_equal(returns, return_t, e)
  17589. return FunctionType([t for (x,t) in params], return_t)
  17590. case _:
  17591. return super().type_check_exp(e, env)
  17592. \end{lstlisting}
  17593. \fi}
  17594. \end{tcolorbox}
  17595. \caption{Type checker for the \LangAny{} language.}
  17596. \label{fig:type-check-Lany}
  17597. \end{figure}
  17598. {\if\edition\racketEd
  17599. \begin{figure}[tbp]
  17600. \begin{tcolorbox}[colback=white]
  17601. \begin{lstlisting}
  17602. (define/override (operator-types)
  17603. (append
  17604. '((integer? . ((Any) . Boolean))
  17605. (vector? . ((Any) . Boolean))
  17606. (procedure? . ((Any) . Boolean))
  17607. (void? . ((Any) . Boolean)))
  17608. (super operator-types)))
  17609. (define/public (type-predicates)
  17610. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17611. (define/public (flat-ty? ty)
  17612. (match ty
  17613. [(or `Integer `Boolean `Void) #t]
  17614. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17615. [`(,ts ... -> ,rt)
  17616. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17617. [else #f]))
  17618. \end{lstlisting}
  17619. \end{tcolorbox}
  17620. \caption{Auxiliary methods for type checking \LangAny{}.}
  17621. \label{fig:type-check-Lany-aux}
  17622. \end{figure}
  17623. \fi}
  17624. \begin{figure}[btp]
  17625. \begin{tcolorbox}[colback=white]
  17626. {\if\edition\racketEd
  17627. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17628. (define interp-Lany-class
  17629. (class interp-Llambda-class
  17630. (super-new)
  17631. (define/override (interp-op op)
  17632. (match op
  17633. ['boolean? (match-lambda
  17634. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17635. [else #f])]
  17636. ['integer? (match-lambda
  17637. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17638. [else #f])]
  17639. ['vector? (match-lambda
  17640. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17641. [else #f])]
  17642. ['procedure? (match-lambda
  17643. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17644. [else #f])]
  17645. ['eq? (match-lambda*
  17646. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17647. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17648. [ls (apply (super interp-op op) ls)])]
  17649. ['any-vector-ref (lambda (v i)
  17650. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17651. ['any-vector-set! (lambda (v i a)
  17652. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17653. ['any-vector-length (lambda (v)
  17654. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17655. [else (super interp-op op)]))
  17656. (define/override ((interp-exp env) e)
  17657. (define recur (interp-exp env))
  17658. (match e
  17659. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17660. [(Project e ty2) (apply-project (recur e) ty2)]
  17661. [else ((super interp-exp env) e)]))
  17662. ))
  17663. (define (interp-Lany p)
  17664. (send (new interp-Lany-class) interp-program p))
  17665. \end{lstlisting}
  17666. \fi}
  17667. {\if\edition\pythonEd\pythonColor
  17668. \begin{lstlisting}
  17669. class InterpLany(InterpLlambda):
  17670. def interp_exp(self, e, env):
  17671. match e:
  17672. case Inject(value, typ):
  17673. v = self.interp_exp(value, env)
  17674. return Tagged(v, self.type_to_tag(typ))
  17675. case Project(value, typ):
  17676. v = self.interp_exp(value, env)
  17677. match v:
  17678. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17679. return val
  17680. case _:
  17681. raise Exception('interp project to ' + repr(typ)
  17682. + ' unexpected ' + repr(v))
  17683. case Call(Name('any_tuple_load'), [tup, index]):
  17684. tv = self.interp_exp(tup, env)
  17685. n = self.interp_exp(index, env)
  17686. match tv:
  17687. case Tagged(v, tag):
  17688. return v[n]
  17689. case _:
  17690. raise Exception('in any_tuple_load unexpected ' + repr(tv))
  17691. case Call(Name('any_len'), [value]):
  17692. v = self.interp_exp(value, env)
  17693. match v:
  17694. case Tagged(value, tag):
  17695. return len(value)
  17696. case _:
  17697. raise Exception('interp any_len unexpected ' + repr(v))
  17698. case Call(Name('arity'), [fun]):
  17699. f = self.interp_exp(fun, env)
  17700. return self.arity(f)
  17701. case _:
  17702. return super().interp_exp(e, env)
  17703. \end{lstlisting}
  17704. \fi}
  17705. \end{tcolorbox}
  17706. \caption{Interpreter for \LangAny{}.}
  17707. \label{fig:interp-Lany}
  17708. \end{figure}
  17709. \begin{figure}[tbp]
  17710. \begin{tcolorbox}[colback=white]
  17711. {\if\edition\racketEd
  17712. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17713. (define/public (apply-inject v tg) (Tagged v tg))
  17714. (define/public (apply-project v ty2)
  17715. (define tag2 (any-tag ty2))
  17716. (match v
  17717. [(Tagged v1 tag1)
  17718. (cond
  17719. [(eq? tag1 tag2)
  17720. (match ty2
  17721. [`(Vector ,ts ...)
  17722. (define l1 ((interp-op 'vector-length) v1))
  17723. (cond
  17724. [(eq? l1 (length ts)) v1]
  17725. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17726. l1 (length ts))])]
  17727. [`(,ts ... -> ,rt)
  17728. (match v1
  17729. [`(function ,xs ,body ,env)
  17730. (cond [(eq? (length xs) (length ts)) v1]
  17731. [else
  17732. (error 'apply-project "arity mismatch ~a != ~a"
  17733. (length xs) (length ts))])]
  17734. [else (error 'apply-project "expected function not ~a" v1)])]
  17735. [else v1])]
  17736. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17737. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17738. \end{lstlisting}
  17739. \fi}
  17740. {\if\edition\pythonEd\pythonColor
  17741. \begin{lstlisting}
  17742. class InterpLany(InterpLlambda):
  17743. def type_to_tag(self, typ):
  17744. match typ:
  17745. case FunctionType(params, rt):
  17746. return 'function'
  17747. case TupleType(fields):
  17748. return 'tuple'
  17749. case t if t == int:
  17750. return 'int'
  17751. case t if t == bool:
  17752. return 'bool'
  17753. case IntType():
  17754. return 'int'
  17755. case BoolType():
  17756. return 'int'
  17757. case _:
  17758. raise Exception('type_to_tag unexpected ' + repr(typ))
  17759. def arity(self, v):
  17760. match v:
  17761. case Function(name, params, body, env):
  17762. return len(params)
  17763. case ClosureTuple(args, arity):
  17764. return arity
  17765. case _:
  17766. raise Exception('Lany arity unexpected ' + repr(v))
  17767. \end{lstlisting}
  17768. \fi}
  17769. \end{tcolorbox}
  17770. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17771. \label{fig:interp-Lany-aux}
  17772. \end{figure}
  17773. \clearpage
  17774. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17775. \label{sec:compile-r7}
  17776. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17777. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17778. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17779. is that given any subexpression $e$ in the \LangDyn{} program, the
  17780. pass will produce an expression $e'$ in \LangAny{} that has type
  17781. \ANYTY{}. For example, the first row in
  17782. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17783. \TRUE{}, which must be injected to produce an expression of type
  17784. \ANYTY{}.
  17785. %
  17786. The compilation of addition is shown in the second row of
  17787. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17788. representative of many primitive operations: the arguments have type
  17789. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17790. be performed.
  17791. The compilation of \key{lambda} (third row of
  17792. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17793. produce type annotations: we simply use \ANYTY{}.
  17794. %
  17795. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17796. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17797. this pass has to account for some differences in behavior between
  17798. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17799. permissive than \LangAny{} regarding what kind of values can be used
  17800. in various places. For example, the condition of an \key{if} does
  17801. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17802. of the same type (in that case the result is \code{\#f}).}
  17803. \begin{figure}[btp]
  17804. \centering
  17805. \begin{tcolorbox}[colback=white]
  17806. {\if\edition\racketEd
  17807. \begin{tabular}{lll}
  17808. \begin{minipage}{0.27\textwidth}
  17809. \begin{lstlisting}
  17810. #t
  17811. \end{lstlisting}
  17812. \end{minipage}
  17813. &
  17814. $\Rightarrow$
  17815. &
  17816. \begin{minipage}{0.65\textwidth}
  17817. \begin{lstlisting}
  17818. (inject #t Boolean)
  17819. \end{lstlisting}
  17820. \end{minipage}
  17821. \\[2ex]\hline
  17822. \begin{minipage}{0.27\textwidth}
  17823. \begin{lstlisting}
  17824. (+ |$e_1$| |$e_2$|)
  17825. \end{lstlisting}
  17826. \end{minipage}
  17827. &
  17828. $\Rightarrow$
  17829. &
  17830. \begin{minipage}{0.65\textwidth}
  17831. \begin{lstlisting}
  17832. (inject
  17833. (+ (project |$e'_1$| Integer)
  17834. (project |$e'_2$| Integer))
  17835. Integer)
  17836. \end{lstlisting}
  17837. \end{minipage}
  17838. \\[2ex]\hline
  17839. \begin{minipage}{0.27\textwidth}
  17840. \begin{lstlisting}
  17841. (lambda (|$x_1 \ldots$|) |$e$|)
  17842. \end{lstlisting}
  17843. \end{minipage}
  17844. &
  17845. $\Rightarrow$
  17846. &
  17847. \begin{minipage}{0.65\textwidth}
  17848. \begin{lstlisting}
  17849. (inject
  17850. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17851. (Any|$\ldots$|Any -> Any))
  17852. \end{lstlisting}
  17853. \end{minipage}
  17854. \\[2ex]\hline
  17855. \begin{minipage}{0.27\textwidth}
  17856. \begin{lstlisting}
  17857. (|$e_0$| |$e_1 \ldots e_n$|)
  17858. \end{lstlisting}
  17859. \end{minipage}
  17860. &
  17861. $\Rightarrow$
  17862. &
  17863. \begin{minipage}{0.65\textwidth}
  17864. \begin{lstlisting}
  17865. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17866. \end{lstlisting}
  17867. \end{minipage}
  17868. \\[2ex]\hline
  17869. \begin{minipage}{0.27\textwidth}
  17870. \begin{lstlisting}
  17871. (vector-ref |$e_1$| |$e_2$|)
  17872. \end{lstlisting}
  17873. \end{minipage}
  17874. &
  17875. $\Rightarrow$
  17876. &
  17877. \begin{minipage}{0.65\textwidth}
  17878. \begin{lstlisting}
  17879. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17880. \end{lstlisting}
  17881. \end{minipage}
  17882. \\[2ex]\hline
  17883. \begin{minipage}{0.27\textwidth}
  17884. \begin{lstlisting}
  17885. (if |$e_1$| |$e_2$| |$e_3$|)
  17886. \end{lstlisting}
  17887. \end{minipage}
  17888. &
  17889. $\Rightarrow$
  17890. &
  17891. \begin{minipage}{0.65\textwidth}
  17892. \begin{lstlisting}
  17893. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17894. \end{lstlisting}
  17895. \end{minipage}
  17896. \\[2ex]\hline
  17897. \begin{minipage}{0.27\textwidth}
  17898. \begin{lstlisting}
  17899. (eq? |$e_1$| |$e_2$|)
  17900. \end{lstlisting}
  17901. \end{minipage}
  17902. &
  17903. $\Rightarrow$
  17904. &
  17905. \begin{minipage}{0.65\textwidth}
  17906. \begin{lstlisting}
  17907. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17908. \end{lstlisting}
  17909. \end{minipage}
  17910. \\[2ex]\hline
  17911. \begin{minipage}{0.27\textwidth}
  17912. \begin{lstlisting}
  17913. (not |$e_1$|)
  17914. \end{lstlisting}
  17915. \end{minipage}
  17916. &
  17917. $\Rightarrow$
  17918. &
  17919. \begin{minipage}{0.65\textwidth}
  17920. \begin{lstlisting}
  17921. (if (eq? |$e'_1$| (inject #f Boolean))
  17922. (inject #t Boolean) (inject #f Boolean))
  17923. \end{lstlisting}
  17924. \end{minipage}
  17925. \end{tabular}
  17926. \fi}
  17927. {\if\edition\pythonEd\pythonColor
  17928. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17929. \begin{minipage}{0.23\textwidth}
  17930. \begin{lstlisting}
  17931. True
  17932. \end{lstlisting}
  17933. \end{minipage}
  17934. &
  17935. $\Rightarrow$
  17936. &
  17937. \begin{minipage}{0.7\textwidth}
  17938. \begin{lstlisting}
  17939. Inject(True, BoolType())
  17940. \end{lstlisting}
  17941. \end{minipage}
  17942. \\[2ex]\hline
  17943. \begin{minipage}{0.23\textwidth}
  17944. \begin{lstlisting}
  17945. |$e_1$| + |$e_2$|
  17946. \end{lstlisting}
  17947. \end{minipage}
  17948. &
  17949. $\Rightarrow$
  17950. &
  17951. \begin{minipage}{0.7\textwidth}
  17952. \begin{lstlisting}
  17953. Inject(Project(|$e'_1$|, IntType())
  17954. + Project(|$e'_2$|, IntType()),
  17955. IntType())
  17956. \end{lstlisting}
  17957. \end{minipage}
  17958. \\[2ex]\hline
  17959. \begin{minipage}{0.23\textwidth}
  17960. \begin{lstlisting}
  17961. lambda |$x_1 \ldots$|: |$e$|
  17962. \end{lstlisting}
  17963. \end{minipage}
  17964. &
  17965. $\Rightarrow$
  17966. &
  17967. \begin{minipage}{0.7\textwidth}
  17968. \begin{lstlisting}
  17969. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17970. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17971. \end{lstlisting}
  17972. \end{minipage}
  17973. \\[2ex]\hline
  17974. \begin{minipage}{0.23\textwidth}
  17975. \begin{lstlisting}
  17976. |$e_0$|(|$e_1 \ldots e_n$|)
  17977. \end{lstlisting}
  17978. \end{minipage}
  17979. &
  17980. $\Rightarrow$
  17981. &
  17982. \begin{minipage}{0.7\textwidth}
  17983. \begin{lstlisting}
  17984. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17985. AnyType())), |$e'_1, \ldots, e'_n$|)
  17986. \end{lstlisting}
  17987. \end{minipage}
  17988. \\[2ex]\hline
  17989. \begin{minipage}{0.23\textwidth}
  17990. \begin{lstlisting}
  17991. |$e_1$|[|$e_2$|]
  17992. \end{lstlisting}
  17993. \end{minipage}
  17994. &
  17995. $\Rightarrow$
  17996. &
  17997. \begin{minipage}{0.7\textwidth}
  17998. \begin{lstlisting}
  17999. Call(Name('any_tuple_load'),
  18000. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18001. \end{lstlisting}
  18002. \end{minipage}
  18003. %% \begin{minipage}{0.23\textwidth}
  18004. %% \begin{lstlisting}
  18005. %% |$e_2$| if |$e_1$| else |$e_3$|
  18006. %% \end{lstlisting}
  18007. %% \end{minipage}
  18008. %% &
  18009. %% $\Rightarrow$
  18010. %% &
  18011. %% \begin{minipage}{0.7\textwidth}
  18012. %% \begin{lstlisting}
  18013. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18014. %% \end{lstlisting}
  18015. %% \end{minipage}
  18016. %% \\[2ex]\hline
  18017. %% \begin{minipage}{0.23\textwidth}
  18018. %% \begin{lstlisting}
  18019. %% (eq? |$e_1$| |$e_2$|)
  18020. %% \end{lstlisting}
  18021. %% \end{minipage}
  18022. %% &
  18023. %% $\Rightarrow$
  18024. %% &
  18025. %% \begin{minipage}{0.7\textwidth}
  18026. %% \begin{lstlisting}
  18027. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18028. %% \end{lstlisting}
  18029. %% \end{minipage}
  18030. %% \\[2ex]\hline
  18031. %% \begin{minipage}{0.23\textwidth}
  18032. %% \begin{lstlisting}
  18033. %% (not |$e_1$|)
  18034. %% \end{lstlisting}
  18035. %% \end{minipage}
  18036. %% &
  18037. %% $\Rightarrow$
  18038. %% &
  18039. %% \begin{minipage}{0.7\textwidth}
  18040. %% \begin{lstlisting}
  18041. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18042. %% (inject #t Boolean) (inject #f Boolean))
  18043. %% \end{lstlisting}
  18044. %% \end{minipage}
  18045. %% \\[2ex]\hline
  18046. \\\hline
  18047. \end{tabular}
  18048. \fi}
  18049. \end{tcolorbox}
  18050. \caption{Cast insertion.}
  18051. \label{fig:compile-r7-Lany}
  18052. \end{figure}
  18053. \section{Reveal Casts}
  18054. \label{sec:reveal-casts-Lany}
  18055. % TODO: define R'_6
  18056. In the \code{reveal\_casts} pass, we recommend compiling
  18057. \code{Project} into a conditional expression that checks whether the
  18058. value's tag matches the target type; if it does, the value is
  18059. converted to a value of the target type by removing the tag; if it
  18060. does not, the program exits.
  18061. %
  18062. {\if\edition\racketEd
  18063. %
  18064. To perform these actions we need a new primitive operation,
  18065. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18066. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18067. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18068. underlying value from a tagged value. The \code{ValueOf} form
  18069. includes the type for the underlying value that is used by the type
  18070. checker.
  18071. %
  18072. \fi}
  18073. %
  18074. {\if\edition\pythonEd\pythonColor
  18075. %
  18076. To perform these actions we need two new AST classes: \code{TagOf} and
  18077. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18078. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18079. the underlying value from a tagged value. The \code{ValueOf}
  18080. operation includes the type for the underlying value that is used by
  18081. the type checker.
  18082. %
  18083. \fi}
  18084. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18085. \code{Project} can be translated as follows:
  18086. \begin{center}
  18087. \begin{minipage}{1.0\textwidth}
  18088. {\if\edition\racketEd
  18089. \begin{lstlisting}
  18090. (Project |$e$| |$\FType$|)
  18091. |$\Rightarrow$|
  18092. (Let |$\itm{tmp}$| |$e'$|
  18093. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18094. (Int |$\itm{tagof}(\FType)$|)))
  18095. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18096. (Exit)))
  18097. \end{lstlisting}
  18098. \fi}
  18099. {\if\edition\pythonEd\pythonColor
  18100. \begin{lstlisting}
  18101. Project(|$e$|, |$\FType$|)
  18102. |$\Rightarrow$|
  18103. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18104. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18105. [Constant(|$\itm{tagof}(\FType)$|)]),
  18106. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18107. Call(Name('exit'), [])))
  18108. \end{lstlisting}
  18109. \fi}
  18110. \end{minipage}
  18111. \end{center}
  18112. If the target type of the projection is a tuple or function type, then
  18113. there is a bit more work to do. For tuples, check that the length of
  18114. the tuple type matches the length of the tuple. For functions, check
  18115. that the number of parameters in the function type matches the
  18116. function's arity.
  18117. Regarding \code{Inject}, we recommend compiling it to a slightly
  18118. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18119. takes a tag instead of a type.
  18120. \begin{center}
  18121. \begin{minipage}{1.0\textwidth}
  18122. {\if\edition\racketEd
  18123. \begin{lstlisting}
  18124. (Inject |$e$| |$\FType$|)
  18125. |$\Rightarrow$|
  18126. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18127. \end{lstlisting}
  18128. \fi}
  18129. {\if\edition\pythonEd\pythonColor
  18130. \begin{lstlisting}
  18131. Inject(|$e$|, |$\FType$|)
  18132. |$\Rightarrow$|
  18133. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18134. \end{lstlisting}
  18135. \fi}
  18136. \end{minipage}
  18137. \end{center}
  18138. {\if\edition\pythonEd\pythonColor
  18139. %
  18140. The introduction of \code{make\_any} makes it difficult to use
  18141. bidirectional type checking because we no longer have an expected type
  18142. to use for type checking the expression $e'$. Thus, we run into
  18143. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18144. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18145. annotated lambda), that contains its return type and the types of its
  18146. parameters.
  18147. %
  18148. \fi}
  18149. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18150. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18151. translation of \code{Project}.}
  18152. {\if\edition\racketEd
  18153. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18154. combine the projection action with the vector operation. Also, the
  18155. read and write operations allow arbitrary expressions for the index, so
  18156. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18157. cannot guarantee that the index is within bounds. Thus, we insert code
  18158. to perform bounds checking at runtime. The translation for
  18159. \code{any-vector-ref} is as follows, and the other two operations are
  18160. translated in a similar way:
  18161. \begin{center}
  18162. \begin{minipage}{0.95\textwidth}
  18163. \begin{lstlisting}
  18164. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18165. |$\Rightarrow$|
  18166. (Let |$v$| |$e'_1$|
  18167. (Let |$i$| |$e'_2$|
  18168. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18169. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18170. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18171. (Exit))
  18172. (Exit))))
  18173. \end{lstlisting}
  18174. \end{minipage}
  18175. \end{center}
  18176. \fi}
  18177. %
  18178. {\if\edition\pythonEd\pythonColor
  18179. %
  18180. The \code{any\_tuple\_load} operation combines the projection action
  18181. with the load operation. Also, the load operation allows arbitrary
  18182. expressions for the index so the type checker for \LangAny{}
  18183. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index, is
  18184. within bounds. Thus, we insert code to perform bounds checking at
  18185. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18186. \begin{lstlisting}
  18187. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18188. |$\Rightarrow$|
  18189. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18190. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18191. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18192. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18193. Call(Name('exit'), [])),
  18194. Call(Name('exit'), [])))
  18195. \end{lstlisting}
  18196. \fi}
  18197. {\if\edition\pythonEd\pythonColor
  18198. \section{Assignment Conversion}
  18199. \label{sec:convert-assignments-Lany}
  18200. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18201. \code{AnnLambda} AST classes.
  18202. \section{Closure Conversion}
  18203. \label{sec:closure-conversion-Lany}
  18204. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18205. \code{AnnLambda} AST classes.
  18206. \fi}
  18207. \section{Remove Complex Operands}
  18208. \label{sec:rco-Lany}
  18209. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18210. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18211. %
  18212. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18213. complex expressions. Their subexpressions must be atomic.}
  18214. \section{Explicate Control and \LangCAny{}}
  18215. \label{sec:explicate-Lany}
  18216. The output of \code{explicate\_control} is the \LangCAny{} language,
  18217. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18218. %
  18219. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18220. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18221. note that the index argument of \code{vector-ref} and
  18222. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18223. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18224. %
  18225. \python{Update the auxiliary functions \code{explicate\_tail},
  18226. \code{explicate\_effect}, and \code{explicate\_pred} as
  18227. appropriate to handle the new expressions in \LangCAny{}. }
  18228. \newcommand{\CanyASTPython}{
  18229. \begin{array}{lcl}
  18230. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18231. &\MID& \key{TagOf}\LP \Atm \RP
  18232. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18233. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18234. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18235. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18236. \end{array}
  18237. }
  18238. \newcommand{\CanyASTRacket}{
  18239. \begin{array}{lcl}
  18240. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18241. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18242. &\MID& \VALUEOF{\Atm}{\FType} \\
  18243. \Tail &::= & \LP\key{Exit}\RP
  18244. \end{array}
  18245. }
  18246. \begin{figure}[tp]
  18247. \begin{tcolorbox}[colback=white]
  18248. \small
  18249. {\if\edition\racketEd
  18250. \[
  18251. \begin{array}{l}
  18252. \gray{\CvarASTRacket} \\ \hline
  18253. \gray{\CifASTRacket} \\ \hline
  18254. \gray{\CloopASTRacket} \\ \hline
  18255. \gray{\CtupASTRacket} \\ \hline
  18256. \gray{\CfunASTRacket} \\ \hline
  18257. \gray{\ClambdaASTRacket} \\ \hline
  18258. \CanyASTRacket \\
  18259. \begin{array}{lcl}
  18260. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18261. \end{array}
  18262. \end{array}
  18263. \]
  18264. \fi}
  18265. {\if\edition\pythonEd\pythonColor
  18266. \[
  18267. \begin{array}{l}
  18268. \gray{\CifASTPython} \\ \hline
  18269. \gray{\CtupASTPython} \\ \hline
  18270. \gray{\CfunASTPython} \\ \hline
  18271. \gray{\ClambdaASTPython} \\ \hline
  18272. \CanyASTPython \\
  18273. \begin{array}{lcl}
  18274. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18275. \end{array}
  18276. \end{array}
  18277. \]
  18278. \fi}
  18279. \end{tcolorbox}
  18280. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18281. \label{fig:c5-syntax}
  18282. \end{figure}
  18283. \section{Select Instructions}
  18284. \label{sec:select-Lany}
  18285. \index{subject}{select instructions}
  18286. In the \code{select\_instructions} pass, we translate the primitive
  18287. operations on the \ANYTY{} type to x86 instructions that manipulate
  18288. the three tag bits of the tagged value. In the following descriptions,
  18289. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18290. of translating $e$ into an x86 argument:
  18291. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18292. We recommend compiling the
  18293. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18294. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18295. shifts the destination to the left by the number of bits specified by its
  18296. source argument (in this case three, the length of the tag), and it
  18297. preserves the sign of the integer. We use the \key{orq} instruction to
  18298. combine the tag and the value to form the tagged value.
  18299. {\if\edition\racketEd
  18300. \begin{lstlisting}
  18301. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18302. |$\Rightarrow$|
  18303. movq |$e'$|, |\itm{lhs'}|
  18304. salq $3, |\itm{lhs'}|
  18305. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18306. \end{lstlisting}
  18307. \fi}
  18308. %
  18309. {\if\edition\pythonEd\pythonColor
  18310. \begin{lstlisting}
  18311. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18312. |$\Rightarrow$|
  18313. movq |$e'$|, |\itm{lhs'}|
  18314. salq $3, |\itm{lhs'}|
  18315. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18316. \end{lstlisting}
  18317. \fi}
  18318. %
  18319. The instruction selection\index{subject}{instruction selection} for
  18320. tuples and procedures is different because there is no need to shift
  18321. them to the left. The rightmost 3 bits are already zeros, so we simply
  18322. combine the value and the tag using \key{orq}. \\
  18323. %
  18324. {\if\edition\racketEd
  18325. \begin{center}
  18326. \begin{minipage}{\textwidth}
  18327. \begin{lstlisting}
  18328. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18329. |$\Rightarrow$|
  18330. movq |$e'$|, |\itm{lhs'}|
  18331. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18332. \end{lstlisting}
  18333. \end{minipage}
  18334. \end{center}
  18335. \fi}
  18336. %
  18337. {\if\edition\pythonEd\pythonColor
  18338. \begin{lstlisting}
  18339. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18340. |$\Rightarrow$|
  18341. movq |$e'$|, |\itm{lhs'}|
  18342. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18343. \end{lstlisting}
  18344. \fi}
  18345. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18346. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18347. operation extracts the type tag from a value of type \ANYTY{}. The
  18348. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18349. bitwise-and of the value with $111$ ($7$ decimal).
  18350. %
  18351. {\if\edition\racketEd
  18352. \begin{lstlisting}
  18353. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18354. |$\Rightarrow$|
  18355. movq |$e'$|, |\itm{lhs'}|
  18356. andq $7, |\itm{lhs'}|
  18357. \end{lstlisting}
  18358. \fi}
  18359. %
  18360. {\if\edition\pythonEd\pythonColor
  18361. \begin{lstlisting}
  18362. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18363. |$\Rightarrow$|
  18364. movq |$e'$|, |\itm{lhs'}|
  18365. andq $7, |\itm{lhs'}|
  18366. \end{lstlisting}
  18367. \fi}
  18368. \paragraph{\code{ValueOf}}
  18369. The instructions for \key{ValueOf} also differ, depending on whether
  18370. the type $T$ is a pointer (tuple or function) or not (integer or
  18371. Boolean). The following shows the instruction
  18372. selection for integers and
  18373. Booleans, in which we produce an untagged value by shifting it to the
  18374. right by 3 bits:
  18375. %
  18376. {\if\edition\racketEd
  18377. \begin{lstlisting}
  18378. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18379. |$\Rightarrow$|
  18380. movq |$e'$|, |\itm{lhs'}|
  18381. sarq $3, |\itm{lhs'}|
  18382. \end{lstlisting}
  18383. \fi}
  18384. %
  18385. {\if\edition\pythonEd\pythonColor
  18386. \begin{lstlisting}
  18387. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18388. |$\Rightarrow$|
  18389. movq |$e'$|, |\itm{lhs'}|
  18390. sarq $3, |\itm{lhs'}|
  18391. \end{lstlisting}
  18392. \fi}
  18393. %
  18394. In the case for tuples and procedures, we zero out the rightmost 3
  18395. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18396. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18397. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18398. Finally, we apply \code{andq} with the tagged value to get the desired
  18399. result.
  18400. %
  18401. {\if\edition\racketEd
  18402. \begin{lstlisting}
  18403. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18404. |$\Rightarrow$|
  18405. movq $|$-8$|, |\itm{lhs'}|
  18406. andq |$e'$|, |\itm{lhs'}|
  18407. \end{lstlisting}
  18408. \fi}
  18409. %
  18410. {\if\edition\pythonEd\pythonColor
  18411. \begin{lstlisting}
  18412. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18413. |$\Rightarrow$|
  18414. movq $|$-8$|, |\itm{lhs'}|
  18415. andq |$e'$|, |\itm{lhs'}|
  18416. \end{lstlisting}
  18417. \fi}
  18418. %% \paragraph{Type Predicates} We leave it to the reader to
  18419. %% devise a sequence of instructions to implement the type predicates
  18420. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18421. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18422. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18423. operation combines the effect of \code{ValueOf} with accessing the
  18424. length of a tuple from the tag stored at the zero index of the tuple.
  18425. {\if\edition\racketEd
  18426. \begin{lstlisting}
  18427. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18428. |$\Longrightarrow$|
  18429. movq $|$-8$|, %r11
  18430. andq |$e_1'$|, %r11
  18431. movq 0(%r11), %r11
  18432. andq $126, %r11
  18433. sarq $1, %r11
  18434. movq %r11, |$\itm{lhs'}$|
  18435. \end{lstlisting}
  18436. \fi}
  18437. {\if\edition\pythonEd\pythonColor
  18438. \begin{lstlisting}
  18439. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18440. |$\Longrightarrow$|
  18441. movq $|$-8$|, %r11
  18442. andq |$e_1'$|, %r11
  18443. movq 0(%r11), %r11
  18444. andq $126, %r11
  18445. sarq $1, %r11
  18446. movq %r11, |$\itm{lhs'}$|
  18447. \end{lstlisting}
  18448. \fi}
  18449. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18450. This operation combines the effect of \code{ValueOf} with reading an
  18451. element of the tuple (see
  18452. section~\ref{sec:select-instructions-gc}). However, the index may be
  18453. an arbitrary atom, so instead of computing the offset at compile time,
  18454. we must generate instructions to compute the offset at runtime as
  18455. follows. Note the use of the new instruction \code{imulq}.
  18456. \begin{center}
  18457. \begin{minipage}{0.96\textwidth}
  18458. {\if\edition\racketEd
  18459. \begin{lstlisting}
  18460. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18461. |$\Longrightarrow$|
  18462. movq |$\neg 111$|, %r11
  18463. andq |$e_1'$|, %r11
  18464. movq |$e_2'$|, %rax
  18465. addq $1, %rax
  18466. imulq $8, %rax
  18467. addq %rax, %r11
  18468. movq 0(%r11) |$\itm{lhs'}$|
  18469. \end{lstlisting}
  18470. \fi}
  18471. %
  18472. {\if\edition\pythonEd\pythonColor
  18473. \begin{lstlisting}
  18474. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18475. |$\Longrightarrow$|
  18476. movq $|$-8$|, %r11
  18477. andq |$e_1'$|, %r11
  18478. movq |$e_2'$|, %rax
  18479. addq $1, %rax
  18480. imulq $8, %rax
  18481. addq %rax, %r11
  18482. movq 0(%r11) |$\itm{lhs'}$|
  18483. \end{lstlisting}
  18484. \fi}
  18485. \end{minipage}
  18486. \end{center}
  18487. % $ pacify font lock
  18488. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18489. %% The code generation for
  18490. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18491. %% analogous to the above translation for reading from a tuple.
  18492. \section{Register Allocation for \LangAny{}}
  18493. \label{sec:register-allocation-Lany}
  18494. \index{subject}{register allocation}
  18495. There is an interesting interaction between tagged values and garbage
  18496. collection that has an impact on register allocation. A variable of
  18497. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18498. that needs to be inspected and copied during garbage collection. Thus,
  18499. we need to treat variables of type \ANYTY{} in a similar way to
  18500. variables of tuple type for purposes of register allocation,
  18501. with particular attention to the following:
  18502. \begin{itemize}
  18503. \item If a variable of type \ANYTY{} is live during a function call,
  18504. then it must be spilled. This can be accomplished by changing
  18505. \code{build\_interference} to mark all variables of type \ANYTY{}
  18506. that are live after a \code{callq} to be interfering with all the
  18507. registers.
  18508. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18509. the root stack instead of the normal procedure call stack.
  18510. \end{itemize}
  18511. Another concern regarding the root stack is that the garbage collector
  18512. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18513. tagged value that points to a tuple, and (3) a tagged value that is
  18514. not a tuple. We enable this differentiation by choosing not to use the
  18515. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18516. reserved for identifying plain old pointers to tuples. That way, if
  18517. one of the first three bits is set, then we have a tagged value and
  18518. inspecting the tag can differentiate between tuples ($010$) and the
  18519. other kinds of values.
  18520. %% \begin{exercise}\normalfont
  18521. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18522. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18523. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18524. %% compiler on these new programs and all of your previously created test
  18525. %% programs.
  18526. %% \end{exercise}
  18527. \begin{exercise}\normalfont\normalsize
  18528. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18529. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18530. by removing type annotations. Add five more test programs that
  18531. specifically rely on the language being dynamically typed. That is,
  18532. they should not be legal programs in a statically typed language, but
  18533. nevertheless they should be valid \LangDyn{} programs that run to
  18534. completion without error.
  18535. \end{exercise}
  18536. \begin{figure}[p]
  18537. \begin{tcolorbox}[colback=white]
  18538. {\if\edition\racketEd
  18539. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18540. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18541. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18542. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18543. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18544. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18545. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18546. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18547. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18548. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18549. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18550. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18551. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18552. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18553. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18554. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18555. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18556. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18557. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18558. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18559. \path[->,bend left=15] (Lfun) edge [above] node
  18560. {\ttfamily\footnotesize shrink} (Lfun-2);
  18561. \path[->,bend left=15] (Lfun-2) edge [above] node
  18562. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18563. \path[->,bend left=15] (Lfun-3) edge [above] node
  18564. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18565. \path[->,bend left=15] (Lfun-4) edge [left] node
  18566. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18567. \path[->,bend left=15] (Lfun-5) edge [below] node
  18568. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18569. \path[->,bend left=15] (Lfun-6) edge [below] node
  18570. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18571. \path[->,bend right=15] (Lfun-7) edge [above] node
  18572. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18573. \path[->,bend right=15] (F1-2) edge [right] node
  18574. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18575. \path[->,bend right=15] (F1-3) edge [below] node
  18576. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18577. \path[->,bend right=15] (F1-4) edge [below] node
  18578. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18579. \path[->,bend left=15] (F1-5) edge [above] node
  18580. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18581. \path[->,bend left=10] (F1-6) edge [below] node
  18582. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18583. \path[->,bend left=15] (C3-2) edge [right] node
  18584. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18585. \path[->,bend right=15] (x86-2) edge [right] node
  18586. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18587. \path[->,bend right=15] (x86-2-1) edge [below] node
  18588. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18589. \path[->,bend right=15] (x86-2-2) edge [right] node
  18590. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18591. \path[->,bend left=15] (x86-3) edge [above] node
  18592. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18593. \path[->,bend left=15] (x86-4) edge [right] node
  18594. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18595. \end{tikzpicture}
  18596. \fi}
  18597. {\if\edition\pythonEd\pythonColor
  18598. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18599. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18600. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18601. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18602. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18603. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18604. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18605. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18606. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18607. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18608. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18609. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18610. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18611. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18612. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18613. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18614. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18615. \path[->,bend left=15] (Lfun) edge [above] node
  18616. {\ttfamily\footnotesize shrink} (Lfun-2);
  18617. \path[->,bend left=15] (Lfun-2) edge [above] node
  18618. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18619. \path[->,bend left=15] (Lfun-3) edge [above] node
  18620. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18621. \path[->,bend left=15] (Lfun-4) edge [left] node
  18622. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18623. \path[->,bend left=15] (Lfun-5) edge [below] node
  18624. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18625. \path[->,bend right=15] (Lfun-6) edge [above] node
  18626. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18627. \path[->,bend right=15] (Lfun-7) edge [above] node
  18628. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18629. \path[->,bend right=15] (F1-2) edge [right] node
  18630. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18631. \path[->,bend right=15] (F1-3) edge [below] node
  18632. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18633. \path[->,bend left=15] (F1-5) edge [above] node
  18634. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18635. \path[->,bend left=10] (F1-6) edge [below] node
  18636. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18637. \path[->,bend right=15] (C3-2) edge [right] node
  18638. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18639. \path[->,bend right=15] (x86-2) edge [below] node
  18640. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18641. \path[->,bend right=15] (x86-3) edge [below] node
  18642. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18643. \path[->,bend left=15] (x86-4) edge [above] node
  18644. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18645. \end{tikzpicture}
  18646. \fi}
  18647. \end{tcolorbox}
  18648. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18649. \label{fig:Ldyn-passes}
  18650. \end{figure}
  18651. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18652. for the compilation of \LangDyn{}.
  18653. % Further Reading
  18654. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18655. %% {\if\edition\pythonEd\pythonColor
  18656. %% \chapter{Objects}
  18657. %% \label{ch:Lobject}
  18658. %% \index{subject}{objects}
  18659. %% \index{subject}{classes}
  18660. %% \setcounter{footnote}{0}
  18661. %% \fi}
  18662. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18663. \chapter{Gradual Typing}
  18664. \label{ch:Lgrad}
  18665. \index{subject}{gradual typing}
  18666. \setcounter{footnote}{0}
  18667. This chapter studies the language \LangGrad{}, in which the programmer
  18668. can choose between static and dynamic type checking in different parts
  18669. of a program, thereby mixing the statically typed \LangLam{} language
  18670. with the dynamically typed \LangDyn{}. There are several approaches to
  18671. mixing static and dynamic typing, including multilanguage
  18672. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18673. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18674. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18675. programmer controls the amount of static versus dynamic checking by
  18676. adding or removing type annotations on parameters and
  18677. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18678. The definition of the concrete syntax of \LangGrad{} is shown in
  18679. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18680. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18681. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18682. annotations are optional, which is specified in the grammar using the
  18683. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18684. annotations are not optional, but we use the \CANYTY{} type when a type
  18685. annotation is absent.
  18686. %
  18687. Both the type checker and the interpreter for \LangGrad{} require some
  18688. interesting changes to enable gradual typing, which we discuss in the
  18689. next two sections.
  18690. \newcommand{\LgradGrammarRacket}{
  18691. \begin{array}{lcl}
  18692. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18693. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18694. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18695. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18696. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18697. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18698. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18699. \end{array}
  18700. }
  18701. \newcommand{\LgradASTRacket}{
  18702. \begin{array}{lcl}
  18703. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18704. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18705. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18706. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18707. \itm{op} &::=& \code{procedure-arity} \\
  18708. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18709. \end{array}
  18710. }
  18711. \newcommand{\LgradGrammarPython}{
  18712. \begin{array}{lcl}
  18713. \Type &::=& \key{Any}
  18714. \MID \key{int}
  18715. \MID \key{bool}
  18716. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18717. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18718. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18719. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18720. \MID \CARITY{\Exp} \\
  18721. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18722. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18723. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18724. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18725. \end{array}
  18726. }
  18727. \newcommand{\LgradASTPython}{
  18728. \begin{array}{lcl}
  18729. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18730. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18731. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18732. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18733. &\MID& \ARITY{\Exp} \\
  18734. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18735. \MID \RETURN{\Exp} \\
  18736. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18737. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18738. \end{array}
  18739. }
  18740. \begin{figure}[tp]
  18741. \centering
  18742. \begin{tcolorbox}[colback=white]
  18743. \small
  18744. {\if\edition\racketEd
  18745. \[
  18746. \begin{array}{l}
  18747. \gray{\LintGrammarRacket{}} \\ \hline
  18748. \gray{\LvarGrammarRacket{}} \\ \hline
  18749. \gray{\LifGrammarRacket{}} \\ \hline
  18750. \gray{\LwhileGrammarRacket} \\ \hline
  18751. \gray{\LtupGrammarRacket} \\ \hline
  18752. \LgradGrammarRacket \\
  18753. \begin{array}{lcl}
  18754. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18755. \end{array}
  18756. \end{array}
  18757. \]
  18758. \fi}
  18759. {\if\edition\pythonEd\pythonColor
  18760. \[
  18761. \begin{array}{l}
  18762. \gray{\LintGrammarPython{}} \\ \hline
  18763. \gray{\LvarGrammarPython{}} \\ \hline
  18764. \gray{\LifGrammarPython{}} \\ \hline
  18765. \gray{\LwhileGrammarPython} \\ \hline
  18766. \gray{\LtupGrammarPython} \\ \hline
  18767. \LgradGrammarPython \\
  18768. \begin{array}{lcl}
  18769. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18770. \end{array}
  18771. \end{array}
  18772. \]
  18773. \fi}
  18774. \end{tcolorbox}
  18775. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18776. \label{fig:Lgrad-concrete-syntax}
  18777. \end{figure}
  18778. \begin{figure}[tp]
  18779. \centering
  18780. \begin{tcolorbox}[colback=white]
  18781. \small
  18782. {\if\edition\racketEd
  18783. \[
  18784. \begin{array}{l}
  18785. \gray{\LintOpAST} \\ \hline
  18786. \gray{\LvarASTRacket{}} \\ \hline
  18787. \gray{\LifASTRacket{}} \\ \hline
  18788. \gray{\LwhileASTRacket{}} \\ \hline
  18789. \gray{\LtupASTRacket{}} \\ \hline
  18790. \LgradASTRacket \\
  18791. \begin{array}{lcl}
  18792. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18793. \end{array}
  18794. \end{array}
  18795. \]
  18796. \fi}
  18797. {\if\edition\pythonEd\pythonColor
  18798. \[
  18799. \begin{array}{l}
  18800. \gray{\LintASTPython{}} \\ \hline
  18801. \gray{\LvarASTPython{}} \\ \hline
  18802. \gray{\LifASTPython{}} \\ \hline
  18803. \gray{\LwhileASTPython} \\ \hline
  18804. \gray{\LtupASTPython} \\ \hline
  18805. \LgradASTPython \\
  18806. \begin{array}{lcl}
  18807. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18808. \end{array}
  18809. \end{array}
  18810. \]
  18811. \fi}
  18812. \end{tcolorbox}
  18813. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18814. \label{fig:Lgrad-syntax}
  18815. \end{figure}
  18816. % TODO: more road map -Jeremy
  18817. %\clearpage
  18818. \section{Type Checking \LangGrad{}}
  18819. \label{sec:gradual-type-check}
  18820. We begin by discussing the type checking of a partially typed variant
  18821. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18822. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18823. statically typed, so there is nothing special happening there with
  18824. respect to type checking. On the other hand, the \code{inc} function
  18825. does not have type annotations, so the type checker assigns the type
  18826. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18827. \code{+} operator inside \code{inc}. It expects both arguments to have
  18828. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18829. a gradually typed language, such differences are allowed so long as
  18830. the types are \emph{consistent}; that is, they are equal except in
  18831. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18832. is consistent with every other type. Figure~\ref{fig:consistent}
  18833. shows the definition of the
  18834. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18835. %
  18836. So the type checker allows the \code{+} operator to be applied
  18837. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18838. %
  18839. Next consider the call to the \code{map} function shown in
  18840. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18841. tuple. The \code{inc} function has type
  18842. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18843. but parameter \code{f} of \code{map} has type
  18844. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18845. The type checker for \LangGrad{} accepts this call because the two types are
  18846. consistent.
  18847. \begin{figure}[btp]
  18848. % gradual_test_9.rkt
  18849. \begin{tcolorbox}[colback=white]
  18850. {\if\edition\racketEd
  18851. \begin{lstlisting}
  18852. (define (map [f : (Integer -> Integer)]
  18853. [v : (Vector Integer Integer)])
  18854. : (Vector Integer Integer)
  18855. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18856. (define (inc x) (+ x 1))
  18857. (vector-ref (map inc (vector 0 41)) 1)
  18858. \end{lstlisting}
  18859. \fi}
  18860. {\if\edition\pythonEd\pythonColor
  18861. \begin{lstlisting}
  18862. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18863. return f(v[0]), f(v[1])
  18864. def inc(x):
  18865. return x + 1
  18866. t = map(inc, (0, 41))
  18867. print(t[1])
  18868. \end{lstlisting}
  18869. \fi}
  18870. \end{tcolorbox}
  18871. \caption{A partially typed version of the \code{map} example.}
  18872. \label{fig:gradual-map}
  18873. \end{figure}
  18874. \begin{figure}[tbp]
  18875. \begin{tcolorbox}[colback=white]
  18876. {\if\edition\racketEd
  18877. \begin{lstlisting}
  18878. (define/public (consistent? t1 t2)
  18879. (match* (t1 t2)
  18880. [('Integer 'Integer) #t]
  18881. [('Boolean 'Boolean) #t]
  18882. [('Void 'Void) #t]
  18883. [('Any t2) #t]
  18884. [(t1 'Any) #t]
  18885. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18886. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18887. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18888. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18889. (consistent? rt1 rt2))]
  18890. [(other wise) #f]))
  18891. \end{lstlisting}
  18892. \fi}
  18893. {\if\edition\pythonEd\pythonColor
  18894. \begin{lstlisting}
  18895. def consistent(self, t1, t2):
  18896. match (t1, t2):
  18897. case (AnyType(), _):
  18898. return True
  18899. case (_, AnyType()):
  18900. return True
  18901. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18902. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18903. case (TupleType(ts1), TupleType(ts2)):
  18904. return all(map(self.consistent, ts1, ts2))
  18905. case (_, _):
  18906. return t1 == t2
  18907. \end{lstlisting}
  18908. \fi}
  18909. \end{tcolorbox}
  18910. \caption{The consistency method on types.}
  18911. \label{fig:consistent}
  18912. \end{figure}
  18913. It is also helpful to consider how gradual typing handles programs with an
  18914. error, such as applying \code{map} to a function that sometimes
  18915. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18916. type checker for \LangGrad{} accepts this program because the type of
  18917. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18918. \code{map}; that is,
  18919. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18920. is consistent with
  18921. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18922. One might say that a gradual type checker is optimistic in that it
  18923. accepts programs that might execute without a runtime type error.
  18924. %
  18925. The definition of the type checker for \LangGrad{} is shown in
  18926. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18927. and \ref{fig:type-check-Lgradual-3}.
  18928. %% \begin{figure}[tp]
  18929. %% \centering
  18930. %% \fbox{
  18931. %% \begin{minipage}{0.96\textwidth}
  18932. %% \small
  18933. %% \[
  18934. %% \begin{array}{lcl}
  18935. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18936. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18937. %% \end{array}
  18938. %% \]
  18939. %% \end{minipage}
  18940. %% }
  18941. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18942. %% \label{fig:Lgrad-prime-syntax}
  18943. %% \end{figure}
  18944. \begin{figure}[tbp]
  18945. \begin{tcolorbox}[colback=white]
  18946. {\if\edition\racketEd
  18947. \begin{lstlisting}
  18948. (define (map [f : (Integer -> Integer)]
  18949. [v : (Vector Integer Integer)])
  18950. : (Vector Integer Integer)
  18951. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18952. (define (inc x) (+ x 1))
  18953. (define (true) #t)
  18954. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18955. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18956. \end{lstlisting}
  18957. \fi}
  18958. {\if\edition\pythonEd\pythonColor
  18959. \begin{lstlisting}
  18960. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18961. return f(v[0]), f(v[1])
  18962. def inc(x):
  18963. return x + 1
  18964. def true():
  18965. return True
  18966. def maybe_inc(x):
  18967. return inc(x) if input_int() == 0 else true()
  18968. t = map(maybe_inc, (0, 41))
  18969. print(t[1])
  18970. \end{lstlisting}
  18971. \fi}
  18972. \end{tcolorbox}
  18973. \caption{A variant of the \code{map} example with an error.}
  18974. \label{fig:map-maybe_inc}
  18975. \end{figure}
  18976. Running this program with input \code{1} triggers an
  18977. error when the \code{maybe\_inc} function returns
  18978. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18979. performs checking at runtime to ensure the integrity of the static
  18980. types, such as the
  18981. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18982. annotation on
  18983. parameter \code{f} of \code{map}.
  18984. Here we give a preview of how the runtime checking is accomplished;
  18985. the following sections provide the details.
  18986. The runtime checking is carried out by a new \code{Cast} AST node that
  18987. is generated in a new pass named \code{cast\_insert}. The output of
  18988. \code{cast\_insert} is a program in the \LangCast{} language, which
  18989. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18990. %
  18991. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18992. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18993. inserted every time the type checker encounters two types that are
  18994. consistent but not equal. In the \code{inc} function, \code{x} is
  18995. cast to \INTTY{} and the result of the \code{+} is cast to
  18996. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18997. is cast from
  18998. \racket{\code{(Any -> Any)}}
  18999. \python{\code{Callable[[Any], Any]}}
  19000. to
  19001. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19002. %
  19003. In the next section we see how to interpret the \code{Cast} node.
  19004. \begin{figure}[btp]
  19005. \begin{tcolorbox}[colback=white]
  19006. {\if\edition\racketEd
  19007. \begin{lstlisting}
  19008. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19009. : (Vector Integer Integer)
  19010. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19011. (define (inc [x : Any]) : Any
  19012. (cast (+ (cast x Any Integer) 1) Integer Any))
  19013. (define (true) : Any (cast #t Boolean Any))
  19014. (define (maybe_inc [x : Any]) : Any
  19015. (if (eq? 0 (read)) (inc x) (true)))
  19016. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19017. (vector 0 41)) 0)
  19018. \end{lstlisting}
  19019. \fi}
  19020. {\if\edition\pythonEd\pythonColor
  19021. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19022. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19023. return f(v[0]), f(v[1])
  19024. def inc(x : Any) -> Any:
  19025. return Cast(Cast(x, Any, int) + 1, int, Any)
  19026. def true() -> Any:
  19027. return Cast(True, bool, Any)
  19028. def maybe_inc(x : Any) -> Any:
  19029. return inc(x) if input_int() == 0 else true()
  19030. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19031. (0, 41))
  19032. print(t[1])
  19033. \end{lstlisting}
  19034. \fi}
  19035. \end{tcolorbox}
  19036. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19037. and \code{maybe\_inc} example.}
  19038. \label{fig:map-cast}
  19039. \end{figure}
  19040. {\if\edition\pythonEd\pythonColor
  19041. \begin{figure}[tbp]
  19042. \begin{tcolorbox}[colback=white]
  19043. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19044. class TypeCheckLgrad(TypeCheckLlambda):
  19045. def type_check_exp(self, e, env) -> Type:
  19046. match e:
  19047. case Name(id):
  19048. return env[id]
  19049. case Constant(value) if isinstance(value, bool):
  19050. return BoolType()
  19051. case Constant(value) if isinstance(value, int):
  19052. return IntType()
  19053. case Call(Name('input_int'), []):
  19054. return IntType()
  19055. case BinOp(left, op, right):
  19056. left_type = self.type_check_exp(left, env)
  19057. self.check_consistent(left_type, IntType(), left)
  19058. right_type = self.type_check_exp(right, env)
  19059. self.check_consistent(right_type, IntType(), right)
  19060. return IntType()
  19061. case IfExp(test, body, orelse):
  19062. test_t = self.type_check_exp(test, env)
  19063. self.check_consistent(test_t, BoolType(), test)
  19064. body_t = self.type_check_exp(body, env)
  19065. orelse_t = self.type_check_exp(orelse, env)
  19066. self.check_consistent(body_t, orelse_t, e)
  19067. return self.join_types(body_t, orelse_t)
  19068. case Call(func, args):
  19069. func_t = self.type_check_exp(func, env)
  19070. args_t = [self.type_check_exp(arg, env) for arg in args]
  19071. match func_t:
  19072. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  19073. for (arg_t, param_t) in zip(args_t, params_t):
  19074. self.check_consistent(param_t, arg_t, e)
  19075. return return_t
  19076. case AnyType():
  19077. return AnyType()
  19078. case _:
  19079. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  19080. ...
  19081. case _:
  19082. raise Exception('type_check_exp: unexpected ' + repr(e))
  19083. \end{lstlisting}
  19084. \end{tcolorbox}
  19085. \caption{Type checking expressions in the \LangGrad{} language.}
  19086. \label{fig:type-check-Lgradual-1}
  19087. \end{figure}
  19088. \begin{figure}[tbp]
  19089. \begin{tcolorbox}[colback=white]
  19090. \begin{lstlisting}
  19091. def check_exp(self, e, expected_ty, env):
  19092. match e:
  19093. case Lambda(params, body):
  19094. match expected_ty:
  19095. case FunctionType(params_t, return_t):
  19096. new_env = env.copy().update(zip(params, params_t))
  19097. e.has_type = expected_ty
  19098. body_ty = self.type_check_exp(body, new_env)
  19099. self.check_consistent(body_ty, return_t)
  19100. case AnyType():
  19101. new_env = env.copy().update((p, AnyType()) for p in params)
  19102. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19103. body_ty = self.type_check_exp(body, new_env)
  19104. case _:
  19105. raise Exception('lambda is not of type ' + str(expected_ty))
  19106. case _:
  19107. e_ty = self.type_check_exp(e, env)
  19108. self.check_consistent(e_ty, expected_ty, e)
  19109. \end{lstlisting}
  19110. \end{tcolorbox}
  19111. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19112. \label{fig:type-check-Lgradual-2}
  19113. \end{figure}
  19114. \begin{figure}[tbp]
  19115. \begin{tcolorbox}[colback=white]
  19116. \begin{lstlisting}
  19117. def type_check_stmt(self, s, env, return_type):
  19118. match s:
  19119. case Assign([Name(id)], value):
  19120. value_ty = self.type_check_exp(value, env)
  19121. if id in env:
  19122. self.check_consistent(env[id], value_ty, value)
  19123. else:
  19124. env[id] = value_ty
  19125. ...
  19126. case _:
  19127. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19128. def type_check_stmts(self, ss, env, return_type):
  19129. for s in ss:
  19130. self.type_check_stmt(s, env, return_type)
  19131. \end{lstlisting}
  19132. \end{tcolorbox}
  19133. \caption{Type checking statements in the \LangGrad{} language.}
  19134. \label{fig:type-check-Lgradual-3}
  19135. \end{figure}
  19136. \begin{figure}[tbp]
  19137. \begin{tcolorbox}[colback=white]
  19138. \begin{lstlisting}
  19139. def join_types(self, t1, t2):
  19140. match (t1, t2):
  19141. case (AnyType(), _):
  19142. return t2
  19143. case (_, AnyType()):
  19144. return t1
  19145. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19146. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19147. self.join_types(rt1,rt2))
  19148. case (TupleType(ts1), TupleType(ts2)):
  19149. return TupleType(list(map(self.join_types, ts1, ts2)))
  19150. case (_, _):
  19151. return t1
  19152. def check_consistent(self, t1, t2, e):
  19153. if not self.consistent(t1, t2):
  19154. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19155. + repr(t2) + ' in ' + repr(e))
  19156. \end{lstlisting}
  19157. \end{tcolorbox}
  19158. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19159. \label{fig:type-check-Lgradual-aux}
  19160. \end{figure}
  19161. \fi}
  19162. {\if\edition\racketEd
  19163. \begin{figure}[tbp]
  19164. \begin{tcolorbox}[colback=white]
  19165. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19166. (define/override (type-check-exp env)
  19167. (lambda (e)
  19168. (define recur (type-check-exp env))
  19169. (match e
  19170. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19171. (define-values (new-es ts)
  19172. (for/lists (exprs types) ([e es])
  19173. (recur e)))
  19174. (define t-ret (type-check-op op ts e))
  19175. (values (Prim op new-es) t-ret)]
  19176. [(Prim 'eq? (list e1 e2))
  19177. (define-values (e1^ t1) (recur e1))
  19178. (define-values (e2^ t2) (recur e2))
  19179. (check-consistent? t1 t2 e)
  19180. (define T (meet t1 t2))
  19181. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19182. [(Prim 'and (list e1 e2))
  19183. (recur (If e1 e2 (Bool #f)))]
  19184. [(Prim 'or (list e1 e2))
  19185. (define tmp (gensym 'tmp))
  19186. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19187. [(If e1 e2 e3)
  19188. (define-values (e1^ T1) (recur e1))
  19189. (define-values (e2^ T2) (recur e2))
  19190. (define-values (e3^ T3) (recur e3))
  19191. (check-consistent? T1 'Boolean e)
  19192. (check-consistent? T2 T3 e)
  19193. (define Tif (meet T2 T3))
  19194. (values (If e1^ e2^ e3^) Tif)]
  19195. [(SetBang x e1)
  19196. (define-values (e1^ T1) (recur e1))
  19197. (define varT (dict-ref env x))
  19198. (check-consistent? T1 varT e)
  19199. (values (SetBang x e1^) 'Void)]
  19200. [(WhileLoop e1 e2)
  19201. (define-values (e1^ T1) (recur e1))
  19202. (check-consistent? T1 'Boolean e)
  19203. (define-values (e2^ T2) ((type-check-exp env) e2))
  19204. (values (WhileLoop e1^ e2^) 'Void)]
  19205. [(Prim 'vector-length (list e1))
  19206. (define-values (e1^ t) (recur e1))
  19207. (match t
  19208. [`(Vector ,ts ...)
  19209. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19210. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19211. \end{lstlisting}
  19212. \end{tcolorbox}
  19213. \caption{Type checker for the \LangGrad{} language, part 1.}
  19214. \label{fig:type-check-Lgradual-1}
  19215. \end{figure}
  19216. \begin{figure}[tbp]
  19217. \begin{tcolorbox}[colback=white]
  19218. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19219. [(Prim 'vector-ref (list e1 e2))
  19220. (define-values (e1^ t1) (recur e1))
  19221. (define-values (e2^ t2) (recur e2))
  19222. (check-consistent? t2 'Integer e)
  19223. (match t1
  19224. [`(Vector ,ts ...)
  19225. (match e2^
  19226. [(Int i)
  19227. (unless (and (0 . <= . i) (i . < . (length ts)))
  19228. (error 'type-check "invalid index ~a in ~a" i e))
  19229. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19230. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19231. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19232. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19233. [(Prim 'vector-set! (list e1 e2 e3) )
  19234. (define-values (e1^ t1) (recur e1))
  19235. (define-values (e2^ t2) (recur e2))
  19236. (define-values (e3^ t3) (recur e3))
  19237. (check-consistent? t2 'Integer e)
  19238. (match t1
  19239. [`(Vector ,ts ...)
  19240. (match e2^
  19241. [(Int i)
  19242. (unless (and (0 . <= . i) (i . < . (length ts)))
  19243. (error 'type-check "invalid index ~a in ~a" i e))
  19244. (check-consistent? (list-ref ts i) t3 e)
  19245. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19246. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19247. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19248. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19249. [(Apply e1 e2s)
  19250. (define-values (e1^ T1) (recur e1))
  19251. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19252. (match T1
  19253. [`(,T1ps ... -> ,T1rt)
  19254. (for ([T2 T2s] [Tp T1ps])
  19255. (check-consistent? T2 Tp e))
  19256. (values (Apply e1^ e2s^) T1rt)]
  19257. [`Any (values (Apply e1^ e2s^) 'Any)]
  19258. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19259. [(Lambda params Tr e1)
  19260. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19261. (match p
  19262. [`[,x : ,T] (values x T)]
  19263. [(? symbol? x) (values x 'Any)])))
  19264. (define-values (e1^ T1)
  19265. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19266. (check-consistent? Tr T1 e)
  19267. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19268. `(,@Ts -> ,Tr))]
  19269. [else ((super type-check-exp env) e)]
  19270. )))
  19271. \end{lstlisting}
  19272. \end{tcolorbox}
  19273. \caption{Type checker for the \LangGrad{} language, part 2.}
  19274. \label{fig:type-check-Lgradual-2}
  19275. \end{figure}
  19276. \begin{figure}[tbp]
  19277. \begin{tcolorbox}[colback=white]
  19278. \begin{lstlisting}
  19279. (define/override (type-check-def env)
  19280. (lambda (e)
  19281. (match e
  19282. [(Def f params rt info body)
  19283. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19284. (match p
  19285. [`[,x : ,T] (values x T)]
  19286. [(? symbol? x) (values x 'Any)])))
  19287. (define new-env (append (map cons xs ps) env))
  19288. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19289. (check-consistent? ty^ rt e)
  19290. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19291. [else (error 'type-check "ill-formed function definition ~a" e)]
  19292. )))
  19293. (define/override (type-check-program e)
  19294. (match e
  19295. [(Program info body)
  19296. (define-values (body^ ty) ((type-check-exp '()) body))
  19297. (check-consistent? ty 'Integer e)
  19298. (ProgramDefsExp info '() body^)]
  19299. [(ProgramDefsExp info ds body)
  19300. (define new-env (for/list ([d ds])
  19301. (cons (Def-name d) (fun-def-type d))))
  19302. (define ds^ (for/list ([d ds])
  19303. ((type-check-def new-env) d)))
  19304. (define-values (body^ ty) ((type-check-exp new-env) body))
  19305. (check-consistent? ty 'Integer e)
  19306. (ProgramDefsExp info ds^ body^)]
  19307. [else (super type-check-program e)]))
  19308. \end{lstlisting}
  19309. \end{tcolorbox}
  19310. \caption{Type checker for the \LangGrad{} language, part 3.}
  19311. \label{fig:type-check-Lgradual-3}
  19312. \end{figure}
  19313. \begin{figure}[tbp]
  19314. \begin{tcolorbox}[colback=white]
  19315. \begin{lstlisting}
  19316. (define/public (join t1 t2)
  19317. (match* (t1 t2)
  19318. [('Integer 'Integer) 'Integer]
  19319. [('Boolean 'Boolean) 'Boolean]
  19320. [('Void 'Void) 'Void]
  19321. [('Any t2) t2]
  19322. [(t1 'Any) t1]
  19323. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19324. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19325. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19326. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19327. -> ,(join rt1 rt2))]))
  19328. (define/public (meet t1 t2)
  19329. (match* (t1 t2)
  19330. [('Integer 'Integer) 'Integer]
  19331. [('Boolean 'Boolean) 'Boolean]
  19332. [('Void 'Void) 'Void]
  19333. [('Any t2) 'Any]
  19334. [(t1 'Any) 'Any]
  19335. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19336. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19337. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19338. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19339. -> ,(meet rt1 rt2))]))
  19340. (define/public (check-consistent? t1 t2 e)
  19341. (unless (consistent? t1 t2)
  19342. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19343. (define explicit-prim-ops
  19344. (set-union
  19345. (type-predicates)
  19346. (set 'procedure-arity 'eq? 'not 'and 'or
  19347. 'vector 'vector-length 'vector-ref 'vector-set!
  19348. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19349. (define/override (fun-def-type d)
  19350. (match d
  19351. [(Def f params rt info body)
  19352. (define ps
  19353. (for/list ([p params])
  19354. (match p
  19355. [`[,x : ,T] T]
  19356. [(? symbol?) 'Any]
  19357. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19358. `(,@ps -> ,rt)]
  19359. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19360. \end{lstlisting}
  19361. \end{tcolorbox}
  19362. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19363. \label{fig:type-check-Lgradual-aux}
  19364. \end{figure}
  19365. \fi}
  19366. \clearpage
  19367. \section{Interpreting \LangCast{}}
  19368. \label{sec:interp-casts}
  19369. The runtime behavior of casts involving simple types such as
  19370. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19371. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19372. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19373. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19374. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19375. operator, by checking the value's tag and either retrieving
  19376. the underlying integer or signaling an error if the tag is not the
  19377. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19378. %
  19379. Things get more interesting with casts involving
  19380. \racket{function and tuple types}\python{function, tuple, and array types}.
  19381. Consider the cast of the function \code{maybe\_inc} from
  19382. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19383. to
  19384. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19385. shown in figure~\ref{fig:map-maybe_inc}.
  19386. When the \code{maybe\_inc} function flows through
  19387. this cast at runtime, we don't know whether it will return
  19388. an integer, because that depends on the input from the user.
  19389. The \LangCast{} interpreter therefore delays the checking
  19390. of the cast until the function is applied. To do so it
  19391. wraps \code{maybe\_inc} in a new function that casts its parameter
  19392. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19393. casts the return value from \CANYTY{} to \INTTY{}.
  19394. {\if\edition\pythonEd\pythonColor
  19395. %
  19396. There are further complications regarding casts on mutable data,
  19397. such as the \code{list} type introduced in
  19398. the challenge assignment of section~\ref{sec:arrays}.
  19399. %
  19400. \fi}
  19401. %
  19402. Consider the example presented in figure~\ref{fig:map-bang} that
  19403. defines a partially typed version of \code{map} whose parameter
  19404. \code{v} has type
  19405. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19406. and that updates \code{v} in place
  19407. instead of returning a new tuple. We name this function
  19408. \code{map\_inplace}. We apply \code{map\_inplace} to
  19409. \racket{a tuple}\python{an array} of integers, so the type checker
  19410. inserts a cast from
  19411. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19412. to
  19413. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19414. A naive way for the \LangCast{} interpreter to cast between
  19415. \racket{tuple}\python{array} types would be to build a new
  19416. \racket{tuple}\python{array} whose elements are the result
  19417. of casting each of the original elements to the appropriate target
  19418. type. However, this approach is not valid for mutable data structures.
  19419. In the example of figure~\ref{fig:map-bang},
  19420. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19421. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19422. the original one.
  19423. \begin{figure}[tbp]
  19424. \begin{tcolorbox}[colback=white]
  19425. % gradual_test_11.rkt
  19426. {\if\edition\racketEd
  19427. \begin{lstlisting}
  19428. (define (map_inplace [f : (Any -> Any)]
  19429. [v : (Vector Any Any)]) : Void
  19430. (begin
  19431. (vector-set! v 0 (f (vector-ref v 0)))
  19432. (vector-set! v 1 (f (vector-ref v 1)))))
  19433. (define (inc x) (+ x 1))
  19434. (let ([v (vector 0 41)])
  19435. (begin (map_inplace inc v) (vector-ref v 1)))
  19436. \end{lstlisting}
  19437. \fi}
  19438. {\if\edition\pythonEd\pythonColor
  19439. \begin{lstlisting}
  19440. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19441. i = 0
  19442. while i != len(v):
  19443. v[i] = f(v[i])
  19444. i = i + 1
  19445. def inc(x : int) -> int:
  19446. return x + 1
  19447. v = [0, 41]
  19448. map_inplace(inc, v)
  19449. print(v[1])
  19450. \end{lstlisting}
  19451. \fi}
  19452. \end{tcolorbox}
  19453. \caption{An example involving casts on arrays.}
  19454. \label{fig:map-bang}
  19455. \end{figure}
  19456. Instead the interpreter needs to create a new kind of value, a
  19457. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19458. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19459. and then applies a
  19460. cast to the resulting value. On a write, the proxy casts the argument
  19461. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19462. \racket{
  19463. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19464. \code{0} from \INTTY{} to \CANYTY{}.
  19465. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19466. from \CANYTY{} to \INTTY{}.
  19467. }
  19468. \python{
  19469. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19470. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19471. For the subscript on the left of the assignment,
  19472. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19473. }
  19474. Finally we consider casts between the \CANYTY{} type and higher-order types
  19475. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19476. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19477. have a type annotation, so it is given type \CANYTY{}. In the call to
  19478. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19479. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19480. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19481. \code{Inject}, but that doesn't work because
  19482. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19483. a flat type. Instead, we must first cast to
  19484. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19485. and then inject to \CANYTY{}.
  19486. \begin{figure}[tbp]
  19487. \begin{tcolorbox}[colback=white]
  19488. {\if\edition\racketEd
  19489. \begin{lstlisting}
  19490. (define (map_inplace [f : (Any -> Any)] v) : Void
  19491. (begin
  19492. (vector-set! v 0 (f (vector-ref v 0)))
  19493. (vector-set! v 1 (f (vector-ref v 1)))))
  19494. (define (inc x) (+ x 1))
  19495. (let ([v (vector 0 41)])
  19496. (begin (map_inplace inc v) (vector-ref v 1)))
  19497. \end{lstlisting}
  19498. \fi}
  19499. {\if\edition\pythonEd\pythonColor
  19500. \begin{lstlisting}
  19501. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19502. i = 0
  19503. while i != len(v):
  19504. v[i] = f(v[i])
  19505. i = i + 1
  19506. def inc(x):
  19507. return x + 1
  19508. v = [0, 41]
  19509. map_inplace(inc, v)
  19510. print(v[1])
  19511. \end{lstlisting}
  19512. \fi}
  19513. \end{tcolorbox}
  19514. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19515. \label{fig:map-any}
  19516. \end{figure}
  19517. \begin{figure}[tbp]
  19518. \begin{tcolorbox}[colback=white]
  19519. {\if\edition\racketEd
  19520. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19521. (define/public (apply_cast v s t)
  19522. (match* (s t)
  19523. [(t1 t2) #:when (equal? t1 t2) v]
  19524. [('Any t2)
  19525. (match t2
  19526. [`(,ts ... -> ,rt)
  19527. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19528. (define v^ (apply-project v any->any))
  19529. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19530. [`(Vector ,ts ...)
  19531. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19532. (define v^ (apply-project v vec-any))
  19533. (apply_cast v^ vec-any `(Vector ,@ts))]
  19534. [else (apply-project v t2)])]
  19535. [(t1 'Any)
  19536. (match t1
  19537. [`(,ts ... -> ,rt)
  19538. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19539. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19540. (apply-inject v^ (any-tag any->any))]
  19541. [`(Vector ,ts ...)
  19542. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19543. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19544. (apply-inject v^ (any-tag vec-any))]
  19545. [else (apply-inject v (any-tag t1))])]
  19546. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19547. (define x (gensym 'x))
  19548. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19549. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19550. (define cast-writes
  19551. (for/list ([t1 ts1] [t2 ts2])
  19552. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19553. `(vector-proxy ,(vector v (apply vector cast-reads)
  19554. (apply vector cast-writes)))]
  19555. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19556. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19557. `(function ,xs ,(Cast
  19558. (Apply (Value v)
  19559. (for/list ([x xs][t1 ts1][t2 ts2])
  19560. (Cast (Var x) t2 t1)))
  19561. rt1 rt2) ())]
  19562. ))
  19563. \end{lstlisting}
  19564. \fi}
  19565. {\if\edition\pythonEd\pythonColor
  19566. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19567. def apply_cast(self, value, src, tgt):
  19568. match (src, tgt):
  19569. case (AnyType(), FunctionType(ps2, rt2)):
  19570. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19571. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19572. case (AnyType(), TupleType(ts2)):
  19573. anytup = TupleType([AnyType() for t1 in ts2])
  19574. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19575. case (AnyType(), ListType(t2)):
  19576. anylist = ListType([AnyType() for t1 in ts2])
  19577. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19578. case (AnyType(), AnyType()):
  19579. return value
  19580. case (AnyType(), _):
  19581. return self.apply_project(value, tgt)
  19582. case (FunctionType(ps1,rt1), AnyType()):
  19583. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19584. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19585. case (TupleType(ts1), AnyType()):
  19586. anytup = TupleType([AnyType() for t1 in ts1])
  19587. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19588. case (ListType(t1), AnyType()):
  19589. anylist = ListType(AnyType())
  19590. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19591. case (_, AnyType()):
  19592. return self.apply_inject(value, src)
  19593. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19594. params = [generate_name('x') for p in ps2]
  19595. args = [Cast(Name(x), t2, t1)
  19596. for (x,t1,t2) in zip(params, ps1, ps2)]
  19597. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19598. return Function('cast', params, [Return(body)], {})
  19599. case (TupleType(ts1), TupleType(ts2)):
  19600. x = generate_name('x')
  19601. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19602. for (t1,t2) in zip(ts1,ts2)]
  19603. return ProxiedTuple(value, reads)
  19604. case (ListType(t1), ListType(t2)):
  19605. x = generate_name('x')
  19606. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19607. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19608. return ProxiedList(value, read, write)
  19609. case (t1, t2) if t1 == t2:
  19610. return value
  19611. case (t1, t2):
  19612. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19613. def apply_inject(self, value, src):
  19614. return Tagged(value, self.type_to_tag(src))
  19615. def apply_project(self, value, tgt):
  19616. match value:
  19617. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19618. return val
  19619. case _:
  19620. raise Exception('apply_project, unexpected ' + repr(value))
  19621. \end{lstlisting}
  19622. \fi}
  19623. \end{tcolorbox}
  19624. \caption{The \code{apply\_cast} auxiliary method.}
  19625. \label{fig:apply_cast}
  19626. \end{figure}
  19627. The \LangCast{} interpreter uses an auxiliary function named
  19628. \code{apply\_cast} to cast a value from a source type to a target type,
  19629. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19630. the kinds of casts that we've discussed in this section.
  19631. %
  19632. The definition of the interpreter for \LangCast{} is shown in
  19633. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19634. dispatching to \code{apply\_cast}.
  19635. \racket{To handle the addition of tuple
  19636. proxies, we update the tuple primitives in \code{interp-op} using the
  19637. functions given in figure~\ref{fig:guarded-tuple}.}
  19638. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19639. \begin{figure}[tbp]
  19640. \begin{tcolorbox}[colback=white]
  19641. {\if\edition\racketEd
  19642. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19643. (define interp-Lcast-class
  19644. (class interp-Llambda-class
  19645. (super-new)
  19646. (inherit apply-fun apply-inject apply-project)
  19647. (define/override (interp-op op)
  19648. (match op
  19649. ['vector-length guarded-vector-length]
  19650. ['vector-ref guarded-vector-ref]
  19651. ['vector-set! guarded-vector-set!]
  19652. ['any-vector-ref (lambda (v i)
  19653. (match v [`(tagged ,v^ ,tg)
  19654. (guarded-vector-ref v^ i)]))]
  19655. ['any-vector-set! (lambda (v i a)
  19656. (match v [`(tagged ,v^ ,tg)
  19657. (guarded-vector-set! v^ i a)]))]
  19658. ['any-vector-length (lambda (v)
  19659. (match v [`(tagged ,v^ ,tg)
  19660. (guarded-vector-length v^)]))]
  19661. [else (super interp-op op)]
  19662. ))
  19663. (define/override ((interp-exp env) e)
  19664. (define (recur e) ((interp-exp env) e))
  19665. (match e
  19666. [(Value v) v]
  19667. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19668. [else ((super interp-exp env) e)]))
  19669. ))
  19670. (define (interp-Lcast p)
  19671. (send (new interp-Lcast-class) interp-program p))
  19672. \end{lstlisting}
  19673. \fi}
  19674. {\if\edition\pythonEd\pythonColor
  19675. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19676. class InterpLcast(InterpLany):
  19677. def interp_exp(self, e, env):
  19678. match e:
  19679. case Cast(value, src, tgt):
  19680. v = self.interp_exp(value, env)
  19681. return self.apply_cast(v, src, tgt)
  19682. case ValueExp(value):
  19683. return value
  19684. ...
  19685. case _:
  19686. return super().interp_exp(e, env)
  19687. \end{lstlisting}
  19688. \fi}
  19689. \end{tcolorbox}
  19690. \caption{The interpreter for \LangCast{}.}
  19691. \label{fig:interp-Lcast}
  19692. \end{figure}
  19693. {\if\edition\racketEd
  19694. \begin{figure}[tbp]
  19695. \begin{tcolorbox}[colback=white]
  19696. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19697. (define (guarded-vector-ref vec i)
  19698. (match vec
  19699. [`(vector-proxy ,proxy)
  19700. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19701. (define rd (vector-ref (vector-ref proxy 1) i))
  19702. (apply-fun rd (list val) 'guarded-vector-ref)]
  19703. [else (vector-ref vec i)]))
  19704. (define (guarded-vector-set! vec i arg)
  19705. (match vec
  19706. [`(vector-proxy ,proxy)
  19707. (define wr (vector-ref (vector-ref proxy 2) i))
  19708. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19709. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19710. [else (vector-set! vec i arg)]))
  19711. (define (guarded-vector-length vec)
  19712. (match vec
  19713. [`(vector-proxy ,proxy)
  19714. (guarded-vector-length (vector-ref proxy 0))]
  19715. [else (vector-length vec)]))
  19716. \end{lstlisting}
  19717. %% {\if\edition\pythonEd\pythonColor
  19718. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19719. %% UNDER CONSTRUCTION
  19720. %% \end{lstlisting}
  19721. %% \fi}
  19722. \end{tcolorbox}
  19723. \caption{The \code{guarded-vector} auxiliary functions.}
  19724. \label{fig:guarded-tuple}
  19725. \end{figure}
  19726. \fi}
  19727. {\if\edition\pythonEd\pythonColor
  19728. \section{Overload Resolution}
  19729. \label{sec:gradual-resolution}
  19730. Recall that when we added support for arrays in
  19731. section~\ref{sec:arrays}, the syntax for the array operations were the
  19732. same as for tuple operations (for example, accessing an element and
  19733. getting the length). So we performed overload resolution, with a pass
  19734. named \code{resolve}, to separate the array and tuple operations. In
  19735. particular, we introduced the primitives \code{array\_load},
  19736. \code{array\_store}, and \code{array\_len}.
  19737. For gradual typing, we further overload these operators to work on
  19738. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19739. updated with new cases for the \CANYTY{} type, translating the element
  19740. access and length operations to the primitives \code{any\_load},
  19741. \code{any\_store}, and \code{any\_len}.
  19742. \fi}
  19743. \section{Cast Insertion}
  19744. \label{sec:gradual-insert-casts}
  19745. In our discussion of type checking of \LangGrad{}, we mentioned how
  19746. the runtime aspect of type checking is carried out by the \code{Cast}
  19747. AST node, which is added to the program by a new pass named
  19748. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19749. language. We now discuss the details of this pass.
  19750. The \code{cast\_insert} pass is closely related to the type checker
  19751. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19752. In particular, the type checker allows implicit casts between
  19753. consistent types. The job of the \code{cast\_insert} pass is to make
  19754. those casts explicit. It does so by inserting
  19755. \code{Cast} nodes into the AST.
  19756. %
  19757. For the most part, the implicit casts occur in places where the type
  19758. checker checks two types for consistency. Consider the case for
  19759. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19760. checker requires that the type of the left operand is consistent with
  19761. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19762. \code{Cast} around the left operand, converting from its type to
  19763. \INTTY{}. The story is similar for the right operand. It is not always
  19764. necessary to insert a cast, for example, if the left operand already has type
  19765. \INTTY{} then there is no need for a \code{Cast}.
  19766. Some of the implicit casts are not as straightforward. One such case
  19767. arises with the
  19768. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19769. see that the type checker requires that the two branches have
  19770. consistent types and that type of the conditional expression is the
  19771. meet of the branches' types. In the target language \LangCast{}, both
  19772. branches will need to have the same type, and that type
  19773. will be the type of the conditional expression. Thus, each branch requires
  19774. a \code{Cast} to convert from its type to the meet of the branches' types.
  19775. The case for the function call exhibits another interesting situation. If
  19776. the function expression is of type \CANYTY{}, then it needs to be cast
  19777. to a function type so that it can be used in a function call in
  19778. \LangCast{}. Which function type should it be cast to? The parameter
  19779. and return types are unknown, so we can simply use \CANYTY{} for all
  19780. of them. Furthermore, in \LangCast{} the argument types will need to
  19781. exactly match the parameter types, so we must cast all the arguments
  19782. to type \CANYTY{} (if they are not already of that type).
  19783. {\if\edition\racketEd
  19784. %
  19785. Likewise, the cases for the tuple operators \code{vector-length},
  19786. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19787. where the tuple expression is of type \CANYTY{}. Instead of
  19788. handling these situations with casts, we recommend translating
  19789. the special-purpose variants of the tuple operators that handle
  19790. tuples of type \CANYTY{}: \code{any-vector-length},
  19791. \code{any-vector-ref}, and \code{any-vector-set!}.
  19792. %
  19793. \fi}
  19794. \section{Lower Casts}
  19795. \label{sec:lower_casts}
  19796. The next step in the journey toward x86 is the \code{lower\_casts}
  19797. pass that translates the casts in \LangCast{} to the lower-level
  19798. \code{Inject} and \code{Project} operators and new operators for
  19799. proxies, extending the \LangLam{} language to \LangProxy{}.
  19800. The \LangProxy{} language can also be described as an extension of
  19801. \LangAny{}, with the addition of proxies. We recommend creating an
  19802. auxiliary function named \code{lower\_cast} that takes an expression
  19803. (in \LangCast{}), a source type, and a target type and translates it
  19804. to an expression in \LangProxy{}.
  19805. The \code{lower\_cast} function can follow a code structure similar to
  19806. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19807. the interpreter for \LangCast{}, because it must handle the same cases
  19808. as \code{apply\_cast} and it needs to mimic the behavior of
  19809. \code{apply\_cast}. The most interesting cases concern
  19810. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19811. {\if\edition\racketEd
  19812. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19813. type to another tuple type is accomplished by creating a proxy that
  19814. intercepts the operations on the underlying tuple. Here we make the
  19815. creation of the proxy explicit with the \code{vector-proxy} AST
  19816. node. It takes three arguments: the first is an expression for the
  19817. tuple, the second is a tuple of functions for casting an element that is
  19818. being read from the tuple, and the third is a tuple of functions for
  19819. casting an element that is being written to the array. You can create
  19820. the functions for reading and writing using lambda expressions. Also,
  19821. as we show in the next section, we need to differentiate these tuples
  19822. of functions from the user-created ones, so we recommend using a new
  19823. AST node named \code{raw-vector} instead of \code{vector}.
  19824. %
  19825. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19826. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19827. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19828. \fi}
  19829. {\if\edition\pythonEd\pythonColor
  19830. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19831. type to another array type is accomplished by creating a proxy that
  19832. intercepts the operations on the underlying array. Here we make the
  19833. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19834. takes fives arguments: the first is an expression for the array, the
  19835. second is a function for casting an element that is being read from
  19836. the array, the third is a function for casting an element that is
  19837. being written to the array, the fourth is the type of the underlying
  19838. array, and the fifth is the type of the proxied array. You can create
  19839. the functions for reading and writing using lambda expressions.
  19840. A cast between two tuple types can be handled in a similar manner. We
  19841. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19842. immutable, so there is no need for a function to cast the value during
  19843. a write. Because there is a separate element type for each slot in
  19844. the tuple, we need more than one function for casting during a read:
  19845. we need a tuple of functions.
  19846. %
  19847. Also, as we show in the next section, we need to differentiate these
  19848. tuples from the user-created ones, so we recommend using a new AST
  19849. node named \code{RawTuple} instead of \code{Tuple} to create the
  19850. tuples of functions.
  19851. %
  19852. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19853. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19854. that involves casting an array of integers to an array of \CANYTY{}.
  19855. \fi}
  19856. \begin{figure}[tbp]
  19857. \begin{tcolorbox}[colback=white]
  19858. {\if\edition\racketEd
  19859. \begin{lstlisting}
  19860. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19861. (begin
  19862. (vector-set! v 0 (f (vector-ref v 0)))
  19863. (vector-set! v 1 (f (vector-ref v 1)))))
  19864. (define (inc [x : Any]) : Any
  19865. (inject (+ (project x Integer) 1) Integer))
  19866. (let ([v (vector 0 41)])
  19867. (begin
  19868. (map_inplace inc (vector-proxy v
  19869. (raw-vector (lambda: ([x9 : Integer]) : Any
  19870. (inject x9 Integer))
  19871. (lambda: ([x9 : Integer]) : Any
  19872. (inject x9 Integer)))
  19873. (raw-vector (lambda: ([x9 : Any]) : Integer
  19874. (project x9 Integer))
  19875. (lambda: ([x9 : Any]) : Integer
  19876. (project x9 Integer)))))
  19877. (vector-ref v 1)))
  19878. \end{lstlisting}
  19879. \fi}
  19880. {\if\edition\pythonEd\pythonColor
  19881. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19882. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19883. i = 0
  19884. while i != array_len(v):
  19885. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19886. i = (i + 1)
  19887. def inc(x : int) -> int:
  19888. return (x + 1)
  19889. def main() -> int:
  19890. v = [0, 41]
  19891. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19892. print(array_load(v, 1))
  19893. return 0
  19894. \end{lstlisting}
  19895. \fi}
  19896. \end{tcolorbox}
  19897. \caption{Output of \code{lower\_casts} on the example shown in
  19898. figure~\ref{fig:map-bang}.}
  19899. \label{fig:map-bang-lower-cast}
  19900. \end{figure}
  19901. A cast from one function type to another function type is accomplished
  19902. by generating a \code{lambda} whose parameter and return types match
  19903. the target function type. The body of the \code{lambda} should cast
  19904. the parameters from the target type to the source type. (Yes,
  19905. backward! Functions are contravariant\index{subject}{contravariant}
  19906. in the parameters.) Afterward, call the underlying function and then
  19907. cast the result from the source return type to the target return type.
  19908. Figure~\ref{fig:map-lower-cast} shows the output of the
  19909. \code{lower\_casts} pass on the \code{map} example give in
  19910. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19911. call to \code{map} is wrapped in a \code{lambda}.
  19912. \begin{figure}[tbp]
  19913. \begin{tcolorbox}[colback=white]
  19914. {\if\edition\racketEd
  19915. \begin{lstlisting}
  19916. (define (map [f : (Integer -> Integer)]
  19917. [v : (Vector Integer Integer)])
  19918. : (Vector Integer Integer)
  19919. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19920. (define (inc [x : Any]) : Any
  19921. (inject (+ (project x Integer) 1) Integer))
  19922. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19923. (project (inc (inject x9 Integer)) Integer))
  19924. (vector 0 41)) 1)
  19925. \end{lstlisting}
  19926. \fi}
  19927. {\if\edition\pythonEd\pythonColor
  19928. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19929. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19930. return (f(v[0]), f(v[1]),)
  19931. def inc(x : any) -> any:
  19932. return inject((project(x, int) + 1), int)
  19933. def main() -> int:
  19934. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19935. print(t[1])
  19936. return 0
  19937. \end{lstlisting}
  19938. \fi}
  19939. \end{tcolorbox}
  19940. \caption{Output of \code{lower\_casts} on the example shown in
  19941. figure~\ref{fig:gradual-map}.}
  19942. \label{fig:map-lower-cast}
  19943. \end{figure}
  19944. \section{Differentiate Proxies}
  19945. \label{sec:differentiate-proxies}
  19946. So far, the responsibility of differentiating tuples and tuple proxies
  19947. has been the job of the interpreter.
  19948. %
  19949. \racket{For example, the interpreter for \LangCast{} implements
  19950. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19951. figure~\ref{fig:guarded-tuple}.}
  19952. %
  19953. In the \code{differentiate\_proxies} pass we shift this responsibility
  19954. to the generated code.
  19955. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19956. we used the type \TUPLETYPENAME{} for both
  19957. real tuples and tuple proxies.
  19958. \python{Similarly, we use the type \code{list} for both arrays and
  19959. array proxies.}
  19960. In \LangPVec{} we return the
  19961. \TUPLETYPENAME{} type to its original
  19962. meaning, as the type of just tuples, and we introduce a new type,
  19963. \PTUPLETYNAME{}, whose values
  19964. can be either real tuples or tuple
  19965. proxies.
  19966. %
  19967. {\if\edition\pythonEd\pythonColor
  19968. Likewise, we return the
  19969. \ARRAYTYPENAME{} type to its original
  19970. meaning, as the type of arrays, and we introduce a new type,
  19971. \PARRAYTYNAME{}, whose values
  19972. can be either arrays or array proxies.
  19973. These new types come with a suite of new primitive operations.
  19974. \fi}
  19975. {\if\edition\racketEd
  19976. A tuple proxy is represented by a tuple containing three things: (1) the
  19977. underlying tuple, (2) a tuple of functions for casting elements that
  19978. are read from the tuple, and (3) a tuple of functions for casting
  19979. values to be written to the tuple. So, we define the following
  19980. abbreviation for the type of a tuple proxy:
  19981. \[
  19982. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19983. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19984. \]
  19985. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19986. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19987. %
  19988. Next we describe each of the new primitive operations.
  19989. \begin{description}
  19990. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19991. (\key{PVector} $T \ldots$)]\ \\
  19992. %
  19993. This operation brands a vector as a value of the \code{PVector} type.
  19994. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19995. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19996. %
  19997. This operation brands a vector proxy as value of the \code{PVector} type.
  19998. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19999. \BOOLTY{}] \ \\
  20000. %
  20001. This returns true if the value is a tuple proxy and false if it is a
  20002. real tuple.
  20003. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20004. (\key{Vector} $T \ldots$)]\ \\
  20005. %
  20006. Assuming that the input is a tuple, this operation returns the
  20007. tuple.
  20008. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20009. $\to$ \BOOLTY{}]\ \\
  20010. %
  20011. Given a tuple proxy, this operation returns the length of the tuple.
  20012. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20013. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  20014. %
  20015. Given a tuple proxy, this operation returns the $i$th element of the
  20016. tuple.
  20017. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20018. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20019. Given a tuple proxy, this operation writes a value to the $i$th element
  20020. of the tuple.
  20021. \end{description}
  20022. \fi}
  20023. {\if\edition\pythonEd\pythonColor
  20024. %
  20025. A tuple proxy is represented by a tuple containing (1) the underlying
  20026. tuple and (2) a tuple of functions for casting elements that are read
  20027. from the tuple. The \LangPVec{} language includes the following AST
  20028. classes and primitive functions.
  20029. \begin{description}
  20030. \item[\code{InjectTuple}] \ \\
  20031. %
  20032. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20033. \item[\code{InjectTupleProxy}]\ \\
  20034. %
  20035. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20036. \item[\code{is\_tuple\_proxy}]\ \\
  20037. %
  20038. This primitive returns true if the value is a tuple proxy and false
  20039. if it is a tuple.
  20040. \item[\code{project\_tuple}]\ \\
  20041. %
  20042. Converts a tuple that is branded as \PTUPLETYNAME{}
  20043. back to a tuple.
  20044. \item[\code{proxy\_tuple\_len}]\ \\
  20045. %
  20046. Given a tuple proxy, returns the length of the underlying tuple.
  20047. \item[\code{proxy\_tuple\_load}]\ \\
  20048. %
  20049. Given a tuple proxy, returns the $i$th element of the underlying
  20050. tuple.
  20051. \end{description}
  20052. An array proxy is represented by a tuple containing (1) the underlying
  20053. array, (2) a function for casting elements that are read from the
  20054. array, and (3) a function for casting elements that are written to the
  20055. array. The \LangPVec{} language includes the following AST classes
  20056. and primitive functions.
  20057. \begin{description}
  20058. \item[\code{InjectList}]\ \\
  20059. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20060. \item[\code{InjectListProxy}]\ \\
  20061. %
  20062. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20063. \item[\code{is\_array\_proxy}]\ \\
  20064. %
  20065. Returns true if the value is an array proxy and false if it is an
  20066. array.
  20067. \item[\code{project\_array}]\ \\
  20068. %
  20069. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20070. array.
  20071. \item[\code{proxy\_array\_len}]\ \\
  20072. %
  20073. Given an array proxy, returns the length of the underlying array.
  20074. \item[\code{proxy\_array\_load}]\ \\
  20075. %
  20076. Given an array proxy, returns the $i$th element of the underlying
  20077. array.
  20078. \item[\code{proxy\_array\_store}]\ \\
  20079. %
  20080. Given an array proxy, writes a value to the $i$th element of the
  20081. underlying array.
  20082. \end{description}
  20083. \fi}
  20084. Now we discuss the translation that differentiates tuples and arrays
  20085. from proxies. First, every type annotation in the program is
  20086. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20087. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20088. places. For example, we wrap every tuple creation with an
  20089. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20090. %
  20091. {\if\edition\racketEd
  20092. \begin{minipage}{0.96\textwidth}
  20093. \begin{lstlisting}
  20094. (vector |$e_1 \ldots e_n$|)
  20095. |$\Rightarrow$|
  20096. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20097. \end{lstlisting}
  20098. \end{minipage}
  20099. \fi}
  20100. {\if\edition\pythonEd\pythonColor
  20101. \begin{lstlisting}
  20102. Tuple(|$e_1, \ldots, e_n$|)
  20103. |$\Rightarrow$|
  20104. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20105. \end{lstlisting}
  20106. \fi}
  20107. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20108. AST node that we introduced in the previous
  20109. section does not get injected.
  20110. {\if\edition\racketEd
  20111. \begin{lstlisting}
  20112. (raw-vector |$e_1 \ldots e_n$|)
  20113. |$\Rightarrow$|
  20114. (vector |$e'_1 \ldots e'_n$|)
  20115. \end{lstlisting}
  20116. \fi}
  20117. {\if\edition\pythonEd\pythonColor
  20118. \begin{lstlisting}
  20119. RawTuple(|$e_1, \ldots, e_n$|)
  20120. |$\Rightarrow$|
  20121. Tuple(|$e'_1, \ldots, e'_n$|)
  20122. \end{lstlisting}
  20123. \fi}
  20124. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20125. translates as follows:
  20126. %
  20127. {\if\edition\racketEd
  20128. \begin{lstlisting}
  20129. (vector-proxy |$e_1~e_2~e_3$|)
  20130. |$\Rightarrow$|
  20131. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20132. \end{lstlisting}
  20133. \fi}
  20134. {\if\edition\pythonEd\pythonColor
  20135. \begin{lstlisting}
  20136. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20137. |$\Rightarrow$|
  20138. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20139. \end{lstlisting}
  20140. \fi}
  20141. We translate the element access operations into conditional
  20142. expressions that check whether the value is a proxy and then dispatch
  20143. to either the appropriate proxy tuple operation or the regular tuple
  20144. operation.
  20145. {\if\edition\racketEd
  20146. \begin{lstlisting}
  20147. (vector-ref |$e_1$| |$i$|)
  20148. |$\Rightarrow$|
  20149. (let ([|$v~e_1$|])
  20150. (if (proxy? |$v$|)
  20151. (proxy-vector-ref |$v$| |$i$|)
  20152. (vector-ref (project-vector |$v$|) |$i$|)
  20153. \end{lstlisting}
  20154. \fi}
  20155. %
  20156. Note that in the branch for a tuple, we must apply
  20157. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20158. from the tuple.
  20159. The translation of array operations is similar to the ones for tuples.
  20160. \section{Reveal Casts}
  20161. \label{sec:reveal-casts-gradual}
  20162. {\if\edition\racketEd
  20163. Recall that the \code{reveal\_casts} pass
  20164. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20165. \code{Inject} and \code{Project} into lower-level operations.
  20166. %
  20167. In particular, \code{Project} turns into a conditional expression that
  20168. inspects the tag and retrieves the underlying value. Here we need to
  20169. augment the translation of \code{Project} to handle the situation in which
  20170. the target type is \code{PVector}. Instead of using
  20171. \code{vector-length} we need to use \code{proxy-vector-length}.
  20172. \begin{lstlisting}
  20173. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20174. |$\Rightarrow$|
  20175. (let |$\itm{tmp}$| |$e'$|
  20176. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20177. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20178. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20179. (exit)))
  20180. \end{lstlisting}
  20181. \fi}
  20182. %
  20183. {\if\edition\pythonEd\pythonColor
  20184. Recall that the $\itm{tagof}$ function determines the bits used to
  20185. identify values of different types, and it is used in the \code{reveal\_casts}
  20186. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20187. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  20188. decimal), just like the tuple and array types.
  20189. \fi}
  20190. %
  20191. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20192. \section{Closure Conversion}
  20193. \label{sec:closure-conversion-gradual}
  20194. The auxiliary function that translates type annotations needs to be
  20195. updated to handle the \PTUPLETYNAME{}
  20196. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20197. %
  20198. Otherwise, the only other changes are adding cases that copy the new
  20199. AST nodes.
  20200. \section{Select Instructions}
  20201. \label{sec:select-instructions-gradual}
  20202. \index{subject}{select instructions}
  20203. Recall that the \code{select\_instructions} pass is responsible for
  20204. lowering the primitive operations into x86 instructions. So, we need
  20205. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20206. to x86. To do so, the first question we need to answer is how to
  20207. differentiate between tuple and tuple proxies\python{, and likewise for
  20208. arrays and array proxies}. We need just one bit to accomplish this;
  20209. we use the bit in position $63$ of the 64-bit tag at the front of
  20210. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20211. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20212. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20213. it that way.
  20214. {\if\edition\racketEd
  20215. \begin{lstlisting}
  20216. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20217. |$\Rightarrow$|
  20218. movq |$e'_1$|, |$\itm{lhs'}$|
  20219. \end{lstlisting}
  20220. \fi}
  20221. {\if\edition\pythonEd\pythonColor
  20222. \begin{lstlisting}
  20223. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20224. |$\Rightarrow$|
  20225. movq |$e'_1$|, |$\itm{lhs'}$|
  20226. \end{lstlisting}
  20227. \fi}
  20228. \python{The translation for \code{InjectList} is also a move instruction.}
  20229. \noindent On the other hand,
  20230. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20231. $63$ to $1$.
  20232. %
  20233. {\if\edition\racketEd
  20234. \begin{lstlisting}
  20235. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20236. |$\Rightarrow$|
  20237. movq |$e'_1$|, %r11
  20238. movq |$(1 << 63)$|, %rax
  20239. orq 0(%r11), %rax
  20240. movq %rax, 0(%r11)
  20241. movq %r11, |$\itm{lhs'}$|
  20242. \end{lstlisting}
  20243. \fi}
  20244. {\if\edition\pythonEd\pythonColor
  20245. \begin{lstlisting}
  20246. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20247. |$\Rightarrow$|
  20248. movq |$e'_1$|, %r11
  20249. movq |$(1 << 63)$|, %rax
  20250. orq 0(%r11), %rax
  20251. movq %rax, 0(%r11)
  20252. movq %r11, |$\itm{lhs'}$|
  20253. \end{lstlisting}
  20254. \fi}
  20255. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20256. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20257. The \racket{\code{proxy?} operation consumes}%
  20258. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20259. consume}
  20260. the information so carefully stashed away by the injections. It
  20261. isolates bit $63$ to tell whether the value is a proxy.
  20262. %
  20263. {\if\edition\racketEd
  20264. \begin{lstlisting}
  20265. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20266. |$\Rightarrow$|
  20267. movq |$e_1'$|, %r11
  20268. movq 0(%r11), %rax
  20269. sarq $63, %rax
  20270. andq $1, %rax
  20271. movq %rax, |$\itm{lhs'}$|
  20272. \end{lstlisting}
  20273. \fi}%
  20274. %
  20275. {\if\edition\pythonEd\pythonColor
  20276. \begin{lstlisting}
  20277. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20278. |$\Rightarrow$|
  20279. movq |$e_1'$|, %r11
  20280. movq 0(%r11), %rax
  20281. sarq $63, %rax
  20282. andq $1, %rax
  20283. movq %rax, |$\itm{lhs'}$|
  20284. \end{lstlisting}
  20285. \fi}%
  20286. %
  20287. The \racket{\code{project-vector} operation is}
  20288. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20289. straightforward to translate, so we leave that to the reader.
  20290. Regarding the element access operations for tuples\python{ and arrays}, the
  20291. runtime provides procedures that implement them (they are recursive
  20292. functions!), so here we simply need to translate these tuple
  20293. operations into the appropriate function call. For example, here is
  20294. the translation for
  20295. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20296. {\if\edition\racketEd
  20297. \begin{minipage}{0.96\textwidth}
  20298. \begin{lstlisting}
  20299. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20300. |$\Rightarrow$|
  20301. movq |$e_1'$|, %rdi
  20302. movq |$e_2'$|, %rsi
  20303. callq proxy_vector_ref
  20304. movq %rax, |$\itm{lhs'}$|
  20305. \end{lstlisting}
  20306. \end{minipage}
  20307. \fi}
  20308. {\if\edition\pythonEd\pythonColor
  20309. \begin{lstlisting}
  20310. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20311. |$\Rightarrow$|
  20312. movq |$e_1'$|, %rdi
  20313. movq |$e_2'$|, %rsi
  20314. callq proxy_vector_ref
  20315. movq %rax, |$\itm{lhs'}$|
  20316. \end{lstlisting}
  20317. \fi}
  20318. {\if\edition\pythonEd\pythonColor
  20319. % TODO: revisit the names vecof for python -Jeremy
  20320. We translate
  20321. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20322. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20323. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20324. \fi}
  20325. We have another batch of operations to deal with: those for the
  20326. \CANYTY{} type. Recall that we generate an
  20327. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20328. there is a element access on something of type \CANYTY{}, and
  20329. similarly for
  20330. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20331. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20332. section~\ref{sec:select-Lany} we selected instructions for these
  20333. operations on the basis of the idea that the underlying value was a tuple or
  20334. array. But in the current setting, the underlying value is of type
  20335. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20336. functions to deal with this:
  20337. \code{proxy\_vector\_ref},
  20338. \code{proxy\_vector\_set}, and
  20339. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20340. to determine whether the value is a proxy, and then
  20341. dispatches to the the appropriate code.
  20342. %
  20343. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20344. can be translated as follows.
  20345. We begin by projecting the underlying value out of the tagged value and
  20346. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20347. {\if\edition\racketEd
  20348. \begin{lstlisting}
  20349. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20350. |$\Rightarrow$|
  20351. movq |$\neg 111$|, %rdi
  20352. andq |$e_1'$|, %rdi
  20353. movq |$e_2'$|, %rsi
  20354. callq proxy_vector_ref
  20355. movq %rax, |$\itm{lhs'}$|
  20356. \end{lstlisting}
  20357. \fi}
  20358. {\if\edition\pythonEd\pythonColor
  20359. \begin{lstlisting}
  20360. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20361. |$\Rightarrow$|
  20362. movq |$\neg 111$|, %rdi
  20363. andq |$e_1'$|, %rdi
  20364. movq |$e_2'$|, %rsi
  20365. callq proxy_vector_ref
  20366. movq %rax, |$\itm{lhs'}$|
  20367. \end{lstlisting}
  20368. \fi}
  20369. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20370. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20371. are translated in a similar way. Alternatively, you could generate
  20372. instructions to open-code
  20373. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20374. and \code{proxy\_vector\_length} functions.
  20375. \begin{exercise}\normalfont\normalsize
  20376. Implement a compiler for the gradually typed \LangGrad{} language by
  20377. extending and adapting your compiler for \LangLam{}. Create ten new
  20378. partially typed test programs. In addition to testing with these
  20379. new programs, test your compiler on all the tests for \LangLam{}
  20380. and for \LangDyn{}.
  20381. %
  20382. \racket{Sometimes you may get a type-checking error on the
  20383. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20384. the \CANYTY{} type around each subexpression that has caused a type
  20385. error. Although \LangDyn{} does not have explicit casts, you can
  20386. induce one by wrapping the subexpression \code{e} with a call to
  20387. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20388. %
  20389. \python{Sometimes you may get a type-checking error on the
  20390. \LangDyn{} programs, but you can adapt them by inserting a
  20391. temporary variable of type \CANYTY{} that is initialized with the
  20392. troublesome expression.}
  20393. \end{exercise}
  20394. \begin{figure}[t]
  20395. \begin{tcolorbox}[colback=white]
  20396. {\if\edition\racketEd
  20397. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20398. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20399. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20400. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20401. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20402. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20403. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20404. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20405. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20406. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20407. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20408. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20409. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20410. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20411. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20412. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20413. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20414. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20415. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20416. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20417. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20418. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20419. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20420. \path[->,bend left=15] (Lgradual) edge [above] node
  20421. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20422. \path[->,bend left=15] (Lgradual2) edge [above] node
  20423. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20424. \path[->,bend left=15] (Lgradual3) edge [above] node
  20425. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20426. \path[->,bend left=15] (Lgradual4) edge [left] node
  20427. {\ttfamily\footnotesize shrink} (Lgradualr);
  20428. \path[->,bend left=15] (Lgradualr) edge [above] node
  20429. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20430. \path[->,bend right=15] (Lgradualp) edge [above] node
  20431. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20432. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20433. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20434. \path[->,bend right=15] (Llambdapp) edge [above] node
  20435. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20436. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20437. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20438. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20439. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20440. \path[->,bend left=15] (F1-2) edge [above] node
  20441. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20442. \path[->,bend left=15] (F1-3) edge [left] node
  20443. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20444. \path[->,bend left=15] (F1-4) edge [below] node
  20445. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20446. \path[->,bend right=15] (F1-5) edge [above] node
  20447. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20448. \path[->,bend right=15] (F1-6) edge [above] node
  20449. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20450. \path[->,bend right=15] (C3-2) edge [right] node
  20451. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20452. \path[->,bend right=15] (x86-2) edge [right] node
  20453. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20454. \path[->,bend right=15] (x86-2-1) edge [below] node
  20455. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20456. \path[->,bend right=15] (x86-2-2) edge [right] node
  20457. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20458. \path[->,bend left=15] (x86-3) edge [above] node
  20459. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20460. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20461. \end{tikzpicture}
  20462. \fi}
  20463. {\if\edition\pythonEd\pythonColor
  20464. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20465. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20466. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20467. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20468. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20469. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20470. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20471. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20472. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20473. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20474. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20475. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20476. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20477. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20478. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20479. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20480. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20481. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20482. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20483. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20484. \path[->,bend left=15] (Lgradual) edge [above] node
  20485. {\ttfamily\footnotesize shrink} (Lgradual2);
  20486. \path[->,bend left=15] (Lgradual2) edge [above] node
  20487. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20488. \path[->,bend left=15] (Lgradual3) edge [above] node
  20489. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20490. \path[->,bend left=15] (Lgradual4) edge [left] node
  20491. {\ttfamily\footnotesize resolve} (Lgradualr);
  20492. \path[->,bend left=15] (Lgradualr) edge [below] node
  20493. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20494. \path[->,bend right=15] (Lgradualp) edge [above] node
  20495. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20496. \path[->,bend right=15] (Llambdapp) edge [above] node
  20497. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20498. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20499. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20500. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20501. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20502. \path[->,bend left=15] (F1-1) edge [above] node
  20503. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20504. \path[->,bend left=15] (F1-2) edge [above] node
  20505. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20506. \path[->,bend left=15] (F1-3) edge [right] node
  20507. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20508. \path[->,bend right=15] (F1-5) edge [above] node
  20509. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20510. \path[->,bend right=15] (F1-6) edge [above] node
  20511. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20512. \path[->,bend right=15] (C3-2) edge [right] node
  20513. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20514. \path[->,bend right=15] (x86-2) edge [below] node
  20515. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20516. \path[->,bend right=15] (x86-3) edge [below] node
  20517. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20518. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20519. \end{tikzpicture}
  20520. \fi}
  20521. \end{tcolorbox}
  20522. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20523. \label{fig:Lgradual-passes}
  20524. \end{figure}
  20525. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20526. needed for the compilation of \LangGrad{}.
  20527. \section{Further Reading}
  20528. This chapter just scratches the surface of gradual typing. The basic
  20529. approach described here is missing two key ingredients that one would
  20530. want in a implementation of gradual typing: blame
  20531. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20532. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20533. problem addressed by blame tracking is that when a cast on a
  20534. higher-order value fails, it often does so at a point in the program
  20535. that is far removed from the original cast. Blame tracking is a
  20536. technique for propagating extra information through casts and proxies
  20537. so that when a cast fails, the error message can point back to the
  20538. original location of the cast in the source program.
  20539. The problem addressed by space-efficient casts also relates to
  20540. higher-order casts. It turns out that in partially typed programs, a
  20541. function or tuple can flow through a great many casts at runtime. With
  20542. the approach described in this chapter, each cast adds another
  20543. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20544. considerable space, but it also makes the function calls and tuple
  20545. operations slow. For example, a partially typed version of quicksort
  20546. could, in the worst case, build a chain of proxies of length $O(n)$
  20547. around the tuple, changing the overall time complexity of the
  20548. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20549. solution to this problem by representing casts using the coercion
  20550. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20551. long chains of proxies by compressing them into a concise normal
  20552. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20553. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20554. the Grift compiler:
  20555. \begin{center}
  20556. \url{https://github.com/Gradual-Typing/Grift}
  20557. \end{center}
  20558. There are also interesting interactions between gradual typing and
  20559. other language features, such as generics, information-flow types, and
  20560. type inference, to name a few. We recommend to the reader the
  20561. online gradual typing bibliography for more material:
  20562. \begin{center}
  20563. \url{http://samth.github.io/gradual-typing-bib/}
  20564. \end{center}
  20565. % TODO: challenge problem:
  20566. % type analysis and type specialization?
  20567. % coercions?
  20568. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20569. \chapter{Generics}
  20570. \label{ch:Lpoly}
  20571. \setcounter{footnote}{0}
  20572. This chapter studies the compilation of
  20573. generics\index{subject}{generics} (aka parametric
  20574. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20575. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20576. enable programmers to make code more reusable by parameterizing
  20577. functions and data structures with respect to the types on which they
  20578. operate. For example, figure~\ref{fig:map-poly} revisits the
  20579. \code{map} example and this time gives it a more fitting type. This
  20580. \code{map} function is parameterized with respect to the element type
  20581. of the tuple. The type of \code{map} is the following generic type
  20582. specified by the \code{All} type with parameter \code{T}:
  20583. {\if\edition\racketEd
  20584. \begin{lstlisting}
  20585. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20586. \end{lstlisting}
  20587. \fi}
  20588. {\if\edition\pythonEd\pythonColor
  20589. \begin{lstlisting}
  20590. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20591. \end{lstlisting}
  20592. \fi}
  20593. %
  20594. The idea is that \code{map} can be used at \emph{all} choices of a
  20595. type for parameter \code{T}. In the example shown in
  20596. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20597. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20598. \code{T}, but we could have just as well applied \code{map} to a tuple
  20599. of Booleans.
  20600. %
  20601. A \emph{monomorphic} function is simply one that is not generic.
  20602. %
  20603. We use the term \emph{instantiation} for the process (within the
  20604. language implementation) of turning a generic function into a
  20605. monomorphic one, where the type parameters have been replaced by
  20606. types.
  20607. {\if\edition\pythonEd\pythonColor
  20608. %
  20609. In Python, when writing a generic function such as \code{map}, one
  20610. does not explicitly write its generic type (using \code{All}).
  20611. Instead, that the function is generic is implied by the use of type
  20612. variables (such as \code{T}) in the type annotations of its
  20613. parameters.
  20614. %
  20615. \fi}
  20616. \begin{figure}[tbp]
  20617. % poly_test_2.rkt
  20618. \begin{tcolorbox}[colback=white]
  20619. {\if\edition\racketEd
  20620. \begin{lstlisting}
  20621. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20622. (define (map f v)
  20623. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20624. (define (inc [x : Integer]) : Integer (+ x 1))
  20625. (vector-ref (map inc (vector 0 41)) 1)
  20626. \end{lstlisting}
  20627. \fi}
  20628. {\if\edition\pythonEd\pythonColor
  20629. \begin{lstlisting}
  20630. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20631. return (f(tup[0]), f(tup[1]))
  20632. def add1(x : int) -> int:
  20633. return x + 1
  20634. t = map(add1, (0, 41))
  20635. print(t[1])
  20636. \end{lstlisting}
  20637. \fi}
  20638. \end{tcolorbox}
  20639. \caption{A generic version of the \code{map} function.}
  20640. \label{fig:map-poly}
  20641. \end{figure}
  20642. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20643. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20644. shows the definition of the abstract syntax.
  20645. %
  20646. {\if\edition\racketEd
  20647. We add a second form for function definitions in which a type
  20648. declaration comes before the \code{define}. In the abstract syntax,
  20649. the return type in the \code{Def} is \CANYTY{}, but that should be
  20650. ignored in favor of the return type in the type declaration. (The
  20651. \CANYTY{} comes from using the same parser as discussed in
  20652. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20653. enables the use of an \code{All} type for a function, thereby making
  20654. it generic.
  20655. \fi}
  20656. %
  20657. The grammar for types is extended to include the type of a generic
  20658. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20659. abstract syntax)}.
  20660. \newcommand{\LpolyGrammarRacket}{
  20661. \begin{array}{lcl}
  20662. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20663. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20664. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20665. \end{array}
  20666. }
  20667. \newcommand{\LpolyASTRacket}{
  20668. \begin{array}{lcl}
  20669. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20670. \Def &::=& \DECL{\Var}{\Type} \\
  20671. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20672. \end{array}
  20673. }
  20674. \newcommand{\LpolyGrammarPython}{
  20675. \begin{array}{lcl}
  20676. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20677. \end{array}
  20678. }
  20679. \newcommand{\LpolyASTPython}{
  20680. \begin{array}{lcl}
  20681. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20682. \MID \key{GenericVar}\LP\Var\RP
  20683. \end{array}
  20684. }
  20685. \begin{figure}[tp]
  20686. \centering
  20687. \begin{tcolorbox}[colback=white]
  20688. \footnotesize
  20689. {\if\edition\racketEd
  20690. \[
  20691. \begin{array}{l}
  20692. \gray{\LintGrammarRacket{}} \\ \hline
  20693. \gray{\LvarGrammarRacket{}} \\ \hline
  20694. \gray{\LifGrammarRacket{}} \\ \hline
  20695. \gray{\LwhileGrammarRacket} \\ \hline
  20696. \gray{\LtupGrammarRacket} \\ \hline
  20697. \gray{\LfunGrammarRacket} \\ \hline
  20698. \gray{\LlambdaGrammarRacket} \\ \hline
  20699. \LpolyGrammarRacket \\
  20700. \begin{array}{lcl}
  20701. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20702. \end{array}
  20703. \end{array}
  20704. \]
  20705. \fi}
  20706. {\if\edition\pythonEd\pythonColor
  20707. \[
  20708. \begin{array}{l}
  20709. \gray{\LintGrammarPython{}} \\ \hline
  20710. \gray{\LvarGrammarPython{}} \\ \hline
  20711. \gray{\LifGrammarPython{}} \\ \hline
  20712. \gray{\LwhileGrammarPython} \\ \hline
  20713. \gray{\LtupGrammarPython} \\ \hline
  20714. \gray{\LfunGrammarPython} \\ \hline
  20715. \gray{\LlambdaGrammarPython} \\\hline
  20716. \LpolyGrammarPython \\
  20717. \begin{array}{lcl}
  20718. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20719. \end{array}
  20720. \end{array}
  20721. \]
  20722. \fi}
  20723. \end{tcolorbox}
  20724. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20725. (figure~\ref{fig:Llam-concrete-syntax}).}
  20726. \label{fig:Lpoly-concrete-syntax}
  20727. \end{figure}
  20728. \begin{figure}[tp]
  20729. \centering
  20730. \begin{tcolorbox}[colback=white]
  20731. \footnotesize
  20732. {\if\edition\racketEd
  20733. \[
  20734. \begin{array}{l}
  20735. \gray{\LintOpAST} \\ \hline
  20736. \gray{\LvarASTRacket{}} \\ \hline
  20737. \gray{\LifASTRacket{}} \\ \hline
  20738. \gray{\LwhileASTRacket{}} \\ \hline
  20739. \gray{\LtupASTRacket{}} \\ \hline
  20740. \gray{\LfunASTRacket} \\ \hline
  20741. \gray{\LlambdaASTRacket} \\ \hline
  20742. \LpolyASTRacket \\
  20743. \begin{array}{lcl}
  20744. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20745. \end{array}
  20746. \end{array}
  20747. \]
  20748. \fi}
  20749. {\if\edition\pythonEd\pythonColor
  20750. \[
  20751. \begin{array}{l}
  20752. \gray{\LintASTPython} \\ \hline
  20753. \gray{\LvarASTPython{}} \\ \hline
  20754. \gray{\LifASTPython{}} \\ \hline
  20755. \gray{\LwhileASTPython{}} \\ \hline
  20756. \gray{\LtupASTPython{}} \\ \hline
  20757. \gray{\LfunASTPython} \\ \hline
  20758. \gray{\LlambdaASTPython} \\ \hline
  20759. \LpolyASTPython \\
  20760. \begin{array}{lcl}
  20761. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20762. \end{array}
  20763. \end{array}
  20764. \]
  20765. \fi}
  20766. \end{tcolorbox}
  20767. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20768. (figure~\ref{fig:Llam-syntax}).}
  20769. \label{fig:Lpoly-syntax}
  20770. \end{figure}
  20771. By including the \code{All} type in the $\Type$ nonterminal of the
  20772. grammar we choose to make generics first class, which has interesting
  20773. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20774. not include syntax for the \code{All} type. It is inferred for functions whose
  20775. type annotations contain type variables.} Many languages with generics, such as
  20776. C++~\citep{stroustrup88:_param_types} and Standard
  20777. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20778. may be helpful to see an example of first-class generics in action. In
  20779. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20780. whose parameter is a generic function. Indeed, because the grammar for
  20781. $\Type$ includes the \code{All} type, a generic function may also be
  20782. returned from a function or stored inside a tuple. The body of
  20783. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20784. and also to an integer, which would not be possible if \code{f} were
  20785. not generic.
  20786. \begin{figure}[tbp]
  20787. \begin{tcolorbox}[colback=white]
  20788. {\if\edition\racketEd
  20789. \begin{lstlisting}
  20790. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20791. (define (apply_twice f)
  20792. (if (f #t) (f 42) (f 777)))
  20793. (: id (All (T) (T -> T)))
  20794. (define (id x) x)
  20795. (apply_twice id)
  20796. \end{lstlisting}
  20797. \fi}
  20798. {\if\edition\pythonEd\pythonColor
  20799. \begin{lstlisting}
  20800. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20801. if f(True):
  20802. return f(42)
  20803. else:
  20804. return f(777)
  20805. def id(x: T) -> T:
  20806. return x
  20807. print(apply_twice(id))
  20808. \end{lstlisting}
  20809. \fi}
  20810. \end{tcolorbox}
  20811. \caption{An example illustrating first-class generics.}
  20812. \label{fig:apply-twice}
  20813. \end{figure}
  20814. The type checker for \LangPoly{} shown in
  20815. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20816. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20817. {\if\edition\pythonEd\pythonColor
  20818. %
  20819. Regarding function definitions, if the type annotations on its
  20820. parameters contain generic variables, then the function is generic and
  20821. therefore its type is an \code{All} type wrapped around a function
  20822. type. Otherwise the function is monomorphic and its type is simply
  20823. a function type.
  20824. %
  20825. \fi}
  20826. The type checking of a function application is extended to handle the
  20827. case in which the operator expression is a generic function. In that case
  20828. the type arguments are deduced by matching the types of the parameters
  20829. with the types of the arguments.
  20830. %
  20831. The \code{match\_types} auxiliary function
  20832. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20833. recursively descending through a parameter type \code{param\_ty} and
  20834. the corresponding argument type \code{arg\_ty}, making sure that they
  20835. are equal except when there is a type parameter in the parameter
  20836. type. Upon encountering a type parameter for the first time, the
  20837. algorithm deduces an association of the type parameter to the
  20838. corresponding part of the argument type. If it is not the first time
  20839. that the type parameter has been encountered, the algorithm looks up
  20840. its deduced type and makes sure that it is equal to the corresponding
  20841. part of the argument type. The return type of the application is the
  20842. return type of the generic function with the type parameters
  20843. replaced by the deduced type arguments, using the
  20844. \code{substitute\_type} auxiliary function, which is also listed in
  20845. figure~\ref{fig:type-check-Lpoly-aux}.
  20846. The type checker extends type equality to handle the \code{All} type.
  20847. This is not quite as simple as for other types, such as function and
  20848. tuple types, because two \code{All} types can be syntactically
  20849. different even though they are equivalent. For example,
  20850. \begin{center}
  20851. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20852. \end{center}
  20853. is equivalent to
  20854. \begin{center}
  20855. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20856. \end{center}
  20857. Two generic types are equal if they differ only in
  20858. the choice of the names of the type parameters. The definition of type
  20859. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20860. parameters in one type to match the type parameters of the other type.
  20861. {\if\edition\racketEd
  20862. %
  20863. The type checker also ensures that only defined type variables appear
  20864. in type annotations. The \code{check\_well\_formed} function for which
  20865. the definition is shown in figure~\ref{fig:well-formed-types}
  20866. recursively inspects a type, making sure that each type variable has
  20867. been defined.
  20868. %
  20869. \fi}
  20870. \begin{figure}[tbp]
  20871. \begin{tcolorbox}[colback=white]
  20872. {\if\edition\racketEd
  20873. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20874. (define type-check-poly-class
  20875. (class type-check-Llambda-class
  20876. (super-new)
  20877. (inherit check-type-equal?)
  20878. (define/override (type-check-apply env e1 es)
  20879. (define-values (e^ ty) ((type-check-exp env) e1))
  20880. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20881. ((type-check-exp env) e)))
  20882. (match ty
  20883. [`(,ty^* ... -> ,rt)
  20884. (for ([arg-ty ty*] [param-ty ty^*])
  20885. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20886. (values e^ es^ rt)]
  20887. [`(All ,xs (,tys ... -> ,rt))
  20888. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20889. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20890. (match_types env^^ param-ty arg-ty)))
  20891. (define targs
  20892. (for/list ([x xs])
  20893. (match (dict-ref env^^ x (lambda () #f))
  20894. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20895. x (Apply e1 es))]
  20896. [ty ty])))
  20897. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20898. [else (error 'type-check "expected a function, not ~a" ty)]))
  20899. (define/override ((type-check-exp env) e)
  20900. (match e
  20901. [(Lambda `([,xs : ,Ts] ...) rT body)
  20902. (for ([T Ts]) ((check_well_formed env) T))
  20903. ((check_well_formed env) rT)
  20904. ((super type-check-exp env) e)]
  20905. [(HasType e1 ty)
  20906. ((check_well_formed env) ty)
  20907. ((super type-check-exp env) e)]
  20908. [else ((super type-check-exp env) e)]))
  20909. (define/override ((type-check-def env) d)
  20910. (verbose 'type-check "poly/def" d)
  20911. (match d
  20912. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20913. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20914. (for ([p ps]) ((check_well_formed ts-env) p))
  20915. ((check_well_formed ts-env) rt)
  20916. (define new-env (append ts-env (map cons xs ps) env))
  20917. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20918. (check-type-equal? ty^ rt body)
  20919. (Generic ts (Def f p:t* rt info body^))]
  20920. [else ((super type-check-def env) d)]))
  20921. (define/override (type-check-program p)
  20922. (match p
  20923. [(Program info body)
  20924. (type-check-program (ProgramDefsExp info '() body))]
  20925. [(ProgramDefsExp info ds body)
  20926. (define ds^ (combine-decls-defs ds))
  20927. (define new-env (for/list ([d ds^])
  20928. (cons (def-name d) (fun-def-type d))))
  20929. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20930. (define-values (body^ ty) ((type-check-exp new-env) body))
  20931. (check-type-equal? ty 'Integer body)
  20932. (ProgramDefsExp info ds^^ body^)]))
  20933. ))
  20934. \end{lstlisting}
  20935. \fi}
  20936. {\if\edition\pythonEd\pythonColor
  20937. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20938. def type_check_exp(self, e, env):
  20939. match e:
  20940. case Call(Name(f), args) if f in builtin_functions:
  20941. return super().type_check_exp(e, env)
  20942. case Call(func, args):
  20943. func_t = self.type_check_exp(func, env)
  20944. func.has_type = func_t
  20945. match func_t:
  20946. case AllType(ps, FunctionType(p_tys, rt)):
  20947. for arg in args:
  20948. arg.has_type = self.type_check_exp(arg, env)
  20949. arg_tys = [arg.has_type for arg in args]
  20950. deduced = {}
  20951. for (p, a) in zip(p_tys, arg_tys):
  20952. self.match_types(p, a, deduced, e)
  20953. return self.substitute_type(rt, deduced)
  20954. case _:
  20955. return super().type_check_exp(e, env)
  20956. case _:
  20957. return super().type_check_exp(e, env)
  20958. def type_check(self, p):
  20959. match p:
  20960. case Module(body):
  20961. env = {}
  20962. for s in body:
  20963. match s:
  20964. case FunctionDef(name, params, bod, dl, returns, comment):
  20965. params_t = [t for (x,t) in params]
  20966. ty_params = set()
  20967. for t in params_t:
  20968. ty_params |$\mid$|= self.generic_variables(t)
  20969. ty = FunctionType(params_t, returns)
  20970. if len(ty_params) > 0:
  20971. ty = AllType(list(ty_params), ty)
  20972. env[name] = ty
  20973. self.check_stmts(body, IntType(), env)
  20974. case _:
  20975. raise Exception('type_check: unexpected ' + repr(p))
  20976. \end{lstlisting}
  20977. \fi}
  20978. \end{tcolorbox}
  20979. \caption{Type checker for the \LangPoly{} language.}
  20980. \label{fig:type-check-Lpoly}
  20981. \end{figure}
  20982. \begin{figure}[tbp]
  20983. \begin{tcolorbox}[colback=white]
  20984. {\if\edition\racketEd
  20985. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20986. (define/override (type-equal? t1 t2)
  20987. (match* (t1 t2)
  20988. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20989. (define env (map cons xs ys))
  20990. (type-equal? (substitute_type env T1) T2)]
  20991. [(other wise)
  20992. (super type-equal? t1 t2)]))
  20993. (define/public (match_types env pt at)
  20994. (match* (pt at)
  20995. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20996. [('Void 'Void) env] [('Any 'Any) env]
  20997. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20998. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20999. (match_types env^ pt1 at1))]
  21000. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21001. (define env^ (match_types env prt art))
  21002. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21003. (match_types env^^ pt1 at1))]
  21004. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21005. (define env^ (append (map cons pxs axs) env))
  21006. (match_types env^ pt1 at1)]
  21007. [((? symbol? x) at)
  21008. (match (dict-ref env x (lambda () #f))
  21009. [#f (error 'type-check "undefined type variable ~a" x)]
  21010. ['Type (cons (cons x at) env)]
  21011. [t^ (check-type-equal? at t^ 'matching) env])]
  21012. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21013. (define/public (substitute_type env pt)
  21014. (match pt
  21015. ['Integer 'Integer] ['Boolean 'Boolean]
  21016. ['Void 'Void] ['Any 'Any]
  21017. [`(Vector ,ts ...)
  21018. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21019. [`(,ts ... -> ,rt)
  21020. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21021. [`(All ,xs ,t)
  21022. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21023. [(? symbol? x) (dict-ref env x)]
  21024. [else (error 'type-check "expected a type not ~a" pt)]))
  21025. (define/public (combine-decls-defs ds)
  21026. (match ds
  21027. ['() '()]
  21028. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21029. (unless (equal? name f)
  21030. (error 'type-check "name mismatch, ~a != ~a" name f))
  21031. (match type
  21032. [`(All ,xs (,ps ... -> ,rt))
  21033. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21034. (cons (Generic xs (Def name params^ rt info body))
  21035. (combine-decls-defs ds^))]
  21036. [`(,ps ... -> ,rt)
  21037. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21038. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21039. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21040. [`(,(Def f params rt info body) . ,ds^)
  21041. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21042. \end{lstlisting}
  21043. \fi}
  21044. {\if\edition\pythonEd\pythonColor
  21045. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21046. def match_types(self, param_ty, arg_ty, deduced, e):
  21047. match (param_ty, arg_ty):
  21048. case (GenericVar(id), _):
  21049. if id in deduced:
  21050. self.check_type_equal(arg_ty, deduced[id], e)
  21051. else:
  21052. deduced[id] = arg_ty
  21053. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21054. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21055. new_arg_ty = self.substitute_type(arg_ty, rename)
  21056. self.match_types(ty, new_arg_ty, deduced, e)
  21057. case (TupleType(ps), TupleType(ts)):
  21058. for (p, a) in zip(ps, ts):
  21059. self.match_types(p, a, deduced, e)
  21060. case (ListType(p), ListType(a)):
  21061. self.match_types(p, a, deduced, e)
  21062. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21063. for (pp, ap) in zip(pps, aps):
  21064. self.match_types(pp, ap, deduced, e)
  21065. self.match_types(prt, art, deduced, e)
  21066. case (IntType(), IntType()):
  21067. pass
  21068. case (BoolType(), BoolType()):
  21069. pass
  21070. case _:
  21071. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21072. def substitute_type(self, ty, var_map):
  21073. match ty:
  21074. case GenericVar(id):
  21075. return var_map[id]
  21076. case AllType(ps, ty):
  21077. new_map = copy.deepcopy(var_map)
  21078. for p in ps:
  21079. new_map[p] = GenericVar(p)
  21080. return AllType(ps, self.substitute_type(ty, new_map))
  21081. case TupleType(ts):
  21082. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21083. case ListType(ty):
  21084. return ListType(self.substitute_type(ty, var_map))
  21085. case FunctionType(pts, rt):
  21086. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21087. self.substitute_type(rt, var_map))
  21088. case IntType():
  21089. return IntType()
  21090. case BoolType():
  21091. return BoolType()
  21092. case _:
  21093. raise Exception('substitute_type: unexpected ' + repr(ty))
  21094. def check_type_equal(self, t1, t2, e):
  21095. match (t1, t2):
  21096. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21097. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21098. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21099. case (_, _):
  21100. return super().check_type_equal(t1, t2, e)
  21101. \end{lstlisting}
  21102. \fi}
  21103. \end{tcolorbox}
  21104. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21105. \label{fig:type-check-Lpoly-aux}
  21106. \end{figure}
  21107. {\if\edition\racketEd
  21108. \begin{figure}[tbp]
  21109. \begin{tcolorbox}[colback=white]
  21110. \begin{lstlisting}
  21111. (define/public ((check_well_formed env) ty)
  21112. (match ty
  21113. ['Integer (void)]
  21114. ['Boolean (void)]
  21115. ['Void (void)]
  21116. [(? symbol? a)
  21117. (match (dict-ref env a (lambda () #f))
  21118. ['Type (void)]
  21119. [else (error 'type-check "undefined type variable ~a" a)])]
  21120. [`(Vector ,ts ...)
  21121. (for ([t ts]) ((check_well_formed env) t))]
  21122. [`(,ts ... -> ,t)
  21123. (for ([t ts]) ((check_well_formed env) t))
  21124. ((check_well_formed env) t)]
  21125. [`(All ,xs ,t)
  21126. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21127. ((check_well_formed env^) t)]
  21128. [else (error 'type-check "unrecognized type ~a" ty)]))
  21129. \end{lstlisting}
  21130. \end{tcolorbox}
  21131. \caption{Well-formed types.}
  21132. \label{fig:well-formed-types}
  21133. \end{figure}
  21134. \fi}
  21135. % TODO: interpreter for R'_10
  21136. \clearpage
  21137. \section{Compiling Generics}
  21138. \label{sec:compiling-poly}
  21139. Broadly speaking, there are four approaches to compiling generics, as
  21140. follows:
  21141. \begin{description}
  21142. \item[Monomorphization] generates a different version of a generic
  21143. function for each set of type arguments with which it is used,
  21144. producing type-specialized code. This approach results in the most
  21145. efficient code but requires whole-program compilation (no separate
  21146. compilation) and may increase code size. Unfortunately,
  21147. monomorphization is incompatible with first-class generics because
  21148. it is not always possible to determine which generic functions are
  21149. used with which type arguments during compilation. (It can be done
  21150. at runtime with just-in-time compilation.) Monomorphization is
  21151. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21152. generic functions in NESL~\citep{Blelloch:1993aa} and
  21153. ML~\citep{Weeks:2006aa}.
  21154. \item[Uniform representation] generates one version of each generic
  21155. function and requires all values to have a common \emph{boxed} format,
  21156. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21157. generic and monomorphic code is compiled similarly to code in a
  21158. dynamically typed language (like \LangDyn{}), in which primitive
  21159. operators require their arguments to be projected from \CANYTY{} and
  21160. their results to be injected into \CANYTY{}. (In object-oriented
  21161. languages, the projection is accomplished via virtual method
  21162. dispatch.) The uniform representation approach is compatible with
  21163. separate compilation and with first-class generics. However, it
  21164. produces the least efficient code because it introduces overhead in
  21165. the entire program. This approach is used in
  21166. Java~\citep{Bracha:1998fk},
  21167. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21168. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21169. \item[Mixed representation] generates one version of each generic
  21170. function, using a boxed representation for type variables. However,
  21171. monomorphic code is compiled as usual (as in \LangLam{}), and
  21172. conversions are performed at the boundaries between monomorphic code
  21173. and polymorphic code (for example, when a generic function is instantiated
  21174. and called). This approach is compatible with separate compilation
  21175. and first-class generics and maintains efficiency in monomorphic
  21176. code. The trade-off is increased overhead at the boundary between
  21177. monomorphic and generic code. This approach is used in
  21178. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21179. Java 5 with the addition of autoboxing.
  21180. \item[Type passing] uses the unboxed representation in both
  21181. monomorphic and generic code. Each generic function is compiled to a
  21182. single function with extra parameters that describe the type
  21183. arguments. The type information is used by the generated code to
  21184. determine how to access the unboxed values at runtime. This approach is
  21185. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21186. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21187. compilation and first-class generics and maintains the
  21188. efficiency for monomorphic code. There is runtime overhead in
  21189. polymorphic code from dispatching on type information.
  21190. \end{description}
  21191. In this chapter we use the mixed representation approach, partly
  21192. because of its favorable attributes and partly because it is
  21193. straightforward to implement using the tools that we have already
  21194. built to support gradual typing. The work of compiling generic
  21195. functions is performed in two passes, \code{resolve} and
  21196. \code{erase\_types}, that we discuss next. The output of
  21197. \code{erase\_types} is \LangCast{}
  21198. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21199. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21200. \section{Resolve Instantiation}
  21201. \label{sec:generic-resolve}
  21202. Recall that the type checker for \LangPoly{} deduces the type
  21203. arguments at call sites to a generic function. The purpose of the
  21204. \code{resolve} pass is to turn this implicit instantiation into an
  21205. explicit one, by adding \code{inst} nodes to the syntax of the
  21206. intermediate language. An \code{inst} node records the mapping of
  21207. type parameters to type arguments. The semantics of the \code{inst}
  21208. node is to instantiate the result of its first argument, a generic
  21209. function, to produce a monomorphic function. However, because the
  21210. interpreter never analyzes type annotations, instantiation can be a
  21211. no-op and simply return the generic function.
  21212. %
  21213. The output language of the \code{resolve} pass is \LangInst{},
  21214. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21215. {\if\edition\racketEd
  21216. The \code{resolve} pass combines the type declaration and polymorphic
  21217. function into a single definition, using the \code{Poly} form, to make
  21218. polymorphic functions more convenient to process in the next pass of the
  21219. compiler.
  21220. \fi}
  21221. \newcommand{\LinstASTRacket}{
  21222. \begin{array}{lcl}
  21223. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21224. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21225. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21226. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21227. \end{array}
  21228. }
  21229. \newcommand{\LinstASTPython}{
  21230. \begin{array}{lcl}
  21231. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21232. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21233. \end{array}
  21234. }
  21235. \begin{figure}[tp]
  21236. \centering
  21237. \begin{tcolorbox}[colback=white]
  21238. \small
  21239. {\if\edition\racketEd
  21240. \[
  21241. \begin{array}{l}
  21242. \gray{\LintOpAST} \\ \hline
  21243. \gray{\LvarASTRacket{}} \\ \hline
  21244. \gray{\LifASTRacket{}} \\ \hline
  21245. \gray{\LwhileASTRacket{}} \\ \hline
  21246. \gray{\LtupASTRacket{}} \\ \hline
  21247. \gray{\LfunASTRacket} \\ \hline
  21248. \gray{\LlambdaASTRacket} \\ \hline
  21249. \LinstASTRacket \\
  21250. \begin{array}{lcl}
  21251. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21252. \end{array}
  21253. \end{array}
  21254. \]
  21255. \fi}
  21256. {\if\edition\pythonEd\pythonColor
  21257. \[
  21258. \begin{array}{l}
  21259. \gray{\LintASTPython} \\ \hline
  21260. \gray{\LvarASTPython{}} \\ \hline
  21261. \gray{\LifASTPython{}} \\ \hline
  21262. \gray{\LwhileASTPython{}} \\ \hline
  21263. \gray{\LtupASTPython{}} \\ \hline
  21264. \gray{\LfunASTPython} \\ \hline
  21265. \gray{\LlambdaASTPython} \\ \hline
  21266. \LinstASTPython \\
  21267. \begin{array}{lcl}
  21268. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21269. \end{array}
  21270. \end{array}
  21271. \]
  21272. \fi}
  21273. \end{tcolorbox}
  21274. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21275. (figure~\ref{fig:Llam-syntax}).}
  21276. \label{fig:Lpoly-prime-syntax}
  21277. \end{figure}
  21278. The output of the \code{resolve} pass on the generic \code{map}
  21279. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21280. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21281. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21282. \begin{figure}[tbp]
  21283. % poly_test_2.rkt
  21284. \begin{tcolorbox}[colback=white]
  21285. {\if\edition\racketEd
  21286. \begin{lstlisting}
  21287. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21288. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21289. (define (inc [x : Integer]) : Integer (+ x 1))
  21290. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21291. (Integer))
  21292. inc (vector 0 41)) 1)
  21293. \end{lstlisting}
  21294. \fi}
  21295. {\if\edition\pythonEd\pythonColor
  21296. \begin{lstlisting}
  21297. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21298. return (f(tup[0]), f(tup[1]))
  21299. def add1(x : int) -> int:
  21300. return x + 1
  21301. t = inst(map, {T: int})(add1, (0, 41))
  21302. print(t[1])
  21303. \end{lstlisting}
  21304. \fi}
  21305. \end{tcolorbox}
  21306. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21307. \label{fig:map-resolve}
  21308. \end{figure}
  21309. \section{Erase Generic Types}
  21310. \label{sec:erase_types}
  21311. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21312. represent type variables. For example, figure~\ref{fig:map-erase}
  21313. shows the output of the \code{erase\_types} pass on the generic
  21314. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21315. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21316. \code{All} types are removed from the type of \code{map}.
  21317. \begin{figure}[tbp]
  21318. \begin{tcolorbox}[colback=white]
  21319. {\if\edition\racketEd
  21320. \begin{lstlisting}
  21321. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21322. : (Vector Any Any)
  21323. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21324. (define (inc [x : Integer]) : Integer (+ x 1))
  21325. (vector-ref ((cast map
  21326. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21327. ((Integer -> Integer) (Vector Integer Integer)
  21328. -> (Vector Integer Integer)))
  21329. inc (vector 0 41)) 1)
  21330. \end{lstlisting}
  21331. \fi}
  21332. {\if\edition\pythonEd\pythonColor
  21333. \begin{lstlisting}
  21334. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21335. return (f(tup[0]), f(tup[1]))
  21336. def add1(x : int) -> int:
  21337. return (x + 1)
  21338. def main() -> int:
  21339. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21340. print(t[1])
  21341. return 0
  21342. \end{lstlisting}
  21343. {\small
  21344. where\\
  21345. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21346. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21347. }
  21348. \fi}
  21349. \end{tcolorbox}
  21350. \caption{The generic \code{map} example after type erasure.}
  21351. \label{fig:map-erase}
  21352. \end{figure}
  21353. This process of type erasure creates a challenge at points of
  21354. instantiation. For example, consider the instantiation of
  21355. \code{map} shown in figure~\ref{fig:map-resolve}.
  21356. The type of \code{map} is
  21357. %
  21358. {\if\edition\racketEd
  21359. \begin{lstlisting}
  21360. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21361. \end{lstlisting}
  21362. \fi}
  21363. {\if\edition\pythonEd\pythonColor
  21364. \begin{lstlisting}
  21365. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21366. \end{lstlisting}
  21367. \fi}
  21368. %
  21369. and it is instantiated to
  21370. %
  21371. {\if\edition\racketEd
  21372. \begin{lstlisting}
  21373. ((Integer -> Integer) (Vector Integer Integer)
  21374. -> (Vector Integer Integer))
  21375. \end{lstlisting}
  21376. \fi}
  21377. {\if\edition\pythonEd\pythonColor
  21378. \begin{lstlisting}
  21379. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21380. \end{lstlisting}
  21381. \fi}
  21382. %
  21383. After erasure, the type of \code{map} is
  21384. %
  21385. {\if\edition\racketEd
  21386. \begin{lstlisting}
  21387. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21388. \end{lstlisting}
  21389. \fi}
  21390. {\if\edition\pythonEd\pythonColor
  21391. \begin{lstlisting}
  21392. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21393. \end{lstlisting}
  21394. \fi}
  21395. %
  21396. but we need to convert it to the instantiated type. This is easy to
  21397. do in the language \LangCast{} with a single \code{cast}. In the
  21398. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21399. \code{map} has been compiled to a \code{cast} from the type of
  21400. \code{map} to the instantiated type. The source and the target type of a
  21401. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21402. the case because both the source and target are obtained from the same
  21403. generic type of \code{map}, replacing the type parameters with
  21404. \CANYTY{} in the former and with the deduced type arguments in the
  21405. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21406. To implement the \code{erase\_types} pass, we first recommend defining
  21407. a recursive function that translates types, named
  21408. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21409. follows.
  21410. %
  21411. {\if\edition\racketEd
  21412. \begin{lstlisting}
  21413. |$T$|
  21414. |$\Rightarrow$|
  21415. Any
  21416. \end{lstlisting}
  21417. \fi}
  21418. {\if\edition\pythonEd\pythonColor
  21419. \begin{lstlisting}
  21420. GenericVar(|$T$|)
  21421. |$\Rightarrow$|
  21422. Any
  21423. \end{lstlisting}
  21424. \fi}
  21425. %
  21426. \noindent The \code{erase\_type} function also removes the generic
  21427. \code{All} types.
  21428. %
  21429. {\if\edition\racketEd
  21430. \begin{lstlisting}
  21431. (All |$xs$| |$T_1$|)
  21432. |$\Rightarrow$|
  21433. |$T'_1$|
  21434. \end{lstlisting}
  21435. \fi}
  21436. {\if\edition\pythonEd\pythonColor
  21437. \begin{lstlisting}
  21438. AllType(|$xs$|, |$T_1$|)
  21439. |$\Rightarrow$|
  21440. |$T'_1$|
  21441. \end{lstlisting}
  21442. \fi}
  21443. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21444. %
  21445. In this compiler pass, apply the \code{erase\_type} function to all
  21446. the type annotations in the program.
  21447. Regarding the translation of expressions, the case for \code{Inst} is
  21448. the interesting one. We translate it into a \code{Cast}, as shown
  21449. next.
  21450. The type of the subexpression $e$ is a generic type of the form
  21451. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21452. The source type of the cast is the erasure of $T$, the type $T_s$.
  21453. %
  21454. {\if\edition\racketEd
  21455. %
  21456. The target type $T_t$ is the result of substituting the argument types
  21457. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21458. erasure.
  21459. %
  21460. \begin{lstlisting}
  21461. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21462. |$\Rightarrow$|
  21463. (Cast |$e'$| |$T_s$| |$T_t$|)
  21464. \end{lstlisting}
  21465. %
  21466. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21467. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21468. \fi}
  21469. {\if\edition\pythonEd\pythonColor
  21470. %
  21471. The target type $T_t$ is the result of substituting the deduced
  21472. argument types $d$ in $T$ and then performing type erasure.
  21473. %
  21474. \begin{lstlisting}
  21475. Inst(|$e$|, |$d$|)
  21476. |$\Rightarrow$|
  21477. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21478. \end{lstlisting}
  21479. %
  21480. where
  21481. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21482. \fi}
  21483. Finally, each generic function is translated to a regular
  21484. function in which type erasure has been applied to all the type
  21485. annotations and the body.
  21486. %% \begin{lstlisting}
  21487. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21488. %% |$\Rightarrow$|
  21489. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21490. %% \end{lstlisting}
  21491. \begin{exercise}\normalfont\normalsize
  21492. Implement a compiler for the polymorphic language \LangPoly{} by
  21493. extending and adapting your compiler for \LangGrad{}. Create six new
  21494. test programs that use polymorphic functions. Some of them should
  21495. make use of first-class generics.
  21496. \end{exercise}
  21497. \begin{figure}[tbp]
  21498. \begin{tcolorbox}[colback=white]
  21499. {\if\edition\racketEd
  21500. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21501. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21502. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21503. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21504. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21505. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21506. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21507. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21508. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21509. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21510. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21511. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21512. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21513. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21514. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21515. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21516. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21517. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21518. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21519. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21520. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21521. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21522. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21523. \path[->,bend left=15] (Lpoly) edge [above] node
  21524. {\ttfamily\footnotesize resolve} (Lpolyp);
  21525. \path[->,bend left=15] (Lpolyp) edge [above] node
  21526. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21527. \path[->,bend left=15] (Lgradualp) edge [above] node
  21528. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21529. \path[->,bend left=15] (Llambdapp) edge [left] node
  21530. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21531. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21532. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21533. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21534. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21535. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21536. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21537. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21538. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21539. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21540. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21541. \path[->,bend left=15] (F1-1) edge [above] node
  21542. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21543. \path[->,bend left=15] (F1-2) edge [above] node
  21544. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21545. \path[->,bend left=15] (F1-3) edge [left] node
  21546. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21547. \path[->,bend left=15] (F1-4) edge [below] node
  21548. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21549. \path[->,bend right=15] (F1-5) edge [above] node
  21550. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21551. \path[->,bend right=15] (F1-6) edge [above] node
  21552. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21553. \path[->,bend right=15] (C3-2) edge [right] node
  21554. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21555. \path[->,bend right=15] (x86-2) edge [right] node
  21556. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21557. \path[->,bend right=15] (x86-2-1) edge [below] node
  21558. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21559. \path[->,bend right=15] (x86-2-2) edge [right] node
  21560. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21561. \path[->,bend left=15] (x86-3) edge [above] node
  21562. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21563. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21564. \end{tikzpicture}
  21565. \fi}
  21566. {\if\edition\pythonEd\pythonColor
  21567. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21568. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21569. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21570. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21571. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21572. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21573. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21574. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21575. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21576. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21577. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21578. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21579. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21580. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21581. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21582. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21583. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21584. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21585. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21586. \path[->,bend left=15] (Lgradual) edge [above] node
  21587. {\ttfamily\footnotesize shrink} (Lgradual2);
  21588. \path[->,bend left=15] (Lgradual2) edge [above] node
  21589. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21590. \path[->,bend left=15] (Lgradual3) edge [above] node
  21591. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21592. \path[->,bend left=15] (Lgradual4) edge [left] node
  21593. {\ttfamily\footnotesize resolve} (Lgradualr);
  21594. \path[->,bend left=15] (Lgradualr) edge [below] node
  21595. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21596. \path[->,bend right=15] (Llambdapp) edge [above] node
  21597. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21598. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21599. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21600. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21601. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21602. \path[->,bend right=15] (F1-1) edge [below] node
  21603. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21604. \path[->,bend right=15] (F1-2) edge [below] node
  21605. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21606. \path[->,bend left=15] (F1-3) edge [above] node
  21607. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21608. \path[->,bend left=15] (F1-5) edge [left] node
  21609. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21610. \path[->,bend left=5] (F1-6) edge [below] node
  21611. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21612. \path[->,bend right=15] (C3-2) edge [right] node
  21613. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21614. \path[->,bend right=15] (x86-2) edge [below] node
  21615. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21616. \path[->,bend right=15] (x86-3) edge [below] node
  21617. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21618. \path[->,bend left=15] (x86-4) edge [above] node
  21619. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21620. \end{tikzpicture}
  21621. \fi}
  21622. \end{tcolorbox}
  21623. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21624. \label{fig:Lpoly-passes}
  21625. \end{figure}
  21626. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21627. needed to compile \LangPoly{}.
  21628. % TODO: challenge problem: specialization of instantiations
  21629. % Further Reading
  21630. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21631. \clearpage
  21632. \appendix
  21633. \chapter{Appendix}
  21634. \setcounter{footnote}{0}
  21635. {\if\edition\racketEd
  21636. \section{Interpreters}
  21637. \label{appendix:interp}
  21638. \index{subject}{interpreter}
  21639. We provide interpreters for each of the source languages \LangInt{},
  21640. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21641. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21642. intermediate languages \LangCVar{} and \LangCIf{} are in
  21643. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21644. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21645. \key{interp.rkt} file.
  21646. \section{Utility Functions}
  21647. \label{appendix:utilities}
  21648. The utility functions described in this section are in the
  21649. \key{utilities.rkt} file of the support code.
  21650. \paragraph{\code{interp-tests}}
  21651. This function runs the compiler passes and the interpreters on each of
  21652. the specified tests to check whether each pass is correct. The
  21653. \key{interp-tests} function has the following parameters:
  21654. \begin{description}
  21655. \item[name (a string)] A name to identify the compiler.
  21656. \item[typechecker] A function of exactly one argument that either
  21657. raises an error using the \code{error} function when it encounters a
  21658. type error, or returns \code{\#f} when it encounters a type
  21659. error. If there is no type error, the type checker returns the
  21660. program.
  21661. \item[passes] A list with one entry per pass. An entry is a list
  21662. consisting of four things:
  21663. \begin{enumerate}
  21664. \item a string giving the name of the pass;
  21665. \item the function that implements the pass (a translator from AST
  21666. to AST);
  21667. \item a function that implements the interpreter (a function from
  21668. AST to result value) for the output language; and,
  21669. \item a type checker for the output language. Type checkers for
  21670. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21671. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21672. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21673. type checker entry is optional. The support code does not provide
  21674. type checkers for the x86 languages.
  21675. \end{enumerate}
  21676. \item[source-interp] An interpreter for the source language. The
  21677. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21678. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21679. \item[tests] A list of test numbers that specifies which tests to
  21680. run (explained next).
  21681. \end{description}
  21682. %
  21683. The \key{interp-tests} function assumes that the subdirectory
  21684. \key{tests} has a collection of Racket programs whose names all start
  21685. with the family name, followed by an underscore and then the test
  21686. number, and ending with the file extension \key{.rkt}. Also, for each test
  21687. program that calls \code{read} one or more times, there is a file with
  21688. the same name except that the file extension is \key{.in}, which
  21689. provides the input for the Racket program. If the test program is
  21690. expected to fail type checking, then there should be an empty file of
  21691. the same name with extension \key{.tyerr}.
  21692. \paragraph{\code{compiler-tests}}
  21693. This function runs the compiler passes to generate x86 (a \key{.s}
  21694. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21695. It runs the machine code and checks that the output is $42$. The
  21696. parameters to the \code{compiler-tests} function are similar to those
  21697. of the \code{interp-tests} function, and they consist of
  21698. \begin{itemize}
  21699. \item a compiler name (a string),
  21700. \item a type checker,
  21701. \item description of the passes,
  21702. \item name of a test-family, and
  21703. \item a list of test numbers.
  21704. \end{itemize}
  21705. \paragraph{\code{compile-file}}
  21706. This function takes a description of the compiler passes (see the
  21707. comment for \key{interp-tests}) and returns a function that, given a
  21708. program file name (a string ending in \key{.rkt}), applies all the
  21709. passes and writes the output to a file whose name is the same as the
  21710. program file name with extension \key{.rkt} replaced by \key{.s}.
  21711. \paragraph{\code{read-program}}
  21712. This function takes a file path and parses that file (it must be a
  21713. Racket program) into an abstract syntax tree.
  21714. \paragraph{\code{parse-program}}
  21715. This function takes an S-expression representation of an abstract
  21716. syntax tree and converts it into the struct-based representation.
  21717. \paragraph{\code{assert}}
  21718. This function takes two parameters, a string (\code{msg}) and Boolean
  21719. (\code{bool}), and displays the message \key{msg} if the Boolean
  21720. \key{bool} is false.
  21721. \paragraph{\code{lookup}}
  21722. % remove discussion of lookup? -Jeremy
  21723. This function takes a key and an alist and returns the first value that is
  21724. associated with the given key, if there is one. If not, an error is
  21725. triggered. The alist may contain both immutable pairs (built with
  21726. \key{cons}) and mutable pairs (built with \key{mcons}).
  21727. %The \key{map2} function ...
  21728. \fi} %\racketEd
  21729. \section{x86 Instruction Set Quick Reference}
  21730. \label{sec:x86-quick-reference}
  21731. \index{subject}{x86}
  21732. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21733. do. We write $A \to B$ to mean that the value of $A$ is written into
  21734. location $B$. Address offsets are given in bytes. The instruction
  21735. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21736. registers (such as \code{\%rax}), or memory references (such as
  21737. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21738. reference per instruction. Other operands must be immediates or
  21739. registers.
  21740. \begin{table}[tbp]
  21741. \centering
  21742. \begin{tabular}{l|l}
  21743. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21744. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21745. \texttt{negq} $A$ & $- A \to A$ \\
  21746. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21747. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21748. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21749. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21750. \texttt{retq} & Pops the return address and jumps to it. \\
  21751. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21752. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21753. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21754. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21755. be an immediate). \\
  21756. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21757. matches the condition code of the instruction; otherwise go to the
  21758. next instructions. The condition codes are \key{e} for \emph{equal},
  21759. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21760. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21761. \texttt{jl} $L$ & \\
  21762. \texttt{jle} $L$ & \\
  21763. \texttt{jg} $L$ & \\
  21764. \texttt{jge} $L$ & \\
  21765. \texttt{jmp} $L$ & Jump to label $L$. \\
  21766. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21767. \texttt{movzbq} $A$, $B$ &
  21768. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21769. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21770. and the extra bytes of $B$ are set to zero.} \\
  21771. & \\
  21772. & \\
  21773. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21774. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21775. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21776. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21777. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21778. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21779. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21780. description of the condition codes. $A$ must be a single byte register
  21781. (e.g., \texttt{al} or \texttt{cl}).} \\
  21782. \texttt{setl} $A$ & \\
  21783. \texttt{setle} $A$ & \\
  21784. \texttt{setg} $A$ & \\
  21785. \texttt{setge} $A$ &
  21786. \end{tabular}
  21787. \vspace{5pt}
  21788. \caption{Quick reference for the x86 instructions used in this book.}
  21789. \label{tab:x86-instr}
  21790. \end{table}
  21791. \backmatter
  21792. \addtocontents{toc}{\vspace{11pt}}
  21793. \cleardoublepage % needed for right page number in TOC for References
  21794. %% \nocite{*} is a way to get all the entries in the .bib file to
  21795. %% print in the bibliography:
  21796. \nocite{*}\let\bibname\refname
  21797. \addcontentsline{toc}{fmbm}{\refname}
  21798. \printbibliography
  21799. %\printindex{authors}{Author Index}
  21800. \printindex{subject}{Index}
  21801. \end{document}
  21802. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21803. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21804. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21805. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21806. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21807. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21808. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21809. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21810. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21811. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21812. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21813. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21814. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21815. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21816. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21817. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21818. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21819. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21820. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21821. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21822. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21823. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21824. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21825. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21826. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21827. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21828. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21829. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21830. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21831. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21832. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21833. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21834. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21835. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21836. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21837. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21838. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21839. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21840. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21841. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21842. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21843. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21844. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21845. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21846. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21847. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21848. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21849. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21850. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21851. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21852. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21853. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21854. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21855. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21856. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21857. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21858. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21859. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21860. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21861. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21862. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21863. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21864. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21865. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21866. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21867. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21868. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21869. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21870. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21871. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21872. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21873. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21874. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21875. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21876. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21877. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21878. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21879. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21880. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21881. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21882. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21883. % LocalWords: pseudocode underapproximation underapproximations LALR
  21884. % LocalWords: semilattices overapproximate incrementing Earley docs
  21885. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21886. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21887. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21888. % LocalWords: LC partialevaluation pythonEd TOC TrappedError