book.tex 830 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840
  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. \makeatletter
  35. \newcommand{\captionabove}[2][]{%
  36. \vskip-\abovecaptionskip
  37. \vskip+\belowcaptionskip
  38. \ifx\@nnil#1\@nnil
  39. \caption{#2}%
  40. \else
  41. \caption[#1]{#2}%
  42. \fi
  43. \vskip+\abovecaptionskip
  44. \vskip-\belowcaptionskip
  45. }
  46. %% For multiple indices:
  47. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  48. \makeindex{subject}
  49. %\makeindex{authors}
  50. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  51. \if\edition\racketEd
  52. \lstset{%
  53. language=Lisp,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  56. deletekeywords={read,mapping,vector},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. \if\edition\pythonEd
  64. \lstset{%
  65. language=Python,
  66. basicstyle=\ttfamily\small,
  67. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  68. deletekeywords={},
  69. escapechar=|,
  70. columns=flexible,
  71. %moredelim=[is][\color{red}]{~}{~},
  72. showstringspaces=false
  73. }
  74. \fi
  75. %%% Any shortcut own defined macros place here
  76. %% sample of author macro:
  77. \input{defs}
  78. \newtheorem{exercise}[theorem]{Exercise}
  79. \numberwithin{theorem}{chapter}
  80. \numberwithin{definition}{chapter}
  81. \numberwithin{equation}{chapter}
  82. % Adjusted settings
  83. \setlength{\columnsep}{4pt}
  84. %% \begingroup
  85. %% \setlength{\intextsep}{0pt}%
  86. %% \setlength{\columnsep}{0pt}%
  87. %% \begin{wrapfigure}{r}{0.5\textwidth}
  88. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  89. %% \caption{Basic layout}
  90. %% \end{wrapfigure}
  91. %% \lipsum[1]
  92. %% \endgroup
  93. \newbox\oiintbox
  94. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  95. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  96. \def\oiint{\copy\oiintbox}
  97. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  98. %\usepackage{showframe}
  99. \def\ShowFrameLinethickness{0.125pt}
  100. \addbibresource{book.bib}
  101. \if\edition\pythonEd
  102. \addbibresource{python.bib}
  103. \fi
  104. \begin{document}
  105. \frontmatter
  106. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  107. \HalfTitle{Essentials of Compilation}
  108. \halftitlepage
  109. \clearemptydoublepage
  110. \Title{Essentials of Compilation}
  111. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  112. %\edition{First Edition}
  113. \BookAuthor{Jeremy G. Siek}
  114. \imprint{The MIT Press\\
  115. Cambridge, Massachusetts\\
  116. London, England}
  117. \begin{copyrightpage}
  118. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  119. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  120. Subject to such license, all rights are reserved. \\[2ex]
  121. \includegraphics{CCBY-logo}
  122. The MIT Press would like to thank the anonymous peer reviewers who
  123. provided comments on drafts of this book. The generous work of
  124. academic experts is essential for establishing the authority and
  125. quality of our publications. We acknowledge with gratitude the
  126. contributions of these otherwise uncredited readers.
  127. This book was set in Times LT Std Roman by the author. Printed and
  128. bound in the United States of America.
  129. {\if\edition\racketEd
  130. Library of Congress Cataloging-in-Publication Data\\
  131. \ \\
  132. Names: Siek, Jeremy, author. \\
  133. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  134. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  135. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  136. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  137. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  138. LC record available at https://lccn.loc.gov/2022015399\\
  139. LC ebook record available at https://lccn.loc.gov/2022015400\\
  140. \ \\
  141. \fi}
  142. %
  143. {\if\edition\pythonEd
  144. Library of Congress Cataloging-in-Publication Data\\
  145. \ \\
  146. Names: Jeremy G. Siek. \\
  147. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  148. bibliographical references and index. \\
  149. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  150. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  151. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  152. language) | Programming languages (Electronic computers) | Computer
  153. programming. \\
  154. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  155. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  156. LC record available at https://lccn.loc.gov/2022043053\\
  157. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  158. \ \\
  159. \fi}
  160. 10 9 8 7 6 5 4 3 2 1
  161. %% Jeremy G. Siek. Available for free viewing
  162. %% or personal downloading under the
  163. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  164. %% license.
  165. %% Copyright in this monograph has been licensed exclusively to The MIT
  166. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  167. %% version to the public in 2022. All inquiries regarding rights should
  168. %% be addressed to The MIT Press, Rights and Permissions Department.
  169. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  170. %% All rights reserved. No part of this book may be reproduced in any
  171. %% form by any electronic or mechanical means (including photocopying,
  172. %% recording, or information storage and retrieval) without permission in
  173. %% writing from the publisher.
  174. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  175. %% United States of America.
  176. %% Library of Congress Cataloging-in-Publication Data is available.
  177. %% ISBN:
  178. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  179. \end{copyrightpage}
  180. \dedication{This book is dedicated to Katie, my partner in everything,
  181. my children, who grew up during the writing of this book, and the
  182. programming language students at Indiana University, whose
  183. thoughtful questions made this a better book.}
  184. %% \begin{epigraphpage}
  185. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  186. %% \textit{Book Name if any}}
  187. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  188. %% \end{epigraphpage}
  189. \tableofcontents
  190. %\listoffigures
  191. %\listoftables
  192. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  193. \chapter*{Preface}
  194. \addcontentsline{toc}{fmbm}{Preface}
  195. There is a magical moment when a programmer presses the \emph{run}
  196. button and the software begins to execute. Somehow a program written
  197. in a high-level language is running on a computer that is capable only
  198. of shuffling bits. Here we reveal the wizardry that makes that moment
  199. possible. Beginning with the groundbreaking work of Backus and
  200. colleagues in the 1950s, computer scientists developed techniques for
  201. constructing programs called \emph{compilers} that automatically
  202. translate high-level programs into machine code.
  203. We take you on a journey through constructing your own compiler for a
  204. small but powerful language. Along the way we explain the essential
  205. concepts, algorithms, and data structures that underlie compilers. We
  206. develop your understanding of how programs are mapped onto computer
  207. hardware, which is helpful in reasoning about properties at the
  208. junction of hardware and software, such as execution time, software
  209. errors, and security vulnerabilities. For those interested in
  210. pursuing compiler construction as a career, our goal is to provide a
  211. stepping-stone to advanced topics such as just-in-time compilation,
  212. program analysis, and program optimization. For those interested in
  213. designing and implementing programming languages, we connect language
  214. design choices to their impact on the compiler and the generated code.
  215. A compiler is typically organized as a sequence of stages that
  216. progressively translate a program to the code that runs on
  217. hardware. We take this approach to the extreme by partitioning our
  218. compiler into a large number of \emph{nanopasses}, each of which
  219. performs a single task. This enables the testing of each pass in
  220. isolation and focuses our attention, making the compiler far easier to
  221. understand.
  222. The most familiar approach to describing compilers is to dedicate each
  223. chapter to one pass. The problem with that approach is that it
  224. obfuscates how language features motivate design choices in a
  225. compiler. We instead take an \emph{incremental} approach in which we
  226. build a complete compiler in each chapter, starting with a small input
  227. language that includes only arithmetic and variables. We add new
  228. language features in subsequent chapters, extending the compiler as
  229. necessary.
  230. Our choice of language features is designed to elicit fundamental
  231. concepts and algorithms used in compilers.
  232. \begin{itemize}
  233. \item We begin with integer arithmetic and local variables in
  234. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  235. the fundamental tools of compiler construction: \emph{abstract
  236. syntax trees} and \emph{recursive functions}.
  237. {\if\edition\pythonEd\pythonColor
  238. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  239. parser framework to create a parser for the language of integer
  240. arithmetic and local variables. We learn about the parsing
  241. algorithms inside Lark, including Earley and LALR(1).
  242. %
  243. \fi}
  244. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  245. \emph{graph coloring} to assign variables to machine registers.
  246. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  247. motivates an elegant recursive algorithm for translating them into
  248. conditional \code{goto} statements.
  249. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  250. variables}. This elicits the need for \emph{dataflow
  251. analysis} in the register allocator.
  252. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  253. \emph{garbage collection}.
  254. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  255. without lexical scoping, similar to functions in the C programming
  256. language~\citep{Kernighan:1988nx}. The reader learns about the
  257. procedure call stack and \emph{calling conventions} and how they interact
  258. with register allocation and garbage collection. The chapter also
  259. describes how to generate efficient tail calls.
  260. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  261. scoping, that is, \emph{lambda} expressions. The reader learns about
  262. \emph{closure conversion}, in which lambdas are translated into a
  263. combination of functions and tuples.
  264. % Chapter about classes and objects?
  265. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  266. point the input languages are statically typed. The reader extends
  267. the statically typed language with an \code{Any} type that serves
  268. as a target for compiling the dynamically typed language.
  269. %% {\if\edition\pythonEd\pythonColor
  270. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  271. %% \emph{classes}.
  272. %% \fi}
  273. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  274. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  275. in which different regions of a program may be static or dynamically
  276. typed. The reader implements runtime support for \emph{proxies} that
  277. allow values to safely move between regions.
  278. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  279. leveraging the \code{Any} type and type casts developed in chapters
  280. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  281. \end{itemize}
  282. There are many language features that we do not include. Our choices
  283. balance the incidental complexity of a feature versus the fundamental
  284. concepts that it exposes. For example, we include tuples and not
  285. records because although they both elicit the study of heap allocation and
  286. garbage collection, records come with more incidental complexity.
  287. Since 2009, drafts of this book have served as the textbook for
  288. sixteen-week compiler courses for upper-level undergraduates and
  289. first-year graduate students at the University of Colorado and Indiana
  290. University.
  291. %
  292. Students come into the course having learned the basics of
  293. programming, data structures and algorithms, and discrete
  294. mathematics.
  295. %
  296. At the beginning of the course, students form groups of two to four
  297. people. The groups complete approximately one chapter every two
  298. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  299. according to the students interests while respecting the dependencies
  300. between chapters shown in
  301. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  302. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  303. implementation of efficient tail calls.
  304. %
  305. The last two weeks of the course involve a final project in which
  306. students design and implement a compiler extension of their choosing.
  307. The last few chapters can be used in support of these projects. Many
  308. chapters include a challenge problem that we assign to the graduate
  309. students.
  310. For compiler courses at universities on the quarter system
  311. (about ten weeks in length), we recommend completing the course
  312. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  313. some scaffolding code to the students for each compiler pass.
  314. %
  315. The course can be adapted to emphasize functional languages by
  316. skipping chapter~\ref{ch:Lwhile} (loops) and including
  317. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  318. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  319. %
  320. %% \python{A course that emphasizes object-oriented languages would
  321. %% include Chapter~\ref{ch:Lobject}.}
  322. This book has been used in compiler courses at California Polytechnic
  323. State University, Portland State University, Rose–Hulman Institute of
  324. Technology, University of Freiburg, University of Massachusetts
  325. Lowell, and the University of Vermont.
  326. \begin{figure}[tp]
  327. \begin{tcolorbox}[colback=white]
  328. {\if\edition\racketEd
  329. \begin{tikzpicture}[baseline=(current bounding box.center)]
  330. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  331. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  332. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  333. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  334. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  335. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  336. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  337. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  338. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  339. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  340. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  341. \path[->] (C1) edge [above] node {} (C2);
  342. \path[->] (C2) edge [above] node {} (C3);
  343. \path[->] (C3) edge [above] node {} (C4);
  344. \path[->] (C4) edge [above] node {} (C5);
  345. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  346. \path[->] (C5) edge [above] node {} (C7);
  347. \path[->] (C6) edge [above] node {} (C7);
  348. \path[->] (C4) edge [above] node {} (C8);
  349. \path[->] (C4) edge [above] node {} (C9);
  350. \path[->] (C7) edge [above] node {} (C10);
  351. \path[->] (C8) edge [above] node {} (C10);
  352. \path[->] (C10) edge [above] node {} (C11);
  353. \end{tikzpicture}
  354. \fi}
  355. {\if\edition\pythonEd\pythonColor
  356. \begin{tikzpicture}[baseline=(current bounding box.center)]
  357. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  358. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  359. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  360. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  361. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  362. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  363. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  364. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  365. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  366. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  367. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  368. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  369. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  370. \path[->] (Prelim) edge [above] node {} (Var);
  371. \path[->] (Var) edge [above] node {} (Reg);
  372. \path[->] (Var) edge [above] node {} (Parse);
  373. \path[->] (Reg) edge [above] node {} (Cond);
  374. \path[->] (Cond) edge [above] node {} (Tuple);
  375. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  376. \path[->] (Cond) edge [above] node {} (Fun);
  377. \path[->] (Tuple) edge [above] node {} (Lam);
  378. \path[->] (Fun) edge [above] node {} (Lam);
  379. \path[->] (Cond) edge [above] node {} (Dyn);
  380. \path[->] (Cond) edge [above] node {} (Loop);
  381. \path[->] (Lam) edge [above] node {} (Gradual);
  382. \path[->] (Dyn) edge [above] node {} (Gradual);
  383. % \path[->] (Dyn) edge [above] node {} (CO);
  384. \path[->] (Gradual) edge [above] node {} (Generic);
  385. \end{tikzpicture}
  386. \fi}
  387. \end{tcolorbox}
  388. \caption{Diagram of chapter dependencies.}
  389. \label{fig:chapter-dependences}
  390. \end{figure}
  391. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  392. the implementation of the compiler and for the input language, so the
  393. reader should be proficient with Racket or Scheme. There are many
  394. excellent resources for learning Scheme and
  395. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  396. %
  397. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  398. both for the implementation of the compiler and for the input language, so the
  399. reader should be proficient with Python. There are many
  400. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  401. %
  402. The support code for this book is in the GitHub repository at
  403. the following location:
  404. \begin{center}\small\texttt
  405. https://github.com/IUCompilerCourse/
  406. \end{center}
  407. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  408. is helpful but not necessary for the reader to have taken a computer
  409. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  410. assembly language that are needed in the compiler.
  411. %
  412. We follow the System V calling
  413. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  414. that we generate works with the runtime system (written in C) when it
  415. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  416. operating systems on Intel hardware.
  417. %
  418. On the Windows operating system, \code{gcc} uses the Microsoft x64
  419. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  420. assembly code that we generate does \emph{not} work with the runtime
  421. system on Windows. One workaround is to use a virtual machine with
  422. Linux as the guest operating system.
  423. \section*{Acknowledgments}
  424. The tradition of compiler construction at Indiana University goes back
  425. to research and courses on programming languages by Daniel Friedman in
  426. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  427. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  428. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  429. the compiler course and continued the development of Chez Scheme.
  430. %
  431. The compiler course evolved to incorporate novel pedagogical ideas
  432. while also including elements of real-world compilers. One of
  433. Friedman's ideas was to split the compiler into many small
  434. passes. Another idea, called ``the game,'' was to test the code
  435. generated by each pass using interpreters.
  436. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  437. developed infrastructure to support this approach and evolved the
  438. course to use even smaller
  439. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  440. design decisions in this book are inspired by the assignment
  441. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  442. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  443. organization of the course made it difficult for students to
  444. understand the rationale for the compiler design. Ghuloum proposed the
  445. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  446. based.
  447. I thank the many students who served as teaching assistants for the
  448. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  449. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  450. garbage collector and x86 interpreter, Michael Vollmer for work on
  451. efficient tail calls, and Michael Vitousek for help with the first
  452. offering of the incremental compiler course at IU.
  453. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  454. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  455. Michael Wollowski for teaching courses based on drafts of this book
  456. and for their feedback. I thank the National Science Foundation for
  457. the grants that helped to support this work: Grant Numbers 1518844,
  458. 1763922, and 1814460.
  459. I thank Ronald Garcia for helping me survive Dybvig's compiler
  460. course in the early 2000s and especially for finding the bug that
  461. sent our garbage collector on a wild goose chase!
  462. \mbox{}\\
  463. \noindent Jeremy G. Siek \\
  464. Bloomington, Indiana
  465. \mainmatter
  466. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  467. \chapter{Preliminaries}
  468. \label{ch:trees-recur}
  469. \setcounter{footnote}{0}
  470. In this chapter we introduce the basic tools needed to implement a
  471. compiler. Programs are typically input by a programmer as text, that
  472. is, a sequence of characters. The program-as-text representation is
  473. called \emph{concrete syntax}. We use concrete syntax to concisely
  474. write down and talk about programs. Inside the compiler, we use
  475. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  476. that efficiently supports the operations that the compiler needs to
  477. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  478. syntax}\index{subject}{abstract syntax
  479. tree}\index{subject}{AST}\index{subject}{program}
  480. The process of translating concrete syntax to abstract syntax is
  481. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  482. chapter~\ref{ch:parsing}}.
  483. \racket{This book does not cover the theory and implementation of parsing.
  484. We refer the readers interested in parsing to the thorough treatment
  485. of parsing by \citet{Aho:2006wb}.}%
  486. %
  487. \racket{A parser is provided in the support code for translating from
  488. concrete to abstract syntax.}%
  489. %
  490. \python{For now we use the \code{parse} function in Python's
  491. \code{ast} module to translate from concrete to abstract syntax.}
  492. ASTs can be represented inside the compiler in many different ways,
  493. depending on the programming language used to write the compiler.
  494. %
  495. \racket{We use Racket's
  496. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  497. feature to represent ASTs (section~\ref{sec:ast}).}
  498. %
  499. \python{We use Python classes and objects to represent ASTs, especially the
  500. classes defined in the standard \code{ast} module for the Python
  501. source language.}
  502. %
  503. We use grammars to define the abstract syntax of programming languages
  504. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  505. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  506. recursive functions to construct and deconstruct ASTs
  507. (section~\ref{sec:recursion}). This chapter provides a brief
  508. introduction to these components.
  509. \racket{\index{subject}{struct}}
  510. \python{\index{subject}{class}\index{subject}{object}}
  511. \section{Abstract Syntax Trees}
  512. \label{sec:ast}
  513. Compilers use abstract syntax trees to represent programs because they
  514. often need to ask questions such as, for a given part of a program,
  515. what kind of language feature is it? What are its subparts? Consider
  516. the program on the left and the diagram of its AST on the
  517. right~\eqref{eq:arith-prog}. This program is an addition operation
  518. that has two subparts, a \racket{read}\python{input} operation and a
  519. negation. The negation has another subpart, the integer constant
  520. \code{8}. By using a tree to represent the program, we can easily
  521. follow the links to go from one part of a program to its subparts.
  522. \begin{center}
  523. \begin{minipage}{0.4\textwidth}
  524. {\if\edition\racketEd
  525. \begin{lstlisting}
  526. (+ (read) (- 8))
  527. \end{lstlisting}
  528. \fi}
  529. {\if\edition\pythonEd\pythonColor
  530. \begin{lstlisting}
  531. input_int() + -8
  532. \end{lstlisting}
  533. \fi}
  534. \end{minipage}
  535. \begin{minipage}{0.4\textwidth}
  536. \begin{equation}
  537. \begin{tikzpicture}
  538. \node[draw] (plus) at (0 , 0) {\key{+}};
  539. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  540. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  541. \node[draw] (8) at (1 , -2) {\key{8}};
  542. \draw[->] (plus) to (read);
  543. \draw[->] (plus) to (minus);
  544. \draw[->] (minus) to (8);
  545. \end{tikzpicture}
  546. \label{eq:arith-prog}
  547. \end{equation}
  548. \end{minipage}
  549. \end{center}
  550. We use the standard terminology for trees to describe ASTs: each
  551. rectangle above is called a \emph{node}. The arrows connect a node to its
  552. \emph{children}, which are also nodes. The top-most node is the
  553. \emph{root}. Every node except for the root has a \emph{parent} (the
  554. node of which it is the child). If a node has no children, it is a
  555. \emph{leaf} node; otherwise it is an \emph{internal} node.
  556. \index{subject}{node}
  557. \index{subject}{children}
  558. \index{subject}{root}
  559. \index{subject}{parent}
  560. \index{subject}{leaf}
  561. \index{subject}{internal node}
  562. %% Recall that an \emph{symbolic expression} (S-expression) is either
  563. %% \begin{enumerate}
  564. %% \item an atom, or
  565. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  566. %% where $e_1$ and $e_2$ are each an S-expression.
  567. %% \end{enumerate}
  568. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  569. %% null value \code{'()}, etc. We can create an S-expression in Racket
  570. %% simply by writing a backquote (called a quasi-quote in Racket)
  571. %% followed by the textual representation of the S-expression. It is
  572. %% quite common to use S-expressions to represent a list, such as $a, b
  573. %% ,c$ in the following way:
  574. %% \begin{lstlisting}
  575. %% `(a . (b . (c . ())))
  576. %% \end{lstlisting}
  577. %% Each element of the list is in the first slot of a pair, and the
  578. %% second slot is either the rest of the list or the null value, to mark
  579. %% the end of the list. Such lists are so common that Racket provides
  580. %% special notation for them that removes the need for the periods
  581. %% and so many parenthesis:
  582. %% \begin{lstlisting}
  583. %% `(a b c)
  584. %% \end{lstlisting}
  585. %% The following expression creates an S-expression that represents AST
  586. %% \eqref{eq:arith-prog}.
  587. %% \begin{lstlisting}
  588. %% `(+ (read) (- 8))
  589. %% \end{lstlisting}
  590. %% When using S-expressions to represent ASTs, the convention is to
  591. %% represent each AST node as a list and to put the operation symbol at
  592. %% the front of the list. The rest of the list contains the children. So
  593. %% in the above case, the root AST node has operation \code{`+} and its
  594. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  595. %% diagram \eqref{eq:arith-prog}.
  596. %% To build larger S-expressions one often needs to splice together
  597. %% several smaller S-expressions. Racket provides the comma operator to
  598. %% splice an S-expression into a larger one. For example, instead of
  599. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  600. %% we could have first created an S-expression for AST
  601. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  602. %% S-expression.
  603. %% \begin{lstlisting}
  604. %% (define ast1.4 `(- 8))
  605. %% (define ast1_1 `(+ (read) ,ast1.4))
  606. %% \end{lstlisting}
  607. %% In general, the Racket expression that follows the comma (splice)
  608. %% can be any expression that produces an S-expression.
  609. {\if\edition\racketEd
  610. We define a Racket \code{struct} for each kind of node. For this
  611. chapter we require just two kinds of nodes: one for integer constants
  612. (aka literals\index{subject}{literals})
  613. and one for primitive operations. The following is the \code{struct}
  614. definition for integer constants.\footnote{All the AST structures are
  615. defined in the file \code{utilities.rkt} in the support code.}
  616. \begin{lstlisting}
  617. (struct Int (value))
  618. \end{lstlisting}
  619. An integer node contains just one thing: the integer value.
  620. We establish the convention that \code{struct} names, such
  621. as \code{Int}, are capitalized.
  622. To create an AST node for the integer $8$, we write \INT{8}.
  623. \begin{lstlisting}
  624. (define eight (Int 8))
  625. \end{lstlisting}
  626. We say that the value created by \INT{8} is an
  627. \emph{instance} of the
  628. \code{Int} structure.
  629. The following is the \code{struct} definition for primitive operations.
  630. \begin{lstlisting}
  631. (struct Prim (op args))
  632. \end{lstlisting}
  633. A primitive operation node includes an operator symbol \code{op} and a
  634. list of child arguments called \code{args}. For example, to create an
  635. AST that negates the number $8$, we write the following.
  636. \begin{lstlisting}
  637. (define neg-eight (Prim '- (list eight)))
  638. \end{lstlisting}
  639. Primitive operations may have zero or more children. The \code{read}
  640. operator has zero:
  641. \begin{lstlisting}
  642. (define rd (Prim 'read '()))
  643. \end{lstlisting}
  644. The addition operator has two children:
  645. \begin{lstlisting}
  646. (define ast1_1 (Prim '+ (list rd neg-eight)))
  647. \end{lstlisting}
  648. We have made a design choice regarding the \code{Prim} structure.
  649. Instead of using one structure for many different operations
  650. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  651. structure for each operation, as follows:
  652. \begin{lstlisting}
  653. (struct Read ())
  654. (struct Add (left right))
  655. (struct Neg (value))
  656. \end{lstlisting}
  657. The reason that we choose to use just one structure is that many parts
  658. of the compiler can use the same code for the different primitive
  659. operators, so we might as well just write that code once by using a
  660. single structure.
  661. %
  662. \fi}
  663. {\if\edition\pythonEd\pythonColor
  664. We use a Python \code{class} for each kind of node.
  665. The following is the class definition for
  666. constants (aka literals\index{subject}{literals})
  667. from the Python \code{ast} module.
  668. \begin{lstlisting}
  669. class Constant:
  670. def __init__(self, value):
  671. self.value = value
  672. \end{lstlisting}
  673. An integer constant node includes just one thing: the integer value.
  674. To create an AST node for the integer $8$, we write \INT{8}.
  675. \begin{lstlisting}
  676. eight = Constant(8)
  677. \end{lstlisting}
  678. We say that the value created by \INT{8} is an
  679. \emph{instance} of the \code{Constant} class.
  680. The following is the class definition for unary operators.
  681. \begin{lstlisting}
  682. class UnaryOp:
  683. def __init__(self, op, operand):
  684. self.op = op
  685. self.operand = operand
  686. \end{lstlisting}
  687. The specific operation is specified by the \code{op} parameter. For
  688. example, the class \code{USub} is for unary subtraction.
  689. (More unary operators are introduced in later chapters.) To create an AST that
  690. negates the number $8$, we write the following.
  691. \begin{lstlisting}
  692. neg_eight = UnaryOp(USub(), eight)
  693. \end{lstlisting}
  694. The call to the \code{input\_int} function is represented by the
  695. \code{Call} and \code{Name} classes.
  696. \begin{lstlisting}
  697. class Call:
  698. def __init__(self, func, args):
  699. self.func = func
  700. self.args = args
  701. class Name:
  702. def __init__(self, id):
  703. self.id = id
  704. \end{lstlisting}
  705. To create an AST node that calls \code{input\_int}, we write
  706. \begin{lstlisting}
  707. read = Call(Name('input_int'), [])
  708. \end{lstlisting}
  709. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  710. the \code{BinOp} class for binary operators.
  711. \begin{lstlisting}
  712. class BinOp:
  713. def __init__(self, left, op, right):
  714. self.op = op
  715. self.left = left
  716. self.right = right
  717. \end{lstlisting}
  718. Similar to \code{UnaryOp}, the specific operation is specified by the
  719. \code{op} parameter, which for now is just an instance of the
  720. \code{Add} class. So to create the AST
  721. node that adds negative eight to some user input, we write the following.
  722. \begin{lstlisting}
  723. ast1_1 = BinOp(read, Add(), neg_eight)
  724. \end{lstlisting}
  725. \fi}
  726. To compile a program such as \eqref{eq:arith-prog}, we need to know
  727. that the operation associated with the root node is addition and we
  728. need to be able to access its two
  729. children. \racket{Racket}\python{Python} provides pattern matching to
  730. support these kinds of queries, as we see in
  731. section~\ref{sec:pattern-matching}.
  732. We often write down the concrete syntax of a program even when we
  733. actually have in mind the AST, because the concrete syntax is more
  734. concise. We recommend that you always think of programs as abstract
  735. syntax trees.
  736. \section{Grammars}
  737. \label{sec:grammar}
  738. \index{subject}{integer}
  739. %\index{subject}{constant}
  740. A programming language can be thought of as a \emph{set} of programs.
  741. The set is infinite (that is, one can always create larger programs),
  742. so one cannot simply describe a language by listing all the
  743. programs in the language. Instead we write down a set of rules, a
  744. \emph{context-free grammar}, for building programs. Grammars are often used to
  745. define the concrete syntax of a language, but they can also be used to
  746. describe the abstract syntax. We write our rules in a variant of
  747. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  748. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  749. we describe a small language, named \LangInt{}, that consists of
  750. integers and arithmetic operations.\index{subject}{grammar}
  751. \index{subject}{context-free grammar}
  752. The first grammar rule for the abstract syntax of \LangInt{} says that an
  753. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  754. \begin{equation}
  755. \Exp ::= \INT{\Int} \label{eq:arith-int}
  756. \end{equation}
  757. %
  758. Each rule has a left-hand side and a right-hand side.
  759. If you have an AST node that matches the
  760. right-hand side, then you can categorize it according to the
  761. left-hand side.
  762. %
  763. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  764. are \emph{terminal} symbols and must literally appear in the program for the
  765. rule to be applicable.\index{subject}{terminal}
  766. %
  767. Our grammars do not mention \emph{white space}, that is, delimiter
  768. characters like spaces, tabs, and new lines. White space may be
  769. inserted between symbols for disambiguation and to improve
  770. readability. \index{subject}{white space}
  771. %
  772. A name such as $\Exp$ that is defined by the grammar rules is a
  773. \emph{nonterminal}. \index{subject}{nonterminal}
  774. %
  775. The name $\Int$ is also a nonterminal, but instead of defining it with
  776. a grammar rule, we define it with the following explanation. An
  777. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  778. $-$ (for negative integers), such that the sequence of decimals
  779. %
  780. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  781. enables the representation of integers using 63 bits, which simplifies
  782. several aspects of compilation.
  783. %
  784. Thus, these integers correspond to the Racket \texttt{fixnum}
  785. datatype on a 64-bit machine.}
  786. %
  787. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  788. enables the representation of integers using 64 bits, which simplifies
  789. several aspects of compilation. In contrast, integers in Python have
  790. unlimited precision, but the techniques needed to handle unlimited
  791. precision fall outside the scope of this book.}
  792. The second grammar rule is the \READOP{} operation, which receives an
  793. input integer from the user of the program.
  794. \begin{equation}
  795. \Exp ::= \READ{} \label{eq:arith-read}
  796. \end{equation}
  797. The third rule categorizes the negation of an $\Exp$ node as an
  798. $\Exp$.
  799. \begin{equation}
  800. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  801. \end{equation}
  802. We can apply these rules to categorize the ASTs that are in the
  803. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  804. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  805. following AST is an $\Exp$.
  806. \begin{center}
  807. \begin{minipage}{0.5\textwidth}
  808. \NEG{\INT{\code{8}}}
  809. \end{minipage}
  810. \begin{minipage}{0.25\textwidth}
  811. \begin{equation}
  812. \begin{tikzpicture}
  813. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  814. \node[draw, circle] (8) at (0, -1.2) {$8$};
  815. \draw[->] (minus) to (8);
  816. \end{tikzpicture}
  817. \label{eq:arith-neg8}
  818. \end{equation}
  819. \end{minipage}
  820. \end{center}
  821. The next two grammar rules are for addition and subtraction expressions:
  822. \begin{align}
  823. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  824. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  825. \end{align}
  826. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  827. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  828. \eqref{eq:arith-read}, and we have already categorized
  829. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  830. to show that
  831. \[
  832. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  833. \]
  834. is an $\Exp$ in the \LangInt{} language.
  835. If you have an AST for which these rules do not apply, then the
  836. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  837. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  838. because there is no rule for the \key{*} operator. Whenever we
  839. define a language with a grammar, the language includes only those
  840. programs that are justified by the grammar rules.
  841. {\if\edition\pythonEd\pythonColor
  842. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  843. There is a statement for printing the value of an expression
  844. \[
  845. \Stmt{} ::= \PRINT{\Exp}
  846. \]
  847. and a statement that evaluates an expression but ignores the result.
  848. \[
  849. \Stmt{} ::= \EXPR{\Exp}
  850. \]
  851. \fi}
  852. {\if\edition\racketEd
  853. The last grammar rule for \LangInt{} states that there is a
  854. \code{Program} node to mark the top of the whole program:
  855. \[
  856. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  857. \]
  858. The \code{Program} structure is defined as follows:
  859. \begin{lstlisting}
  860. (struct Program (info body))
  861. \end{lstlisting}
  862. where \code{body} is an expression. In further chapters, the \code{info}
  863. part is used to store auxiliary information, but for now it is
  864. just the empty list.
  865. \fi}
  866. {\if\edition\pythonEd\pythonColor
  867. The last grammar rule for \LangInt{} states that there is a
  868. \code{Module} node to mark the top of the whole program:
  869. \[
  870. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  871. \]
  872. The asterisk $*$ indicates a list of the preceding grammar item, in
  873. this case a list of statements.
  874. %
  875. The \code{Module} class is defined as follows:
  876. \begin{lstlisting}
  877. class Module:
  878. def __init__(self, body):
  879. self.body = body
  880. \end{lstlisting}
  881. where \code{body} is a list of statements.
  882. \fi}
  883. It is common to have many grammar rules with the same left-hand side
  884. but different right-hand sides, such as the rules for $\Exp$ in the
  885. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  886. combine several right-hand sides into a single rule.
  887. The concrete syntax for \LangInt{} is shown in
  888. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  889. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  890. %
  891. \racket{The \code{read-program} function provided in
  892. \code{utilities.rkt} of the support code reads a program from a file
  893. (the sequence of characters in the concrete syntax of Racket) and
  894. parses it into an abstract syntax tree. Refer to the description of
  895. \code{read-program} in appendix~\ref{appendix:utilities} for more
  896. details.}
  897. %
  898. \python{We recommend using the \code{parse} function in Python's
  899. \code{ast} module to convert the concrete syntax into an abstract
  900. syntax tree.}
  901. \newcommand{\LintGrammarRacket}{
  902. \begin{array}{rcl}
  903. \Type &::=& \key{Integer} \\
  904. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  905. \MID \CSUB{\Exp}{\Exp}
  906. \end{array}
  907. }
  908. \newcommand{\LintASTRacket}{
  909. \begin{array}{rcl}
  910. \Type &::=& \key{Integer} \\
  911. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  912. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  913. \end{array}
  914. }
  915. \newcommand{\LintGrammarPython}{
  916. \begin{array}{rcl}
  917. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  918. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  919. \end{array}
  920. }
  921. \newcommand{\LintASTPython}{
  922. \begin{array}{rcl}
  923. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  924. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  925. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  926. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  927. \end{array}
  928. }
  929. \begin{figure}[tp]
  930. \begin{tcolorbox}[colback=white]
  931. {\if\edition\racketEd
  932. \[
  933. \begin{array}{l}
  934. \LintGrammarRacket \\
  935. \begin{array}{rcl}
  936. \LangInt{} &::=& \Exp
  937. \end{array}
  938. \end{array}
  939. \]
  940. \fi}
  941. {\if\edition\pythonEd\pythonColor
  942. \[
  943. \begin{array}{l}
  944. \LintGrammarPython \\
  945. \begin{array}{rcl}
  946. \LangInt{} &::=& \Stmt^{*}
  947. \end{array}
  948. \end{array}
  949. \]
  950. \fi}
  951. \end{tcolorbox}
  952. \caption{The concrete syntax of \LangInt{}.}
  953. \label{fig:r0-concrete-syntax}
  954. \end{figure}
  955. \begin{figure}[tp]
  956. \begin{tcolorbox}[colback=white]
  957. {\if\edition\racketEd
  958. \[
  959. \begin{array}{l}
  960. \LintASTRacket{} \\
  961. \begin{array}{rcl}
  962. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  963. \end{array}
  964. \end{array}
  965. \]
  966. \fi}
  967. {\if\edition\pythonEd\pythonColor
  968. \[
  969. \begin{array}{l}
  970. \LintASTPython\\
  971. \begin{array}{rcl}
  972. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  973. \end{array}
  974. \end{array}
  975. \]
  976. \fi}
  977. \end{tcolorbox}
  978. \python{
  979. \index{subject}{Constant@\texttt{Constant}}
  980. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  981. \index{subject}{USub@\texttt{USub}}
  982. \index{subject}{inputint@\texttt{input\_int}}
  983. \index{subject}{Call@\texttt{Call}}
  984. \index{subject}{Name@\texttt{Name}}
  985. \index{subject}{BinOp@\texttt{BinOp}}
  986. \index{subject}{Add@\texttt{Add}}
  987. \index{subject}{Sub@\texttt{Sub}}
  988. \index{subject}{print@\texttt{print}}
  989. \index{subject}{Expr@\texttt{Expr}}
  990. \index{subject}{Module@\texttt{Module}}
  991. }
  992. \caption{The abstract syntax of \LangInt{}.}
  993. \label{fig:r0-syntax}
  994. \end{figure}
  995. \section{Pattern Matching}
  996. \label{sec:pattern-matching}
  997. As mentioned in section~\ref{sec:ast}, compilers often need to access
  998. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  999. provides the \texttt{match} feature to access the parts of a value.
  1000. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  1001. \begin{center}
  1002. \begin{minipage}{1.0\textwidth}
  1003. {\if\edition\racketEd
  1004. \begin{lstlisting}
  1005. (match ast1_1
  1006. [(Prim op (list child1 child2))
  1007. (print op)])
  1008. \end{lstlisting}
  1009. \fi}
  1010. {\if\edition\pythonEd\pythonColor
  1011. \begin{lstlisting}
  1012. match ast1_1:
  1013. case BinOp(child1, op, child2):
  1014. print(op)
  1015. \end{lstlisting}
  1016. \fi}
  1017. \end{minipage}
  1018. \end{center}
  1019. {\if\edition\racketEd
  1020. %
  1021. In this example, the \texttt{match} form checks whether the AST
  1022. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1023. three pattern variables \texttt{op}, \texttt{child1}, and
  1024. \texttt{child2}. In general, a match clause consists of a
  1025. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1026. recursively defined to be a pattern variable, a structure name
  1027. followed by a pattern for each of the structure's arguments, or an
  1028. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1029. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1030. and chapter 9 of The Racket
  1031. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1032. for complete descriptions of \code{match}.)
  1033. %
  1034. The body of a match clause may contain arbitrary Racket code. The
  1035. pattern variables can be used in the scope of the body, such as
  1036. \code{op} in \code{(print op)}.
  1037. %
  1038. \fi}
  1039. %
  1040. %
  1041. {\if\edition\pythonEd\pythonColor
  1042. %
  1043. In the example above, the \texttt{match} form checks whether the AST
  1044. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1045. three pattern variables (\texttt{child1}, \texttt{op}, and
  1046. \texttt{child2}). In general, each \code{case} consists of a
  1047. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1048. recursively defined to be one of the following: a pattern variable, a
  1049. class name followed by a pattern for each of its constructor's
  1050. arguments, or other literals\index{subject}{literals} such as strings
  1051. or lists.
  1052. %
  1053. The body of each \code{case} may contain arbitrary Python code. The
  1054. pattern variables can be used in the body, such as \code{op} in
  1055. \code{print(op)}.
  1056. %
  1057. \fi}
  1058. A \code{match} form may contain several clauses, as in the following
  1059. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1060. the AST. The \code{match} proceeds through the clauses in order,
  1061. checking whether the pattern can match the input AST. The body of the
  1062. first clause that matches is executed. The output of \code{leaf} for
  1063. several ASTs is shown on the right side of the following:
  1064. \begin{center}
  1065. \begin{minipage}{0.6\textwidth}
  1066. {\if\edition\racketEd
  1067. \begin{lstlisting}
  1068. (define (leaf arith)
  1069. (match arith
  1070. [(Int n) #t]
  1071. [(Prim 'read '()) #t]
  1072. [(Prim '- (list e1)) #f]
  1073. [(Prim '+ (list e1 e2)) #f]
  1074. [(Prim '- (list e1 e2)) #f]))
  1075. (leaf (Prim 'read '()))
  1076. (leaf (Prim '- (list (Int 8))))
  1077. (leaf (Int 8))
  1078. \end{lstlisting}
  1079. \fi}
  1080. {\if\edition\pythonEd\pythonColor
  1081. \begin{lstlisting}
  1082. def leaf(arith):
  1083. match arith:
  1084. case Constant(n):
  1085. return True
  1086. case Call(Name('input_int'), []):
  1087. return True
  1088. case UnaryOp(USub(), e1):
  1089. return False
  1090. case BinOp(e1, Add(), e2):
  1091. return False
  1092. case BinOp(e1, Sub(), e2):
  1093. return False
  1094. print(leaf(Call(Name('input_int'), [])))
  1095. print(leaf(UnaryOp(USub(), eight)))
  1096. print(leaf(Constant(8)))
  1097. \end{lstlisting}
  1098. \fi}
  1099. \end{minipage}
  1100. \vrule
  1101. \begin{minipage}{0.25\textwidth}
  1102. {\if\edition\racketEd
  1103. \begin{lstlisting}
  1104. #t
  1105. #f
  1106. #t
  1107. \end{lstlisting}
  1108. \fi}
  1109. {\if\edition\pythonEd\pythonColor
  1110. \begin{lstlisting}
  1111. True
  1112. False
  1113. True
  1114. \end{lstlisting}
  1115. \fi}
  1116. \end{minipage}
  1117. \index{subject}{True@\TRUE{}}
  1118. \index{subject}{False@\FALSE{}}
  1119. \end{center}
  1120. When constructing a \code{match} expression, we refer to the grammar
  1121. definition to identify which nonterminal we are expecting to match
  1122. against, and then we make sure that (1) we have one
  1123. \racket{clause}\python{case} for each alternative of that nonterminal
  1124. and (2) the pattern in each \racket{clause}\python{case}
  1125. corresponds to the corresponding right-hand side of a grammar
  1126. rule. For the \code{match} in the \code{leaf} function, we refer to
  1127. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1128. nonterminal has five alternatives, so the \code{match} has five
  1129. \racket{clauses}\python{cases}. The pattern in each
  1130. \racket{clause}\python{case} corresponds to the right-hand side of a
  1131. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1132. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1133. translating from grammars to patterns, replace nonterminals such as
  1134. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1135. \code{e2}).
  1136. \section{Recursive Functions}
  1137. \label{sec:recursion}
  1138. \index{subject}{recursive function}
  1139. Programs are inherently recursive. For example, an expression is often
  1140. made of smaller expressions. Thus, the natural way to process an
  1141. entire program is to use a recursive function. As a first example of
  1142. such a recursive function, we define the function \code{is\_exp} as
  1143. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1144. value and determine whether or not it is an expression in \LangInt{}.
  1145. %
  1146. We say that a function is defined by \emph{structural recursion} if
  1147. it is defined using a sequence of match \racket{clauses}\python{cases}
  1148. that correspond to a grammar and the body of each
  1149. \racket{clause}\python{case} makes a recursive call on each child
  1150. node.\footnote{This principle of structuring code according to the
  1151. data definition is advocated in the book \emph{How to Design
  1152. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1153. second function, named \code{is\_stmt}, that recognizes whether a value
  1154. is a \LangInt{} statement.} \python{Finally, }
  1155. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1156. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1157. In general, we can write one recursive function to handle each
  1158. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1159. two examples at the bottom of the figure, the first is in
  1160. \LangInt{} and the second is not.
  1161. \begin{figure}[tp]
  1162. \begin{tcolorbox}[colback=white]
  1163. {\if\edition\racketEd
  1164. \begin{lstlisting}
  1165. (define (is_exp ast)
  1166. (match ast
  1167. [(Int n) #t]
  1168. [(Prim 'read '()) #t]
  1169. [(Prim '- (list e)) (is_exp e)]
  1170. [(Prim '+ (list e1 e2))
  1171. (and (is_exp e1) (is_exp e2))]
  1172. [(Prim '- (list e1 e2))
  1173. (and (is_exp e1) (is_exp e2))]
  1174. [else #f]))
  1175. (define (is_Lint ast)
  1176. (match ast
  1177. [(Program '() e) (is_exp e)]
  1178. [else #f]))
  1179. (is_Lint (Program '() ast1_1)
  1180. (is_Lint (Program '()
  1181. (Prim '* (list (Prim 'read '())
  1182. (Prim '+ (list (Int 8)))))))
  1183. \end{lstlisting}
  1184. \fi}
  1185. {\if\edition\pythonEd\pythonColor
  1186. \begin{lstlisting}
  1187. def is_exp(e):
  1188. match e:
  1189. case Constant(n):
  1190. return True
  1191. case Call(Name('input_int'), []):
  1192. return True
  1193. case UnaryOp(USub(), e1):
  1194. return is_exp(e1)
  1195. case BinOp(e1, Add(), e2):
  1196. return is_exp(e1) and is_exp(e2)
  1197. case BinOp(e1, Sub(), e2):
  1198. return is_exp(e1) and is_exp(e2)
  1199. case _:
  1200. return False
  1201. def is_stmt(s):
  1202. match s:
  1203. case Expr(Call(Name('print'), [e])):
  1204. return is_exp(e)
  1205. case Expr(e):
  1206. return is_exp(e)
  1207. case _:
  1208. return False
  1209. def is_Lint(p):
  1210. match p:
  1211. case Module(body):
  1212. return all([is_stmt(s) for s in body])
  1213. case _:
  1214. return False
  1215. print(is_Lint(Module([Expr(ast1_1)])))
  1216. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1217. UnaryOp(Add(), Constant(8))))])))
  1218. \end{lstlisting}
  1219. \fi}
  1220. \end{tcolorbox}
  1221. \caption{Example of recursive functions for \LangInt{}. These functions
  1222. recognize whether an AST is in \LangInt{}.}
  1223. \label{fig:exp-predicate}
  1224. \end{figure}
  1225. %% You may be tempted to merge the two functions into one, like this:
  1226. %% \begin{center}
  1227. %% \begin{minipage}{0.5\textwidth}
  1228. %% \begin{lstlisting}
  1229. %% (define (Lint ast)
  1230. %% (match ast
  1231. %% [(Int n) #t]
  1232. %% [(Prim 'read '()) #t]
  1233. %% [(Prim '- (list e)) (Lint e)]
  1234. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1235. %% [(Program '() e) (Lint e)]
  1236. %% [else #f]))
  1237. %% \end{lstlisting}
  1238. %% \end{minipage}
  1239. %% \end{center}
  1240. %% %
  1241. %% Sometimes such a trick will save a few lines of code, especially when
  1242. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1243. %% \emph{not} recommended because it can get you into trouble.
  1244. %% %
  1245. %% For example, the above function is subtly wrong:
  1246. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1247. %% returns true when it should return false.
  1248. \section{Interpreters}
  1249. \label{sec:interp_Lint}
  1250. \index{subject}{interpreter}
  1251. The behavior of a program is defined by the specification of the
  1252. programming language.
  1253. %
  1254. \racket{For example, the Scheme language is defined in the report by
  1255. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1256. reference manual~\citep{plt-tr}.}
  1257. %
  1258. \python{For example, the Python language is defined in the Python
  1259. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1260. %
  1261. In this book we use interpreters to specify each language that we
  1262. consider. An interpreter that is designated as the definition of a
  1263. language is called a \emph{definitional
  1264. interpreter}~\citep{reynolds72:_def_interp}.
  1265. \index{subject}{definitional interpreter} We warm up by creating a
  1266. definitional interpreter for the \LangInt{} language. This interpreter
  1267. serves as a second example of structural recursion. The definition of the
  1268. \code{interp\_Lint} function is shown in
  1269. figure~\ref{fig:interp_Lint}.
  1270. %
  1271. \racket{The body of the function is a match on the input program
  1272. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1273. which in turn has one match clause per grammar rule for \LangInt{}
  1274. expressions.}
  1275. %
  1276. \python{The body of the function matches on the \code{Module} AST node
  1277. and then invokes \code{interp\_stmt} on each statement in the
  1278. module. The \code{interp\_stmt} function includes a case for each
  1279. grammar rule of the \Stmt{} nonterminal, and it calls
  1280. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1281. function includes a case for each grammar rule of the \Exp{}
  1282. nonterminal. We use several auxiliary functions such as \code{add64}
  1283. and \code{input\_int} that are defined in the support code for this book.}
  1284. \begin{figure}[tp]
  1285. \begin{tcolorbox}[colback=white]
  1286. {\if\edition\racketEd
  1287. \begin{lstlisting}
  1288. (define (interp_exp e)
  1289. (match e
  1290. [(Int n) n]
  1291. [(Prim 'read '())
  1292. (define r (read))
  1293. (cond [(fixnum? r) r]
  1294. [else (error 'interp_exp "read expected an integer" r)])]
  1295. [(Prim '- (list e))
  1296. (define v (interp_exp e))
  1297. (fx- 0 v)]
  1298. [(Prim '+ (list e1 e2))
  1299. (define v1 (interp_exp e1))
  1300. (define v2 (interp_exp e2))
  1301. (fx+ v1 v2)]
  1302. [(Prim '- (list e1 e2))
  1303. (define v1 (interp_exp e1))
  1304. (define v2 (interp_exp e2))
  1305. (fx- v1 v2)]))
  1306. (define (interp_Lint p)
  1307. (match p
  1308. [(Program '() e) (interp_exp e)]))
  1309. \end{lstlisting}
  1310. \fi}
  1311. {\if\edition\pythonEd\pythonColor
  1312. \begin{lstlisting}
  1313. def interp_exp(e):
  1314. match e:
  1315. case BinOp(left, Add(), right):
  1316. l = interp_exp(left); r = interp_exp(right)
  1317. return add64(l, r)
  1318. case BinOp(left, Sub(), right):
  1319. l = interp_exp(left); r = interp_exp(right)
  1320. return sub64(l, r)
  1321. case UnaryOp(USub(), v):
  1322. return neg64(interp_exp(v))
  1323. case Constant(value):
  1324. return value
  1325. case Call(Name('input_int'), []):
  1326. return input_int()
  1327. def interp_stmt(s):
  1328. match s:
  1329. case Expr(Call(Name('print'), [arg])):
  1330. print(interp_exp(arg))
  1331. case Expr(value):
  1332. interp_exp(value)
  1333. def interp_Lint(p):
  1334. match p:
  1335. case Module(body):
  1336. for s in body:
  1337. interp_stmt(s)
  1338. \end{lstlisting}
  1339. \fi}
  1340. \end{tcolorbox}
  1341. \caption{Interpreter for the \LangInt{} language.}
  1342. \label{fig:interp_Lint}
  1343. \end{figure}
  1344. Let us consider the result of interpreting a few \LangInt{} programs. The
  1345. following program adds two integers:
  1346. {\if\edition\racketEd
  1347. \begin{lstlisting}
  1348. (+ 10 32)
  1349. \end{lstlisting}
  1350. \fi}
  1351. {\if\edition\pythonEd\pythonColor
  1352. \begin{lstlisting}
  1353. print(10 + 32)
  1354. \end{lstlisting}
  1355. \fi}
  1356. %
  1357. \noindent The result is \key{42}, the answer to life, the universe,
  1358. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1359. the Galaxy} by Douglas Adams.}
  1360. %
  1361. We wrote this program in concrete syntax, whereas the parsed
  1362. abstract syntax is
  1363. {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd\pythonColor
  1369. \begin{lstlisting}
  1370. Module([Expr(Call(Name('print'),
  1371. [BinOp(Constant(10), Add(), Constant(32))]))])
  1372. \end{lstlisting}
  1373. \fi}
  1374. The following program demonstrates that expressions may be nested within
  1375. each other, in this case nesting several additions and negations.
  1376. {\if\edition\racketEd
  1377. \begin{lstlisting}
  1378. (+ 10 (- (+ 12 20)))
  1379. \end{lstlisting}
  1380. \fi}
  1381. {\if\edition\pythonEd\pythonColor
  1382. \begin{lstlisting}
  1383. print(10 + -(12 + 20))
  1384. \end{lstlisting}
  1385. \fi}
  1386. %
  1387. \noindent What is the result of this program?
  1388. {\if\edition\racketEd
  1389. As mentioned previously, the \LangInt{} language does not support
  1390. arbitrarily large integers but only $63$-bit integers, so we
  1391. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1392. in Racket.
  1393. Suppose that
  1394. \[
  1395. n = 999999999999999999
  1396. \]
  1397. which indeed fits in $63$ bits. What happens when we run the
  1398. following program in our interpreter?
  1399. \begin{lstlisting}
  1400. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1401. \end{lstlisting}
  1402. It produces the following error:
  1403. \begin{lstlisting}
  1404. fx+: result is not a fixnum
  1405. \end{lstlisting}
  1406. We establish the convention that if running the definitional
  1407. interpreter on a program produces an error, then the meaning of that
  1408. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1409. error is a \code{trapped-error}. A compiler for the language is under
  1410. no obligation regarding programs with unspecified behavior; it does
  1411. not have to produce an executable, and if it does, that executable can
  1412. do anything. On the other hand, if the error is a
  1413. \code{trapped-error}, then the compiler must produce an executable and
  1414. it is required to report that an error occurred. To signal an error,
  1415. exit with a return code of \code{255}. The interpreters in chapters
  1416. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1417. \code{trapped-error}.
  1418. \fi}
  1419. % TODO: how to deal with too-large integers in the Python interpreter?
  1420. %% This convention applies to the languages defined in this
  1421. %% book, as a way to simplify the student's task of implementing them,
  1422. %% but this convention is not applicable to all programming languages.
  1423. %%
  1424. The last feature of the \LangInt{} language, the \READOP{} operation,
  1425. prompts the user of the program for an integer. Recall that program
  1426. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1427. \code{8}. So, if we run {\if\edition\racketEd
  1428. \begin{lstlisting}
  1429. (interp_Lint (Program '() ast1_1))
  1430. \end{lstlisting}
  1431. \fi}
  1432. {\if\edition\pythonEd\pythonColor
  1433. \begin{lstlisting}
  1434. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1435. \end{lstlisting}
  1436. \fi}
  1437. \noindent and if the input is \code{50}, the result is \code{42}.
  1438. We include the \READOP{} operation in \LangInt{} so that a clever
  1439. student cannot implement a compiler for \LangInt{} that simply runs
  1440. the interpreter during compilation to obtain the output and then
  1441. generates the trivial code to produce the output.\footnote{Yes, a
  1442. clever student did this in the first instance of this course!}
  1443. The job of a compiler is to translate a program in one language into a
  1444. program in another language so that the output program behaves the
  1445. same way as the input program. This idea is depicted in the
  1446. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1447. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1448. Given a compiler that translates from language $\mathcal{L}_1$ to
  1449. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1450. compiler must translate it into some program $P_2$ such that
  1451. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1452. same input $i$ yields the same output $o$.
  1453. \begin{equation} \label{eq:compile-correct}
  1454. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1455. \node (p1) at (0, 0) {$P_1$};
  1456. \node (p2) at (3, 0) {$P_2$};
  1457. \node (o) at (3, -2.5) {$o$};
  1458. \path[->] (p1) edge [above] node {compile} (p2);
  1459. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1460. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1461. \end{tikzpicture}
  1462. \end{equation}
  1463. \python{We establish the convention that if running the definitional
  1464. interpreter on a program produces an error, then the meaning of that
  1465. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1466. unless the exception raised is a \code{TrappedError}. A compiler for
  1467. the language is under no obligation regarding programs with
  1468. unspecified behavior; it does not have to produce an executable, and
  1469. if it does, that executable can do anything. On the other hand, if
  1470. the error is a \code{TrappedError}, then the compiler must produce
  1471. an executable and it is required to report that an error
  1472. occurred. To signal an error, exit with a return code of \code{255}.
  1473. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1474. section \ref{sec:arrays} use \code{TrappedError}.}
  1475. In the next section we see our first example of a compiler.
  1476. \section{Example Compiler: A Partial Evaluator}
  1477. \label{sec:partial-evaluation}
  1478. In this section we consider a compiler that translates \LangInt{}
  1479. programs into \LangInt{} programs that may be more efficient. The
  1480. compiler eagerly computes the parts of the program that do not depend
  1481. on any inputs, a process known as \emph{partial
  1482. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1483. For example, given the following program
  1484. {\if\edition\racketEd
  1485. \begin{lstlisting}
  1486. (+ (read) (- (+ 5 3)))
  1487. \end{lstlisting}
  1488. \fi}
  1489. {\if\edition\pythonEd\pythonColor
  1490. \begin{lstlisting}
  1491. print(input_int() + -(5 + 3) )
  1492. \end{lstlisting}
  1493. \fi}
  1494. \noindent our compiler translates it into the program
  1495. {\if\edition\racketEd
  1496. \begin{lstlisting}
  1497. (+ (read) -8)
  1498. \end{lstlisting}
  1499. \fi}
  1500. {\if\edition\pythonEd\pythonColor
  1501. \begin{lstlisting}
  1502. print(input_int() + -8)
  1503. \end{lstlisting}
  1504. \fi}
  1505. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1506. evaluator for the \LangInt{} language. The output of the partial evaluator
  1507. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1508. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1509. whereas the code for partially evaluating the negation and addition
  1510. operations is factored into three auxiliary functions:
  1511. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1512. functions is the output of partially evaluating the children.
  1513. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1514. arguments are integers and if they are, perform the appropriate
  1515. arithmetic. Otherwise, they create an AST node for the arithmetic
  1516. operation.
  1517. \begin{figure}[tp]
  1518. \begin{tcolorbox}[colback=white]
  1519. {\if\edition\racketEd
  1520. \begin{lstlisting}
  1521. (define (pe_neg r)
  1522. (match r
  1523. [(Int n) (Int (fx- 0 n))]
  1524. [else (Prim '- (list r))]))
  1525. (define (pe_add r1 r2)
  1526. (match* (r1 r2)
  1527. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1528. [(_ _) (Prim '+ (list r1 r2))]))
  1529. (define (pe_sub r1 r2)
  1530. (match* (r1 r2)
  1531. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1532. [(_ _) (Prim '- (list r1 r2))]))
  1533. (define (pe_exp e)
  1534. (match e
  1535. [(Int n) (Int n)]
  1536. [(Prim 'read '()) (Prim 'read '())]
  1537. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1538. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1539. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1540. (define (pe_Lint p)
  1541. (match p
  1542. [(Program '() e) (Program '() (pe_exp e))]))
  1543. \end{lstlisting}
  1544. \fi}
  1545. {\if\edition\pythonEd\pythonColor
  1546. \begin{lstlisting}
  1547. def pe_neg(r):
  1548. match r:
  1549. case Constant(n):
  1550. return Constant(neg64(n))
  1551. case _:
  1552. return UnaryOp(USub(), r)
  1553. def pe_add(r1, r2):
  1554. match (r1, r2):
  1555. case (Constant(n1), Constant(n2)):
  1556. return Constant(add64(n1, n2))
  1557. case _:
  1558. return BinOp(r1, Add(), r2)
  1559. def pe_sub(r1, r2):
  1560. match (r1, r2):
  1561. case (Constant(n1), Constant(n2)):
  1562. return Constant(sub64(n1, n2))
  1563. case _:
  1564. return BinOp(r1, Sub(), r2)
  1565. def pe_exp(e):
  1566. match e:
  1567. case BinOp(left, Add(), right):
  1568. return pe_add(pe_exp(left), pe_exp(right))
  1569. case BinOp(left, Sub(), right):
  1570. return pe_sub(pe_exp(left), pe_exp(right))
  1571. case UnaryOp(USub(), v):
  1572. return pe_neg(pe_exp(v))
  1573. case Constant(value):
  1574. return e
  1575. case Call(Name('input_int'), []):
  1576. return e
  1577. def pe_stmt(s):
  1578. match s:
  1579. case Expr(Call(Name('print'), [arg])):
  1580. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1581. case Expr(value):
  1582. return Expr(pe_exp(value))
  1583. def pe_P_int(p):
  1584. match p:
  1585. case Module(body):
  1586. new_body = [pe_stmt(s) for s in body]
  1587. return Module(new_body)
  1588. \end{lstlisting}
  1589. \fi}
  1590. \end{tcolorbox}
  1591. \caption{A partial evaluator for \LangInt{}.}
  1592. \label{fig:pe-arith}
  1593. \end{figure}
  1594. To gain some confidence that the partial evaluator is correct, we can
  1595. test whether it produces programs that produce the same result as the
  1596. input programs. That is, we can test whether it satisfies the diagram
  1597. of \eqref{eq:compile-correct}.
  1598. %
  1599. {\if\edition\racketEd
  1600. The following code runs the partial evaluator on several examples and
  1601. tests the output program. The \texttt{parse-program} and
  1602. \texttt{assert} functions are defined in
  1603. appendix~\ref{appendix:utilities}.\\
  1604. \begin{minipage}{1.0\textwidth}
  1605. \begin{lstlisting}
  1606. (define (test_pe p)
  1607. (assert "testing pe_Lint"
  1608. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1609. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1610. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1611. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1612. \end{lstlisting}
  1613. \end{minipage}
  1614. \fi}
  1615. % TODO: python version of testing the PE
  1616. \begin{exercise}\normalfont\normalsize
  1617. Create three programs in the \LangInt{} language and test whether
  1618. partially evaluating them with \code{pe\_Lint} and then
  1619. interpreting them with \code{interp\_Lint} gives the same result
  1620. as directly interpreting them with \code{interp\_Lint}.
  1621. \end{exercise}
  1622. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1623. \chapter{Integers and Variables}
  1624. \label{ch:Lvar}
  1625. \setcounter{footnote}{0}
  1626. This chapter covers compiling a subset of
  1627. \racket{Racket}\python{Python} to x86-64 assembly
  1628. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1629. integer arithmetic and local variables. We often refer to x86-64
  1630. simply as x86. The chapter first describes the \LangVar{} language
  1631. (section~\ref{sec:s0}) and then introduces x86 assembly
  1632. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1633. discuss only the instructions needed for compiling \LangVar{}. We
  1634. introduce more x86 instructions in subsequent chapters. After
  1635. introducing \LangVar{} and x86, we reflect on their differences and
  1636. create a plan to break down the translation from \LangVar{} to x86
  1637. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1638. the chapter gives detailed hints regarding each step. We aim to give
  1639. enough hints that the well-prepared reader, together with a few
  1640. friends, can implement a compiler from \LangVar{} to x86 in a short
  1641. time. To suggest the scale of this first compiler, we note that the
  1642. instructor solution for the \LangVar{} compiler is approximately
  1643. \racket{500}\python{300} lines of code.
  1644. \section{The \LangVar{} Language}
  1645. \label{sec:s0}
  1646. \index{subject}{variable}
  1647. The \LangVar{} language extends the \LangInt{} language with
  1648. variables. The concrete syntax of the \LangVar{} language is defined
  1649. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1650. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1651. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1652. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1653. \key{-} is a unary operator, and \key{+} is a binary operator.
  1654. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1655. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1656. the top of the program.
  1657. %% The $\itm{info}$
  1658. %% field of the \key{Program} structure contains an \emph{association
  1659. %% list} (a list of key-value pairs) that is used to communicate
  1660. %% auxiliary data from one compiler pass the next.
  1661. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1662. exhibit several compilation techniques.
  1663. \newcommand{\LvarGrammarRacket}{
  1664. \begin{array}{rcl}
  1665. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1666. \end{array}
  1667. }
  1668. \newcommand{\LvarASTRacket}{
  1669. \begin{array}{rcl}
  1670. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1671. \end{array}
  1672. }
  1673. \newcommand{\LvarGrammarPython}{
  1674. \begin{array}{rcl}
  1675. \Exp &::=& \Var{} \\
  1676. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1677. \end{array}
  1678. }
  1679. \newcommand{\LvarASTPython}{
  1680. \begin{array}{rcl}
  1681. \Exp{} &::=& \VAR{\Var{}} \\
  1682. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1683. \end{array}
  1684. }
  1685. \begin{figure}[tp]
  1686. \centering
  1687. \begin{tcolorbox}[colback=white]
  1688. {\if\edition\racketEd
  1689. \[
  1690. \begin{array}{l}
  1691. \gray{\LintGrammarRacket{}} \\ \hline
  1692. \LvarGrammarRacket{} \\
  1693. \begin{array}{rcl}
  1694. \LangVarM{} &::=& \Exp
  1695. \end{array}
  1696. \end{array}
  1697. \]
  1698. \fi}
  1699. {\if\edition\pythonEd\pythonColor
  1700. \[
  1701. \begin{array}{l}
  1702. \gray{\LintGrammarPython} \\ \hline
  1703. \LvarGrammarPython \\
  1704. \begin{array}{rcl}
  1705. \LangVarM{} &::=& \Stmt^{*}
  1706. \end{array}
  1707. \end{array}
  1708. \]
  1709. \fi}
  1710. \end{tcolorbox}
  1711. \caption{The concrete syntax of \LangVar{}.}
  1712. \label{fig:Lvar-concrete-syntax}
  1713. \end{figure}
  1714. \begin{figure}[tp]
  1715. \centering
  1716. \begin{tcolorbox}[colback=white]
  1717. {\if\edition\racketEd
  1718. \[
  1719. \begin{array}{l}
  1720. \gray{\LintASTRacket{}} \\ \hline
  1721. \LvarASTRacket \\
  1722. \begin{array}{rcl}
  1723. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1724. \end{array}
  1725. \end{array}
  1726. \]
  1727. \fi}
  1728. {\if\edition\pythonEd\pythonColor
  1729. \[
  1730. \begin{array}{l}
  1731. \gray{\LintASTPython}\\ \hline
  1732. \LvarASTPython \\
  1733. \begin{array}{rcl}
  1734. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1735. \end{array}
  1736. \end{array}
  1737. \]
  1738. \fi}
  1739. \end{tcolorbox}
  1740. \caption{The abstract syntax of \LangVar{}.}
  1741. \label{fig:Lvar-syntax}
  1742. \end{figure}
  1743. {\if\edition\racketEd
  1744. Let us dive further into the syntax and semantics of the \LangVar{}
  1745. language. The \key{let} feature defines a variable for use within its
  1746. body and initializes the variable with the value of an expression.
  1747. The abstract syntax for \key{let} is shown in
  1748. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1749. \begin{lstlisting}
  1750. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1751. \end{lstlisting}
  1752. For example, the following program initializes \code{x} to $32$ and then
  1753. evaluates the body \code{(+ 10 x)}, producing $42$.
  1754. \begin{lstlisting}
  1755. (let ([x (+ 12 20)]) (+ 10 x))
  1756. \end{lstlisting}
  1757. \fi}
  1758. %
  1759. {\if\edition\pythonEd\pythonColor
  1760. %
  1761. The \LangVar{} language includes an assignment statement, which defines a
  1762. variable for use in later statements and initializes the variable with
  1763. the value of an expression. The abstract syntax for assignment is
  1764. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1765. assignment is \index{subject}{Assign@\texttt{Assign}}
  1766. \begin{lstlisting}
  1767. |$\itm{var}$| = |$\itm{exp}$|
  1768. \end{lstlisting}
  1769. For example, the following program initializes the variable \code{x}
  1770. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1771. \begin{lstlisting}
  1772. x = 12 + 20
  1773. print(10 + x)
  1774. \end{lstlisting}
  1775. \fi}
  1776. {\if\edition\racketEd
  1777. %
  1778. When there are multiple \key{let}s for the same variable, the closest
  1779. enclosing \key{let} is used. That is, variable definitions overshadow
  1780. prior definitions. Consider the following program with two \key{let}s
  1781. that define two variables named \code{x}. Can you figure out the
  1782. result?
  1783. \begin{lstlisting}
  1784. (let ([x 32]) (+ (let ([x 10]) x) x))
  1785. \end{lstlisting}
  1786. For the purposes of depicting which variable occurrences correspond to
  1787. which definitions, the following shows the \code{x}'s annotated with
  1788. subscripts to distinguish them. Double-check that your answer for the
  1789. previous program is the same as your answer for this annotated version
  1790. of the program.
  1791. \begin{lstlisting}
  1792. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1793. \end{lstlisting}
  1794. The initializing expression is always evaluated before the body of the
  1795. \key{let}, so in the following, the \key{read} for \code{x} is
  1796. performed before the \key{read} for \code{y}. Given the input
  1797. $52$ then $10$, the following produces $42$ (not $-42$).
  1798. \begin{lstlisting}
  1799. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1800. \end{lstlisting}
  1801. \fi}
  1802. \subsection{Extensible Interpreters via Method Overriding}
  1803. \label{sec:extensible-interp}
  1804. \index{subject}{method overriding}
  1805. To prepare for discussing the interpreter of \LangVar{}, we explain
  1806. why we implement it in an object-oriented style. Throughout this book
  1807. we define many interpreters, one for each language that we
  1808. study. Because each language builds on the prior one, there is a lot
  1809. of commonality between these interpreters. We want to write down the
  1810. common parts just once instead of many times. A naive interpreter for
  1811. \LangVar{} would handle the \racket{cases for variables and
  1812. \code{let}} \python{case for variables} but dispatch to an
  1813. interpreter for \LangInt{} in the rest of the cases. The following
  1814. code sketches this idea. (We explain the \code{env} parameter in
  1815. section~\ref{sec:interp-Lvar}.)
  1816. \begin{center}
  1817. {\if\edition\racketEd
  1818. \begin{minipage}{0.45\textwidth}
  1819. \begin{lstlisting}
  1820. (define ((interp_Lint env) e)
  1821. (match e
  1822. [(Prim '- (list e1))
  1823. (fx- 0 ((interp_Lint env) e1))]
  1824. ...))
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \begin{minipage}{0.45\textwidth}
  1828. \begin{lstlisting}
  1829. (define ((interp_Lvar env) e)
  1830. (match e
  1831. [(Var x)
  1832. (dict-ref env x)]
  1833. [(Let x e body)
  1834. (define v ((interp_Lvar env) e))
  1835. (define env^ (dict-set env x v))
  1836. ((interp_Lvar env^) body)]
  1837. [else ((interp_Lint env) e)]))
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \fi}
  1841. {\if\edition\pythonEd\pythonColor
  1842. \begin{minipage}{0.45\textwidth}
  1843. \begin{lstlisting}
  1844. def interp_Lint(e, env):
  1845. match e:
  1846. case UnaryOp(USub(), e1):
  1847. return - interp_Lint(e1, env)
  1848. ...
  1849. \end{lstlisting}
  1850. \end{minipage}
  1851. \begin{minipage}{0.45\textwidth}
  1852. \begin{lstlisting}
  1853. def interp_Lvar(e, env):
  1854. match e:
  1855. case Name(id):
  1856. return env[id]
  1857. case _:
  1858. return interp_Lint(e, env)
  1859. \end{lstlisting}
  1860. \end{minipage}
  1861. \fi}
  1862. \end{center}
  1863. The problem with this naive approach is that it does not handle
  1864. situations in which an \LangVar{} feature, such as a variable, is
  1865. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1866. in the following program.
  1867. {\if\edition\racketEd
  1868. \begin{lstlisting}
  1869. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1870. \end{lstlisting}
  1871. \fi}
  1872. {\if\edition\pythonEd\pythonColor
  1873. \begin{minipage}{1.0\textwidth}
  1874. \begin{lstlisting}
  1875. y = 10
  1876. print(-y)
  1877. \end{lstlisting}
  1878. \end{minipage}
  1879. \fi}
  1880. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1881. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1882. then it recursively calls \code{interp\_Lint} again on its argument.
  1883. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1884. \code{interp\_Lint}, we get an error!
  1885. To make our interpreters extensible we need something called
  1886. \emph{open recursion}\index{subject}{open recursion}, in which the
  1887. tying of the recursive knot is delayed until the functions are
  1888. composed. Object-oriented languages provide open recursion via method
  1889. overriding. The following code uses
  1890. method overriding to interpret \LangInt{} and \LangVar{} using
  1891. %
  1892. \racket{the
  1893. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1894. \index{subject}{class} feature of Racket.}%
  1895. %
  1896. \python{Python \code{class} definitions.}
  1897. %
  1898. We define one class for each language and define a method for
  1899. interpreting expressions inside each class. The class for \LangVar{}
  1900. inherits from the class for \LangInt{}, and the method
  1901. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1902. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1903. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1904. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1905. \code{interp\_exp} in \LangInt{}.
  1906. \begin{center}
  1907. \hspace{-20pt}
  1908. {\if\edition\racketEd
  1909. \begin{minipage}{0.45\textwidth}
  1910. \begin{lstlisting}
  1911. (define interp-Lint-class
  1912. (class object%
  1913. (define/public ((interp_exp env) e)
  1914. (match e
  1915. [(Prim '- (list e))
  1916. (fx- 0 ((interp_exp env) e))]
  1917. ...))
  1918. ...))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \begin{minipage}{0.45\textwidth}
  1922. \begin{lstlisting}
  1923. (define interp-Lvar-class
  1924. (class interp-Lint-class
  1925. (define/override ((interp_exp env) e)
  1926. (match e
  1927. [(Var x)
  1928. (dict-ref env x)]
  1929. [(Let x e body)
  1930. (define v ((interp_exp env) e))
  1931. (define env^ (dict-set env x v))
  1932. ((interp_exp env^) body)]
  1933. [else
  1934. (super (interp_exp env) e)]))
  1935. ...
  1936. ))
  1937. \end{lstlisting}
  1938. \end{minipage}
  1939. \fi}
  1940. {\if\edition\pythonEd\pythonColor
  1941. \begin{minipage}{0.45\textwidth}
  1942. \begin{lstlisting}
  1943. class InterpLint:
  1944. def interp_exp(e):
  1945. match e:
  1946. case UnaryOp(USub(), e1):
  1947. return neg64(self.interp_exp(e1))
  1948. ...
  1949. ...
  1950. \end{lstlisting}
  1951. \end{minipage}
  1952. \begin{minipage}{0.45\textwidth}
  1953. \begin{lstlisting}
  1954. def InterpLvar(InterpLint):
  1955. def interp_exp(e):
  1956. match e:
  1957. case Name(id):
  1958. return env[id]
  1959. case _:
  1960. return super().interp_exp(e)
  1961. ...
  1962. \end{lstlisting}
  1963. \end{minipage}
  1964. \fi}
  1965. \end{center}
  1966. We return to the troublesome example, repeated here:
  1967. {\if\edition\racketEd
  1968. \begin{lstlisting}
  1969. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1970. \end{lstlisting}
  1971. \fi}
  1972. {\if\edition\pythonEd\pythonColor
  1973. \begin{lstlisting}
  1974. y = 10
  1975. print(-y)
  1976. \end{lstlisting}
  1977. \fi}
  1978. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1979. \racket{on this expression,}
  1980. \python{on the \code{-y} expression,}
  1981. %
  1982. which we call \code{e0}, by creating an object of the \LangVar{} class
  1983. and calling the \code{interp\_exp} method
  1984. {\if\edition\racketEd
  1985. \begin{lstlisting}
  1986. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1987. \end{lstlisting}
  1988. \fi}
  1989. {\if\edition\pythonEd\pythonColor
  1990. \begin{lstlisting}
  1991. InterpLvar().interp_exp(e0)
  1992. \end{lstlisting}
  1993. \fi}
  1994. \noindent To process the \code{-} operator, the default case of
  1995. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1996. method in \LangInt{}. But then for the recursive method call, it
  1997. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1998. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  1999. Thus, method overriding gives us the open recursion that we need to
  2000. implement our interpreters in an extensible way.
  2001. \subsection{Definitional Interpreter for \LangVar{}}
  2002. \label{sec:interp-Lvar}
  2003. Having justified the use of classes and methods to implement
  2004. interpreters, we revisit the definitional interpreter for \LangInt{}
  2005. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  2006. create an interpreter for \LangVar{}, shown in
  2007. figure~\ref{fig:interp-Lvar}.
  2008. %
  2009. \python{We change the \code{interp\_stmt} method in the interpreter
  2010. for \LangInt{} to take two extra parameters named \code{env}, which
  2011. we discuss in the next paragraph, and \code{cont} for
  2012. \emph{continuation}, which is the technical name for what comes
  2013. after a particular point in a program. The \code{cont} parameter is
  2014. the list of statements that follow the current statement. Note
  2015. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2016. statement and passes the rest of the statements as the argument for
  2017. \code{cont}. This organization enables each statement to decide what
  2018. if anything should be evaluated after it, for example, allowing a
  2019. \code{return} statement to exit early from a function (see
  2020. Chapter~\ref{ch:Lfun}).}
  2021. The interpreter for \LangVar{} adds two new cases for
  2022. variables and \racket{\key{let}}\python{assignment}. For
  2023. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2024. value bound to a variable to all the uses of the variable. To
  2025. accomplish this, we maintain a mapping from variables to values called
  2026. an \emph{environment}\index{subject}{environment}.
  2027. %
  2028. We use
  2029. %
  2030. \racket{an association list (alist) }%
  2031. %
  2032. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2033. %
  2034. to represent the environment.
  2035. %
  2036. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2037. and the \code{racket/dict} package.}
  2038. %
  2039. The \code{interp\_exp} function takes the current environment,
  2040. \code{env}, as an extra parameter. When the interpreter encounters a
  2041. variable, it looks up the corresponding value in the environment. If
  2042. the variable is not in the environment (because the variable was not
  2043. defined) then the lookup will fail and the interpreter will
  2044. halt with an error. Recall that the compiler is not obligated to
  2045. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2046. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2047. prohibit access to undefined variables.}
  2048. %
  2049. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2050. initializing expression, extends the environment with the result
  2051. value bound to the variable, using \code{dict-set}, then evaluates
  2052. the body of the \key{Let}.}
  2053. %
  2054. \python{When the interpreter encounters an assignment, it evaluates
  2055. the initializing expression and then associates the resulting value
  2056. with the variable in the environment.}
  2057. \begin{figure}[tp]
  2058. \begin{tcolorbox}[colback=white]
  2059. {\if\edition\racketEd
  2060. \begin{lstlisting}
  2061. (define interp-Lint-class
  2062. (class object%
  2063. (super-new)
  2064. (define/public ((interp_exp env) e)
  2065. (match e
  2066. [(Int n) n]
  2067. [(Prim 'read '())
  2068. (define r (read))
  2069. (cond [(fixnum? r) r]
  2070. [else (error 'interp_exp "expected an integer" r)])]
  2071. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2072. [(Prim '+ (list e1 e2))
  2073. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2074. [(Prim '- (list e1 e2))
  2075. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2076. (define/public (interp_program p)
  2077. (match p
  2078. [(Program '() e) ((interp_exp '()) e)]))
  2079. ))
  2080. \end{lstlisting}
  2081. \fi}
  2082. {\if\edition\pythonEd\pythonColor
  2083. \begin{lstlisting}
  2084. class InterpLint:
  2085. def interp_exp(self, e, env):
  2086. match e:
  2087. case BinOp(left, Add(), right):
  2088. l = self.interp_exp(left, env)
  2089. r = self.interp_exp(right, env)
  2090. return add64(l, r)
  2091. case BinOp(left, Sub(), right):
  2092. l = self.interp_exp(left, env)
  2093. r = self.interp_exp(right, env)
  2094. return sub64(l, r)
  2095. case UnaryOp(USub(), v):
  2096. return neg64(self.interp_exp(v, env))
  2097. case Constant(value):
  2098. return value
  2099. case Call(Name('input_int'), []):
  2100. return int(input())
  2101. def interp_stmt(self, s, env, cont):
  2102. match s:
  2103. case Expr(Call(Name('print'), [arg])):
  2104. val = self.interp_exp(arg, env)
  2105. print(val, end='')
  2106. return self.interp_stmts(cont, env)
  2107. case Expr(value):
  2108. self.interp_exp(value, env)
  2109. return self.interp_stmts(cont, env)
  2110. case _:
  2111. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2112. def interp_stmts(self, ss, env):
  2113. match ss:
  2114. case []:
  2115. return 0
  2116. case [s, *ss]:
  2117. return self.interp_stmt(s, env, ss)
  2118. def interp(self, p):
  2119. match p:
  2120. case Module(body):
  2121. self.interp_stmts(body, {})
  2122. def interp_Lint(p):
  2123. return InterpLint().interp(p)
  2124. \end{lstlisting}
  2125. \fi}
  2126. \end{tcolorbox}
  2127. \caption{Interpreter for \LangInt{} as a class.}
  2128. \label{fig:interp-Lint-class}
  2129. \end{figure}
  2130. \begin{figure}[tp]
  2131. \begin{tcolorbox}[colback=white]
  2132. {\if\edition\racketEd
  2133. \begin{lstlisting}
  2134. (define interp-Lvar-class
  2135. (class interp-Lint-class
  2136. (super-new)
  2137. (define/override ((interp_exp env) e)
  2138. (match e
  2139. [(Var x) (dict-ref env x)]
  2140. [(Let x e body)
  2141. (define new-env (dict-set env x ((interp_exp env) e)))
  2142. ((interp_exp new-env) body)]
  2143. [else ((super interp_exp env) e)]))
  2144. ))
  2145. (define (interp_Lvar p)
  2146. (send (new interp-Lvar-class) interp_program p))
  2147. \end{lstlisting}
  2148. \fi}
  2149. {\if\edition\pythonEd\pythonColor
  2150. \begin{lstlisting}
  2151. class InterpLvar(InterpLint):
  2152. def interp_exp(self, e, env):
  2153. match e:
  2154. case Name(id):
  2155. return env[id]
  2156. case _:
  2157. return super().interp_exp(e, env)
  2158. def interp_stmt(self, s, env, cont):
  2159. match s:
  2160. case Assign([Name(id)], value):
  2161. env[id] = self.interp_exp(value, env)
  2162. return self.interp_stmts(cont, env)
  2163. case _:
  2164. return super().interp_stmt(s, env, cont)
  2165. def interp_Lvar(p):
  2166. return InterpLvar().interp(p)
  2167. \end{lstlisting}
  2168. \fi}
  2169. \end{tcolorbox}
  2170. \caption{Interpreter for the \LangVar{} language.}
  2171. \label{fig:interp-Lvar}
  2172. \end{figure}
  2173. {\if\edition\racketEd
  2174. \begin{figure}[tp]
  2175. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2176. \small
  2177. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2178. An \emph{association list} (called an alist) is a list of key-value pairs.
  2179. For example, we can map people to their ages with an alist
  2180. \index{subject}{alist}\index{subject}{association list}
  2181. \begin{lstlisting}[basicstyle=\ttfamily]
  2182. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2183. \end{lstlisting}
  2184. The \emph{dictionary} interface is for mapping keys to values.
  2185. Every alist implements this interface. \index{subject}{dictionary}
  2186. The package
  2187. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2188. provides many functions for working with dictionaries, such as
  2189. \begin{description}
  2190. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2191. returns the value associated with the given $\itm{key}$.
  2192. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2193. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2194. and otherwise is the same as $\itm{dict}$.
  2195. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2196. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2197. of keys and values in $\itm{dict}$. For example, the following
  2198. creates a new alist in which the ages are incremented:
  2199. \end{description}
  2200. \vspace{-10pt}
  2201. \begin{lstlisting}[basicstyle=\ttfamily]
  2202. (for/list ([(k v) (in-dict ages)])
  2203. (cons k (add1 v)))
  2204. \end{lstlisting}
  2205. \end{tcolorbox}
  2206. %\end{wrapfigure}
  2207. \caption{Association lists implement the dictionary interface.}
  2208. \label{fig:alist}
  2209. \end{figure}
  2210. \fi}
  2211. The goal for this chapter is to implement a compiler that translates
  2212. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2213. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2214. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2215. That is, they output the same integer $n$. We depict this correctness
  2216. criteria in the following diagram:
  2217. \[
  2218. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2219. \node (p1) at (0, 0) {$P_1$};
  2220. \node (p2) at (4, 0) {$P_2$};
  2221. \node (o) at (4, -2) {$n$};
  2222. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2223. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2224. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2225. \end{tikzpicture}
  2226. \]
  2227. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2228. compiling \LangVar{}.
  2229. \section{The \LangXInt{} Assembly Language}
  2230. \label{sec:x86}
  2231. \index{subject}{x86}
  2232. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2233. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2234. assembler.
  2235. %
  2236. A program begins with a \code{main} label followed by a sequence of
  2237. instructions. The \key{globl} directive makes the \key{main} procedure
  2238. externally visible so that the operating system can call it.
  2239. %
  2240. An x86 program is stored in the computer's memory. For our purposes,
  2241. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2242. values. The computer has a \emph{program counter}
  2243. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2244. \code{rip} register that points to the address of the next instruction
  2245. to be executed. For most instructions, the program counter is
  2246. incremented after the instruction is executed so that it points to the
  2247. next instruction in memory. Most x86 instructions take two operands,
  2248. each of which is an integer constant (called an \emph{immediate
  2249. value}\index{subject}{immediate value}), a
  2250. \emph{register}\index{subject}{register}, or a memory location.
  2251. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2252. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2253. && \key{r8} \MID \key{r9} \MID \key{r10}
  2254. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2255. \MID \key{r14} \MID \key{r15}}
  2256. \newcommand{\GrammarXInt}{
  2257. \begin{array}{rcl}
  2258. \Reg &::=& \allregisters{} \\
  2259. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2260. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2261. \key{subq} \; \Arg\key{,} \Arg \MID
  2262. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2263. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2264. \key{callq} \; \mathit{label} \MID
  2265. \key{retq} \MID
  2266. \key{jmp}\,\itm{label} \MID \\
  2267. && \itm{label}\key{:}\; \Instr
  2268. \end{array}
  2269. }
  2270. \begin{figure}[tp]
  2271. \begin{tcolorbox}[colback=white]
  2272. {\if\edition\racketEd
  2273. \[
  2274. \begin{array}{l}
  2275. \GrammarXInt \\
  2276. \begin{array}{lcl}
  2277. \LangXIntM{} &::= & \key{.globl main}\\
  2278. & & \key{main:} \; \Instr\ldots
  2279. \end{array}
  2280. \end{array}
  2281. \]
  2282. \fi}
  2283. {\if\edition\pythonEd\pythonColor
  2284. \[
  2285. \begin{array}{lcl}
  2286. \Reg &::=& \allregisters{} \\
  2287. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2288. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2289. \key{subq} \; \Arg\key{,} \Arg \MID
  2290. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2291. && \key{callq} \; \mathit{label} \MID
  2292. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2293. \LangXIntM{} &::= & \key{.globl main}\\
  2294. & & \key{main:} \; \Instr^{*}
  2295. \end{array}
  2296. \]
  2297. \fi}
  2298. \end{tcolorbox}
  2299. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2300. \label{fig:x86-int-concrete}
  2301. \end{figure}
  2302. A register is a special kind of variable that holds a 64-bit
  2303. value. There are 16 general-purpose registers in the computer; their
  2304. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2305. written with a percent sign, \key{\%}, followed by its name,
  2306. for example \key{\%rax}.
  2307. An immediate value is written using the notation \key{\$}$n$ where $n$
  2308. is an integer.
  2309. %
  2310. %
  2311. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2312. which obtains the address stored in register $r$ and then adds $n$
  2313. bytes to the address. The resulting address is used to load or to store
  2314. to memory depending on whether it occurs as a source or destination
  2315. argument of an instruction.
  2316. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2317. the source $s$ and destination $d$, applies the arithmetic operation,
  2318. and then writes the result to the destination $d$. \index{subject}{instruction}
  2319. %
  2320. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2321. stores the result in $d$.
  2322. %
  2323. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2324. specified by the label, and $\key{retq}$ returns from a procedure to
  2325. its caller.
  2326. %
  2327. We discuss procedure calls in more detail further in this chapter and
  2328. in chapter~\ref{ch:Lfun}.
  2329. %
  2330. The last letter \key{q} indicates that these instructions operate on
  2331. quadwords, which are 64-bit values.
  2332. %
  2333. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2334. counter to the address of the instruction immediately after the
  2335. specified label.}
  2336. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2337. all the x86 instructions used in this book.
  2338. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2339. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2340. \lstinline{movq $10, %rax}
  2341. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2342. adds $32$ to the $10$ in \key{rax} and
  2343. puts the result, $42$, into \key{rax}.
  2344. %
  2345. The last instruction \key{retq} finishes the \key{main} function by
  2346. returning the integer in \key{rax} to the operating system. The
  2347. operating system interprets this integer as the program's exit
  2348. code. By convention, an exit code of 0 indicates that a program has
  2349. completed successfully, and all other exit codes indicate various
  2350. errors.
  2351. %
  2352. \racket{However, in this book we return the result of the program
  2353. as the exit code.}
  2354. \begin{figure}[tbp]
  2355. \begin{minipage}{0.45\textwidth}
  2356. \begin{tcolorbox}[colback=white]
  2357. \begin{lstlisting}
  2358. .globl main
  2359. main:
  2360. movq $10, %rax
  2361. addq $32, %rax
  2362. retq
  2363. \end{lstlisting}
  2364. \end{tcolorbox}
  2365. \end{minipage}
  2366. \caption{An x86 program that computes
  2367. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2368. \label{fig:p0-x86}
  2369. \end{figure}
  2370. We exhibit the use of memory for storing intermediate results in the
  2371. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2372. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2373. uses a region of memory called the \emph{procedure call stack}
  2374. (\emph{stack} for
  2375. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2376. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2377. for each procedure call. The memory layout for an individual frame is
  2378. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2379. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2380. address of the item at the top of the stack. In general, we use the
  2381. term \emph{pointer}\index{subject}{pointer} for something that
  2382. contains an address. The stack grows downward in memory, so we
  2383. increase the size of the stack by subtracting from the stack pointer.
  2384. In the context of a procedure call, the \emph{return
  2385. address}\index{subject}{return address} is the location of the
  2386. instruction that immediately follows the call instruction on the
  2387. caller side. The function call instruction, \code{callq}, pushes the
  2388. return address onto the stack prior to jumping to the procedure. The
  2389. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2390. pointer} and is used to access variables that are stored in the
  2391. frame of the current procedure call. The base pointer of the caller
  2392. is stored immediately after the return address.
  2393. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2394. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2395. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2396. $-16\key{(\%rbp)}$, and so on.
  2397. \begin{figure}[tbp]
  2398. \begin{minipage}{0.66\textwidth}
  2399. \begin{tcolorbox}[colback=white]
  2400. {\if\edition\racketEd
  2401. \begin{lstlisting}
  2402. start:
  2403. movq $10, -8(%rbp)
  2404. negq -8(%rbp)
  2405. movq -8(%rbp), %rax
  2406. addq $52, %rax
  2407. jmp conclusion
  2408. .globl main
  2409. main:
  2410. pushq %rbp
  2411. movq %rsp, %rbp
  2412. subq $16, %rsp
  2413. jmp start
  2414. conclusion:
  2415. addq $16, %rsp
  2416. popq %rbp
  2417. retq
  2418. \end{lstlisting}
  2419. \fi}
  2420. {\if\edition\pythonEd\pythonColor
  2421. \begin{lstlisting}
  2422. .globl main
  2423. main:
  2424. pushq %rbp
  2425. movq %rsp, %rbp
  2426. subq $16, %rsp
  2427. movq $10, -8(%rbp)
  2428. negq -8(%rbp)
  2429. movq -8(%rbp), %rax
  2430. addq $52, %rax
  2431. addq $16, %rsp
  2432. popq %rbp
  2433. retq
  2434. \end{lstlisting}
  2435. \fi}
  2436. \end{tcolorbox}
  2437. \end{minipage}
  2438. \caption{An x86 program that computes
  2439. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2440. \label{fig:p1-x86}
  2441. \end{figure}
  2442. \begin{figure}[tbp]
  2443. \begin{minipage}{0.66\textwidth}
  2444. \begin{tcolorbox}[colback=white]
  2445. \centering
  2446. \begin{tabular}{|r|l|} \hline
  2447. Position & Contents \\ \hline
  2448. $8$(\key{\%rbp}) & return address \\
  2449. $0$(\key{\%rbp}) & old \key{rbp} \\
  2450. $-8$(\key{\%rbp}) & variable $1$ \\
  2451. $-16$(\key{\%rbp}) & variable $2$ \\
  2452. \ldots & \ldots \\
  2453. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2454. \end{tabular}
  2455. \end{tcolorbox}
  2456. \end{minipage}
  2457. \caption{Memory layout of a frame.}
  2458. \label{fig:frame}
  2459. \end{figure}
  2460. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2461. is transferred from the operating system to the \code{main} function.
  2462. The operating system issues a \code{callq main} instruction that
  2463. pushes its return address on the stack and then jumps to
  2464. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2465. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2466. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2467. out of alignment (because the \code{callq} pushed the return address).
  2468. The first three instructions are the typical
  2469. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2470. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2471. pointer \code{rsp} and then saves the base pointer of the caller at
  2472. address \code{rsp} on the stack. The next instruction \code{movq
  2473. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2474. which is pointing to the location of the old base pointer. The
  2475. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2476. make enough room for storing variables. This program needs one
  2477. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2478. 16-byte-aligned, and then we are ready to make calls to other functions.
  2479. \racket{The last instruction of the prelude is \code{jmp start}, which
  2480. transfers control to the instructions that were generated from the
  2481. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2482. \racket{The first instruction under the \code{start} label is}
  2483. %
  2484. \python{The first instruction after the prelude is}
  2485. %
  2486. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2487. %
  2488. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2489. $1$ to $-10$.
  2490. %
  2491. The next instruction moves the $-10$ from variable $1$ into the
  2492. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2493. the value in \code{rax}, updating its contents to $42$.
  2494. \racket{The three instructions under the label \code{conclusion} are the
  2495. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2496. %
  2497. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2498. \code{main} function consists of the last three instructions.}
  2499. %
  2500. The first two restore the \code{rsp} and \code{rbp} registers to their
  2501. states at the beginning of the procedure. In particular,
  2502. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2503. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2504. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2505. \key{retq}, jumps back to the procedure that called this one and adds
  2506. $8$ to the stack pointer.
  2507. Our compiler needs a convenient representation for manipulating x86
  2508. programs, so we define an abstract syntax for x86, shown in
  2509. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2510. \LangXInt{}.
  2511. %
  2512. {\if\edition\pythonEd\pythonColor%
  2513. The main difference between this and the concrete syntax of \LangXInt{}
  2514. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2515. names, and register names are explicitly represented by strings.
  2516. \fi} %
  2517. {\if\edition\racketEd
  2518. The main difference between this and the concrete syntax of \LangXInt{}
  2519. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2520. front of every instruction. Instead instructions are grouped into
  2521. \emph{basic blocks}\index{subject}{basic block} with a
  2522. label associated with every basic block; this is why the \key{X86Program}
  2523. struct includes an alist mapping labels to basic blocks. The reason for this
  2524. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2525. introduce conditional branching. The \code{Block} structure includes
  2526. an $\itm{info}$ field that is not needed in this chapter but becomes
  2527. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2528. $\itm{info}$ field should contain an empty list.
  2529. \fi}
  2530. %
  2531. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2532. node includes an integer for representing the arity of the function,
  2533. that is, the number of arguments, which is helpful to know during
  2534. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2535. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2536. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2537. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2538. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2539. \MID \skey{r14} \MID \skey{r15}}
  2540. \newcommand{\ASTXIntRacket}{
  2541. \begin{array}{lcl}
  2542. \Reg &::=& \allregisters{} \\
  2543. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2544. \MID \DEREF{\Reg}{\Int} \\
  2545. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2546. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2547. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2548. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2549. &\MID& \PUSHQ{\Arg}
  2550. \MID \POPQ{\Arg} \\
  2551. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2552. \MID \RETQ{}
  2553. \MID \JMP{\itm{label}} \\
  2554. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2555. \end{array}
  2556. }
  2557. \newcommand{\ASTXIntPython}{
  2558. \begin{array}{lcl}
  2559. \Reg &::=& \allregisters{} \\
  2560. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2561. \MID \DEREF{\Reg}{\Int} \\
  2562. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2563. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2564. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2565. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2566. &\MID& \PUSHQ{\Arg}
  2567. \MID \POPQ{\Arg} \\
  2568. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2569. \MID \RETQ{}
  2570. \MID \JMP{\itm{label}} \\
  2571. \Block &::= & \Instr^{+}
  2572. \end{array}
  2573. }
  2574. \begin{figure}[tp]
  2575. \begin{tcolorbox}[colback=white]
  2576. \small
  2577. {\if\edition\racketEd
  2578. \[\arraycolsep=3pt
  2579. \begin{array}{l}
  2580. \ASTXIntRacket \\
  2581. \begin{array}{lcl}
  2582. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2583. \end{array}
  2584. \end{array}
  2585. \]
  2586. \fi}
  2587. {\if\edition\pythonEd\pythonColor
  2588. \[
  2589. \begin{array}{lcl}
  2590. \Reg &::=& \allastregisters{} \\
  2591. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2592. \MID \DEREF{\Reg}{\Int} \\
  2593. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2594. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2595. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2596. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2597. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2598. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2599. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2600. \end{array}
  2601. \]
  2602. \fi}
  2603. \end{tcolorbox}
  2604. \caption{The abstract syntax of \LangXInt{} assembly.}
  2605. \label{fig:x86-int-ast}
  2606. \end{figure}
  2607. \section{Planning the Trip to x86}
  2608. \label{sec:plan-s0-x86}
  2609. To compile one language to another, it helps to focus on the
  2610. differences between the two languages because the compiler will need
  2611. to bridge those differences. What are the differences between \LangVar{}
  2612. and x86 assembly? Here are some of the most important ones:
  2613. \begin{enumerate}
  2614. \item x86 arithmetic instructions typically have two arguments and
  2615. update the second argument in place. In contrast, \LangVar{}
  2616. arithmetic operations take two arguments and produce a new value.
  2617. An x86 instruction may have at most one memory-accessing argument.
  2618. Furthermore, some x86 instructions place special restrictions on
  2619. their arguments.
  2620. \item An argument of an \LangVar{} operator can be a deeply nested
  2621. expression, whereas x86 instructions restrict their arguments to be
  2622. integer constants, registers, and memory locations.
  2623. {\if\edition\racketEd
  2624. \item The order of execution in x86 is explicit in the syntax, which
  2625. is a sequence of instructions and jumps to labeled positions,
  2626. whereas in \LangVar{} the order of evaluation is a left-to-right
  2627. depth-first traversal of the abstract syntax tree. \fi}
  2628. \item A program in \LangVar{} can have any number of variables,
  2629. whereas x86 has 16 registers and the procedure call stack.
  2630. {\if\edition\racketEd
  2631. \item Variables in \LangVar{} can shadow other variables with the
  2632. same name. In x86, registers have unique names, and memory locations
  2633. have unique addresses.
  2634. \fi}
  2635. \end{enumerate}
  2636. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2637. down the problem into several steps, which deal with these differences
  2638. one at a time. Each of these steps is called a \emph{pass} of the
  2639. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2640. %
  2641. This term indicates that each step passes over, or traverses, the AST
  2642. of the program.
  2643. %
  2644. Furthermore, we follow the nanopass approach, which means that we
  2645. strive for each pass to accomplish one clear objective rather than two
  2646. or three at the same time.
  2647. %
  2648. We begin by sketching how we might implement each pass and give each
  2649. pass a name. We then figure out an ordering of the passes and the
  2650. input/output language for each pass. The very first pass has
  2651. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2652. its output language. In between these two passes, we can choose
  2653. whichever language is most convenient for expressing the output of
  2654. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2655. \emph{intermediate language} of our own design. Finally, to
  2656. implement each pass we write one recursive function per nonterminal in
  2657. the grammar of the input language of the pass.
  2658. \index{subject}{intermediate language}
  2659. Our compiler for \LangVar{} consists of the following passes:
  2660. %
  2661. \begin{description}
  2662. {\if\edition\racketEd
  2663. \item[\key{uniquify}] deals with the shadowing of variables by
  2664. renaming every variable to a unique name.
  2665. \fi}
  2666. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2667. of a primitive operation or function call is a variable or integer,
  2668. that is, an \emph{atomic} expression. We refer to nonatomic
  2669. expressions as \emph{complex}. This pass introduces temporary
  2670. variables to hold the results of complex
  2671. subexpressions.\index{subject}{atomic
  2672. expression}\index{subject}{complex expression}%
  2673. {\if\edition\racketEd
  2674. \item[\key{explicate\_control}] makes the execution order of the
  2675. program explicit. It converts the abstract syntax tree
  2676. representation into a graph in which each node is a labeled sequence
  2677. of statements and the edges are \code{goto} statements.
  2678. \fi}
  2679. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2680. handles the difference between
  2681. \LangVar{} operations and x86 instructions. This pass converts each
  2682. \LangVar{} operation to a short sequence of instructions that
  2683. accomplishes the same task.
  2684. \item[\key{assign\_homes}] replaces variables with registers or stack
  2685. locations.
  2686. \end{description}
  2687. %
  2688. {\if\edition\racketEd
  2689. %
  2690. Our treatment of \code{remove\_complex\_operands} and
  2691. \code{explicate\_control} as separate passes is an example of the
  2692. nanopass approach.\footnote{For analogous decompositions of the
  2693. translation into continuation passing style, see the work of
  2694. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2695. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2696. %
  2697. \fi}
  2698. The next question is, in what order should we apply these passes? This
  2699. question can be challenging because it is difficult to know ahead of
  2700. time which orderings will be better (that is, will be easier to
  2701. implement, produce more efficient code, and so on), and therefore
  2702. ordering often involves trial and error. Nevertheless, we can plan
  2703. ahead and make educated choices regarding the ordering.
  2704. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2705. \key{uniquify}? The \key{uniquify} pass should come first because
  2706. \key{explicate\_control} changes all the \key{let}-bound variables to
  2707. become local variables whose scope is the entire program, which would
  2708. confuse variables with the same name.}
  2709. %
  2710. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2711. because the later removes the \key{let} form, but it is convenient to
  2712. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2713. %
  2714. \racket{The ordering of \key{uniquify} with respect to
  2715. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2716. \key{uniquify} to come first.}
  2717. The \key{select\_instructions} and \key{assign\_homes} passes are
  2718. intertwined.
  2719. %
  2720. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2721. passing arguments to functions and that it is preferable to assign
  2722. parameters to their corresponding registers. This suggests that it
  2723. would be better to start with the \key{select\_instructions} pass,
  2724. which generates the instructions for argument passing, before
  2725. performing register allocation.
  2726. %
  2727. On the other hand, by selecting instructions first we may run into a
  2728. dead end in \key{assign\_homes}. Recall that only one argument of an
  2729. x86 instruction may be a memory access, but \key{assign\_homes} might
  2730. be forced to assign both arguments to memory locations.
  2731. %
  2732. A sophisticated approach is to repeat the two passes until a solution
  2733. is found. However, to reduce implementation complexity we recommend
  2734. placing \key{select\_instructions} first, followed by the
  2735. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2736. that uses a reserved register to fix outstanding problems.
  2737. \begin{figure}[tbp]
  2738. \begin{tcolorbox}[colback=white]
  2739. {\if\edition\racketEd
  2740. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2741. \node (Lvar) at (0,2) {\large \LangVar{}};
  2742. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2743. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2744. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2745. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2746. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2747. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2748. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2749. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2750. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2751. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2752. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2753. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2754. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2755. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2756. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2757. \end{tikzpicture}
  2758. \fi}
  2759. {\if\edition\pythonEd\pythonColor
  2760. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2761. \node (Lvar) at (0,2) {\large \LangVar{}};
  2762. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2763. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2764. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2765. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2766. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2767. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2768. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2769. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2770. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2771. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2772. \end{tikzpicture}
  2773. \fi}
  2774. \end{tcolorbox}
  2775. \caption{Diagram of the passes for compiling \LangVar{}. }
  2776. \label{fig:Lvar-passes}
  2777. \end{figure}
  2778. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2779. passes and identifies the input and output language of each pass.
  2780. %
  2781. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2782. language, which extends \LangXInt{} with an unbounded number of
  2783. program-scope variables and removes the restrictions regarding
  2784. instruction arguments.
  2785. %
  2786. The last pass, \key{prelude\_and\_conclusion}, places the program
  2787. instructions inside a \code{main} function with instructions for the
  2788. prelude and conclusion.
  2789. %
  2790. \racket{In the next section we discuss the \LangCVar{} intermediate
  2791. language that serves as the output of \code{explicate\_control}.}
  2792. %
  2793. The remainder of this chapter provides guidance on the implementation
  2794. of each of the compiler passes represented in
  2795. figure~\ref{fig:Lvar-passes}.
  2796. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2797. %% are programs that are still in the \LangVar{} language, though the
  2798. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2799. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2800. %% %
  2801. %% The output of \code{explicate\_control} is in an intermediate language
  2802. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2803. %% syntax, which we introduce in the next section. The
  2804. %% \key{select-instruction} pass translates from \LangCVar{} to
  2805. %% \LangXVar{}. The \key{assign-homes} and
  2806. %% \key{patch-instructions}
  2807. %% passes input and output variants of x86 assembly.
  2808. \newcommand{\CvarGrammarRacket}{
  2809. \begin{array}{lcl}
  2810. \Atm &::=& \Int \MID \Var \\
  2811. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2812. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2813. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2814. \end{array}
  2815. }
  2816. \newcommand{\CvarASTRacket}{
  2817. \begin{array}{lcl}
  2818. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2819. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2820. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2821. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2822. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2823. \end{array}
  2824. }
  2825. {\if\edition\racketEd
  2826. \subsection{The \LangCVar{} Intermediate Language}
  2827. The output of \code{explicate\_control} is similar to the C
  2828. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2829. categories for expressions and statements, so we name it \LangCVar{}.
  2830. This style of intermediate language is also known as
  2831. \emph{three-address code}, to emphasize that the typical form of a
  2832. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2833. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2834. The concrete syntax for \LangCVar{} is shown in
  2835. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2836. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2837. %
  2838. The \LangCVar{} language supports the same operators as \LangVar{} but
  2839. the arguments of operators are restricted to atomic
  2840. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2841. assignment statements that can be executed in sequence using the
  2842. \key{Seq} form. A sequence of statements always ends with
  2843. \key{Return}, a guarantee that is baked into the grammar rules for
  2844. \itm{tail}. The naming of this nonterminal comes from the term
  2845. \emph{tail position}\index{subject}{tail position}, which refers to an
  2846. expression that is the last one to execute within a function or
  2847. program.
  2848. A \LangCVar{} program consists of an alist mapping labels to
  2849. tails. This is more general than necessary for the present chapter, as
  2850. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2851. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2852. there is just one label, \key{start}, and the whole program is
  2853. its tail.
  2854. %
  2855. The $\itm{info}$ field of the \key{CProgram} form, after the
  2856. \code{explicate\_control} pass, contains an alist that associates the
  2857. symbol \key{locals} with a list of all the variables used in the
  2858. program. At the start of the program, these variables are
  2859. uninitialized; they become initialized on their first assignment.
  2860. \begin{figure}[tbp]
  2861. \begin{tcolorbox}[colback=white]
  2862. \[
  2863. \begin{array}{l}
  2864. \CvarGrammarRacket \\
  2865. \begin{array}{lcl}
  2866. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2867. \end{array}
  2868. \end{array}
  2869. \]
  2870. \end{tcolorbox}
  2871. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2872. \label{fig:c0-concrete-syntax}
  2873. \end{figure}
  2874. \begin{figure}[tbp]
  2875. \begin{tcolorbox}[colback=white]
  2876. \[
  2877. \begin{array}{l}
  2878. \CvarASTRacket \\
  2879. \begin{array}{lcl}
  2880. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2881. \end{array}
  2882. \end{array}
  2883. \]
  2884. \end{tcolorbox}
  2885. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2886. \label{fig:c0-syntax}
  2887. \end{figure}
  2888. The definitional interpreter for \LangCVar{} is in the support code,
  2889. in the file \code{interp-Cvar.rkt}.
  2890. \fi}
  2891. {\if\edition\racketEd
  2892. \section{Uniquify Variables}
  2893. \label{sec:uniquify-Lvar}
  2894. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2895. with a unique name. Both the input and output of the \code{uniquify}
  2896. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2897. should translate the program on the left into the program on the
  2898. right.
  2899. \begin{transformation}
  2900. \begin{lstlisting}
  2901. (let ([x 32])
  2902. (+ (let ([x 10]) x) x))
  2903. \end{lstlisting}
  2904. \compilesto
  2905. \begin{lstlisting}
  2906. (let ([x.1 32])
  2907. (+ (let ([x.2 10]) x.2) x.1))
  2908. \end{lstlisting}
  2909. \end{transformation}
  2910. The following is another example translation, this time of a program
  2911. with a \key{let} nested inside the initializing expression of another
  2912. \key{let}.
  2913. \begin{transformation}
  2914. \begin{lstlisting}
  2915. (let ([x (let ([x 4])
  2916. (+ x 1))])
  2917. (+ x 2))
  2918. \end{lstlisting}
  2919. \compilesto
  2920. \begin{lstlisting}
  2921. (let ([x.2 (let ([x.1 4])
  2922. (+ x.1 1))])
  2923. (+ x.2 2))
  2924. \end{lstlisting}
  2925. \end{transformation}
  2926. We recommend implementing \code{uniquify} by creating a structurally
  2927. recursive function named \code{uniquify\_exp} that does little other
  2928. than copy an expression. However, when encountering a \key{let}, it
  2929. should generate a unique name for the variable and associate the old
  2930. name with the new name in an alist.\footnote{The Racket function
  2931. \code{gensym} is handy for generating unique variable names.} The
  2932. \code{uniquify\_exp} function needs to access this alist when it gets
  2933. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2934. for the alist.
  2935. The skeleton of the \code{uniquify\_exp} function is shown in
  2936. figure~\ref{fig:uniquify-Lvar}.
  2937. %% The function is curried so that it is
  2938. %% convenient to partially apply it to an alist and then apply it to
  2939. %% different expressions, as in the last case for primitive operations in
  2940. %% figure~\ref{fig:uniquify-Lvar}.
  2941. The
  2942. %
  2943. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2944. %
  2945. form of Racket is useful for transforming the element of a list to
  2946. produce a new list.\index{subject}{for/list}
  2947. \begin{figure}[tbp]
  2948. \begin{tcolorbox}[colback=white]
  2949. \begin{lstlisting}
  2950. (define (uniquify_exp env)
  2951. (lambda (e)
  2952. (match e
  2953. [(Var x) ___]
  2954. [(Int n) (Int n)]
  2955. [(Let x e body) ___]
  2956. [(Prim op es)
  2957. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2958. (define (uniquify p)
  2959. (match p
  2960. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2961. \end{lstlisting}
  2962. \end{tcolorbox}
  2963. \caption{Skeleton for the \key{uniquify} pass.}
  2964. \label{fig:uniquify-Lvar}
  2965. \end{figure}
  2966. \begin{exercise}
  2967. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2968. Complete the \code{uniquify} pass by filling in the blanks in
  2969. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2970. variables and for the \key{let} form in the file \code{compiler.rkt}
  2971. in the support code.
  2972. \end{exercise}
  2973. \begin{exercise}
  2974. \normalfont\normalsize
  2975. \label{ex:Lvar}
  2976. Create five \LangVar{} programs that exercise the most interesting
  2977. parts of the \key{uniquify} pass; that is, the programs should include
  2978. \key{let} forms, variables, and variables that shadow each other.
  2979. The five programs should be placed in the subdirectory named
  2980. \key{tests}, and the file names should start with \code{var\_test\_}
  2981. followed by a unique integer and end with the file extension
  2982. \key{.rkt}.
  2983. %
  2984. The \key{run-tests.rkt} script in the support code checks whether the
  2985. output programs produce the same result as the input programs. The
  2986. script uses the \key{interp-tests} function
  2987. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2988. your \key{uniquify} pass on the example programs. The \code{passes}
  2989. parameter of \key{interp-tests} is a list that should have one entry
  2990. for each pass in your compiler. For now, define \code{passes} to
  2991. contain just one entry for \code{uniquify} as follows:
  2992. \begin{lstlisting}
  2993. (define passes
  2994. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2995. \end{lstlisting}
  2996. Run the \key{run-tests.rkt} script in the support code to check
  2997. whether the output programs produce the same result as the input
  2998. programs.
  2999. \end{exercise}
  3000. \fi}
  3001. \section{Remove Complex Operands}
  3002. \label{sec:remove-complex-opera-Lvar}
  3003. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3004. into a restricted form in which the arguments of operations are atomic
  3005. expressions. Put another way, this pass removes complex
  3006. operands\index{subject}{complex operand}, such as the expression
  3007. \racket{\code{(- 10)}}\python{\code{-10}}
  3008. in the following program. This is accomplished by introducing a new
  3009. temporary variable, assigning the complex operand to the new
  3010. variable, and then using the new variable in place of the complex
  3011. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3012. right.
  3013. {\if\edition\racketEd
  3014. \begin{transformation}
  3015. % var_test_19.rkt
  3016. \begin{lstlisting}
  3017. (let ([x (+ 42 (- 10))])
  3018. (+ x 10))
  3019. \end{lstlisting}
  3020. \compilesto
  3021. \begin{lstlisting}
  3022. (let ([x (let ([tmp.1 (- 10)])
  3023. (+ 42 tmp.1))])
  3024. (+ x 10))
  3025. \end{lstlisting}
  3026. \end{transformation}
  3027. \fi}
  3028. {\if\edition\pythonEd\pythonColor
  3029. \begin{transformation}
  3030. \begin{lstlisting}
  3031. x = 42 + -10
  3032. print(x + 10)
  3033. \end{lstlisting}
  3034. \compilesto
  3035. \begin{lstlisting}
  3036. tmp_0 = -10
  3037. x = 42 + tmp_0
  3038. tmp_1 = x + 10
  3039. print(tmp_1)
  3040. \end{lstlisting}
  3041. \end{transformation}
  3042. \fi}
  3043. \newcommand{\LvarMonadASTRacket}{
  3044. \begin{array}{rcl}
  3045. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3046. \Exp &::=& \Atm \MID \READ{} \\
  3047. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3048. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3049. \end{array}
  3050. }
  3051. \newcommand{\LvarMonadASTPython}{
  3052. \begin{array}{rcl}
  3053. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3054. \Exp{} &::=& \Atm \MID \READ{} \\
  3055. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3056. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3057. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3058. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3059. \end{array}
  3060. }
  3061. \begin{figure}[tp]
  3062. \centering
  3063. \begin{tcolorbox}[colback=white]
  3064. {\if\edition\racketEd
  3065. \[
  3066. \begin{array}{l}
  3067. \LvarMonadASTRacket \\
  3068. \begin{array}{rcl}
  3069. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3070. \end{array}
  3071. \end{array}
  3072. \]
  3073. \fi}
  3074. {\if\edition\pythonEd\pythonColor
  3075. \[
  3076. \begin{array}{l}
  3077. \LvarMonadASTPython \\
  3078. \begin{array}{rcl}
  3079. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3080. \end{array}
  3081. \end{array}
  3082. \]
  3083. \fi}
  3084. \end{tcolorbox}
  3085. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3086. atomic expressions.}
  3087. \label{fig:Lvar-anf-syntax}
  3088. \end{figure}
  3089. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3090. of this pass, the language \LangVarANF{}. The only difference is that
  3091. operator arguments are restricted to be atomic expressions that are
  3092. defined by the \Atm{} nonterminal. In particular, integer constants
  3093. and variables are atomic.
  3094. The atomic expressions are pure (they do not cause or depend on side
  3095. effects) whereas complex expressions may have side effects, such as
  3096. \READ{}. A language with this separation between pure expressions
  3097. versus expressions with side effects is said to be in monadic normal
  3098. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3099. in the name \LangVarANF{}. An important invariant of the
  3100. \code{remove\_complex\_operands} pass is that the relative ordering
  3101. among complex expressions is not changed, but the relative ordering
  3102. between atomic expressions and complex expressions can change and
  3103. often does. These changes are behavior preserving because
  3104. atomic expressions are pure.
  3105. {\if\edition\racketEd
  3106. Another well-known form for intermediate languages is the
  3107. \emph{administrative normal form}
  3108. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3109. \index{subject}{administrative normal form} \index{subject}{ANF}
  3110. %
  3111. The \LangVarANF{} language is not quite in ANF because it allows the
  3112. right-hand side of a \code{let} to be a complex expression, such as
  3113. another \code{let}. The flattening of nested \code{let} expressions is
  3114. instead one of the responsibilities of the \code{explicate\_control}
  3115. pass.
  3116. \fi}
  3117. {\if\edition\racketEd
  3118. We recommend implementing this pass with two mutually recursive
  3119. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3120. \code{rco\_atom} to subexpressions that need to become atomic and to
  3121. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3122. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3123. returns an expression. The \code{rco\_atom} function returns two
  3124. things: an atomic expression and an alist mapping temporary variables to
  3125. complex subexpressions. You can return multiple things from a function
  3126. using Racket's \key{values} form, and you can receive multiple things
  3127. from a function call using the \key{define-values} form.
  3128. \fi}
  3129. %
  3130. {\if\edition\pythonEd\pythonColor
  3131. %
  3132. We recommend implementing this pass with an auxiliary method named
  3133. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3134. Boolean that specifies whether the expression needs to become atomic
  3135. or not. The \code{rco\_exp} method should return a pair consisting of
  3136. the new expression and a list of pairs, associating new temporary
  3137. variables with their initializing expressions.
  3138. %
  3139. \fi}
  3140. {\if\edition\racketEd
  3141. %
  3142. In the example program with the expression \code{(+ 42 (-
  3143. 10))}, the subexpression \code{(- 10)} should be processed using the
  3144. \code{rco\_atom} function because it is an argument of the \code{+}
  3145. operator and therefore needs to become atomic. The output of
  3146. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3147. \begin{transformation}
  3148. \begin{lstlisting}
  3149. (- 10)
  3150. \end{lstlisting}
  3151. \compilesto
  3152. \begin{lstlisting}
  3153. tmp.1
  3154. ((tmp.1 . (- 10)))
  3155. \end{lstlisting}
  3156. \end{transformation}
  3157. \fi}
  3158. %
  3159. {\if\edition\pythonEd\pythonColor
  3160. %
  3161. Returning to the example program with the expression \code{42 + -10},
  3162. the subexpression \code{-10} should be processed using the
  3163. \code{rco\_exp} function with \code{True} as the second argument,
  3164. because \code{-10} is an argument of the \code{+} operator and
  3165. therefore needs to become atomic. The output of \code{rco\_exp}
  3166. applied to \code{-10} is as follows.
  3167. \begin{transformation}
  3168. \begin{lstlisting}
  3169. -10
  3170. \end{lstlisting}
  3171. \compilesto
  3172. \begin{lstlisting}
  3173. tmp_1
  3174. [(tmp_1, -10)]
  3175. \end{lstlisting}
  3176. \end{transformation}
  3177. %
  3178. \fi}
  3179. Take special care of programs, such as the following, that
  3180. %
  3181. \racket{bind a variable to an atomic expression.}
  3182. %
  3183. \python{assign an atomic expression to a variable.}
  3184. %
  3185. You should leave such \racket{variable bindings}\python{assignments}
  3186. unchanged, as shown in the program on the right:\\
  3187. %
  3188. {\if\edition\racketEd
  3189. \begin{transformation}
  3190. % var_test_20.rkt
  3191. \begin{lstlisting}
  3192. (let ([a 42])
  3193. (let ([b a])
  3194. b))
  3195. \end{lstlisting}
  3196. \compilesto
  3197. \begin{lstlisting}
  3198. (let ([a 42])
  3199. (let ([b a])
  3200. b))
  3201. \end{lstlisting}
  3202. \end{transformation}
  3203. \fi}
  3204. {\if\edition\pythonEd\pythonColor
  3205. \begin{transformation}
  3206. \begin{lstlisting}
  3207. a = 42
  3208. b = a
  3209. print(b)
  3210. \end{lstlisting}
  3211. \compilesto
  3212. \begin{lstlisting}
  3213. a = 42
  3214. b = a
  3215. print(b)
  3216. \end{lstlisting}
  3217. \end{transformation}
  3218. \fi}
  3219. %
  3220. \noindent A careless implementation might produce the following output with
  3221. unnecessary temporary variables.
  3222. \begin{center}
  3223. \begin{minipage}{0.4\textwidth}
  3224. {\if\edition\racketEd
  3225. \begin{lstlisting}
  3226. (let ([tmp.1 42])
  3227. (let ([a tmp.1])
  3228. (let ([tmp.2 a])
  3229. (let ([b tmp.2])
  3230. b))))
  3231. \end{lstlisting}
  3232. \fi}
  3233. {\if\edition\pythonEd\pythonColor
  3234. \begin{lstlisting}
  3235. tmp_1 = 42
  3236. a = tmp_1
  3237. tmp_2 = a
  3238. b = tmp_2
  3239. print(b)
  3240. \end{lstlisting}
  3241. \fi}
  3242. \end{minipage}
  3243. \end{center}
  3244. \begin{exercise}
  3245. \normalfont\normalsize
  3246. {\if\edition\racketEd
  3247. Implement the \code{remove\_complex\_operands} function in
  3248. \code{compiler.rkt}.
  3249. %
  3250. Create three new \LangVar{} programs that exercise the interesting
  3251. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3252. regarding file names described in exercise~\ref{ex:Lvar}.
  3253. %
  3254. In the \code{run-tests.rkt} script, add the following entry to the
  3255. list of \code{passes}, and then run the script to test your compiler.
  3256. \begin{lstlisting}
  3257. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3258. \end{lstlisting}
  3259. In debugging your compiler, it is often useful to see the intermediate
  3260. programs that are output from each pass. To print the intermediate
  3261. programs, place \lstinline{(debug-level 1)} before the call to
  3262. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3263. %
  3264. {\if\edition\pythonEd\pythonColor
  3265. Implement the \code{remove\_complex\_operands} pass in
  3266. \code{compiler.py}, creating auxiliary functions for each
  3267. nonterminal in the grammar, that is, \code{rco\_exp}
  3268. and \code{rco\_stmt}. We recommend that you use the function
  3269. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3270. \fi}
  3271. \end{exercise}
  3272. {\if\edition\pythonEd\pythonColor
  3273. \begin{exercise}
  3274. \normalfont\normalsize
  3275. \label{ex:Lvar}
  3276. Create five \LangVar{} programs that exercise the most interesting
  3277. parts of the \code{remove\_complex\_operands} pass. The five programs
  3278. should be placed in the subdirectory \key{tests/var}, and the file
  3279. names should end with the file extension \key{.py}. Run the
  3280. \key{run-tests.py} script in the support code to check whether the
  3281. output programs produce the same result as the input programs.
  3282. \end{exercise}
  3283. \fi}
  3284. {\if\edition\racketEd
  3285. \section{Explicate Control}
  3286. \label{sec:explicate-control-Lvar}
  3287. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3288. programs that make the order of execution explicit in their
  3289. syntax. For now this amounts to flattening \key{let} constructs into a
  3290. sequence of assignment statements. For example, consider the following
  3291. \LangVar{} program:\\
  3292. % var_test_11.rkt
  3293. \begin{minipage}{0.96\textwidth}
  3294. \begin{lstlisting}
  3295. (let ([y (let ([x 20])
  3296. (+ x (let ([x 22]) x)))])
  3297. y)
  3298. \end{lstlisting}
  3299. \end{minipage}\\
  3300. %
  3301. The output of the previous pass is shown next, on the left, and the
  3302. output of \code{explicate\_control} is on the right. Recall that the
  3303. right-hand side of a \key{let} executes before its body, so that the order
  3304. of evaluation for this program is to assign \code{20} to \code{x.1},
  3305. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3306. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3307. this ordering explicit.
  3308. \begin{transformation}
  3309. \begin{lstlisting}
  3310. (let ([y (let ([x.1 20])
  3311. (let ([x.2 22])
  3312. (+ x.1 x.2)))])
  3313. y)
  3314. \end{lstlisting}
  3315. \compilesto
  3316. \begin{lstlisting}[language=C]
  3317. start:
  3318. x.1 = 20;
  3319. x.2 = 22;
  3320. y = (+ x.1 x.2);
  3321. return y;
  3322. \end{lstlisting}
  3323. \end{transformation}
  3324. \begin{figure}[tbp]
  3325. \begin{tcolorbox}[colback=white]
  3326. \begin{lstlisting}
  3327. (define (explicate_tail e)
  3328. (match e
  3329. [(Var x) ___]
  3330. [(Int n) (Return (Int n))]
  3331. [(Let x rhs body) ___]
  3332. [(Prim op es) ___]
  3333. [else (error "explicate_tail unhandled case" e)]))
  3334. (define (explicate_assign e x cont)
  3335. (match e
  3336. [(Var x) ___]
  3337. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3338. [(Let y rhs body) ___]
  3339. [(Prim op es) ___]
  3340. [else (error "explicate_assign unhandled case" e)]))
  3341. (define (explicate_control p)
  3342. (match p
  3343. [(Program info body) ___]))
  3344. \end{lstlisting}
  3345. \end{tcolorbox}
  3346. \caption{Skeleton for the \code{explicate\_control} pass.}
  3347. \label{fig:explicate-control-Lvar}
  3348. \end{figure}
  3349. The organization of this pass depends on the notion of tail position
  3350. to which we have alluded. Here is the definition.
  3351. \begin{definition}\normalfont
  3352. The following rules define when an expression is in \emph{tail
  3353. position}\index{subject}{tail position} for the language \LangVar{}.
  3354. \begin{enumerate}
  3355. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3356. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3357. \end{enumerate}
  3358. \end{definition}
  3359. We recommend implementing \code{explicate\_control} using two
  3360. recursive functions, \code{explicate\_tail} and
  3361. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3362. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3363. function should be applied to expressions in tail position, whereas the
  3364. \code{explicate\_assign} should be applied to expressions that occur on
  3365. the right-hand side of a \key{let}.
  3366. %
  3367. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3368. input and produces a \Tail{} in \LangCVar{} (see
  3369. figure~\ref{fig:c0-syntax}).
  3370. %
  3371. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3372. the variable to which it is to be assigned, and a \Tail{} in
  3373. \LangCVar{} for the code that comes after the assignment. The
  3374. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3375. The \code{explicate\_assign} function is in accumulator-passing style:
  3376. the \code{cont} parameter is used for accumulating the output. This
  3377. accumulator-passing style plays an important role in the way that we
  3378. generate high-quality code for conditional expressions in
  3379. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3380. continuation because it contains the generated code that should come
  3381. after the current assignment. This code organization is also related
  3382. to continuation-passing style, except that \code{cont} is not what
  3383. happens next during compilation but is what happens next in the
  3384. generated code.
  3385. \begin{exercise}\normalfont\normalsize
  3386. %
  3387. Implement the \code{explicate\_control} function in
  3388. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3389. exercise the code in \code{explicate\_control}.
  3390. %
  3391. In the \code{run-tests.rkt} script, add the following entry to the
  3392. list of \code{passes} and then run the script to test your compiler.
  3393. \begin{lstlisting}
  3394. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3395. \end{lstlisting}
  3396. \end{exercise}
  3397. \fi}
  3398. \section{Select Instructions}
  3399. \label{sec:select-Lvar}
  3400. \index{subject}{select instructions}
  3401. In the \code{select\_instructions} pass we begin the work of
  3402. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3403. language of this pass is a variant of x86 that still uses variables,
  3404. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3405. nonterminal of the \LangXInt{} abstract syntax
  3406. (figure~\ref{fig:x86-int-ast}).
  3407. \racket{We recommend implementing the
  3408. \code{select\_instructions} with three auxiliary functions, one for
  3409. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3410. $\Tail$.}
  3411. \python{We recommend implementing an auxiliary function
  3412. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3413. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3414. same and integer constants change to immediates; that is, $\INT{n}$
  3415. changes to $\IMM{n}$.}
  3416. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3417. arithmetic operations. For example, consider the following addition
  3418. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3419. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3420. \key{addq} instruction in x86, but it performs an in-place update.
  3421. %
  3422. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3423. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3424. \begin{transformation}
  3425. {\if\edition\racketEd
  3426. \begin{lstlisting}
  3427. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3428. \end{lstlisting}
  3429. \fi}
  3430. {\if\edition\pythonEd\pythonColor
  3431. \begin{lstlisting}
  3432. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3433. \end{lstlisting}
  3434. \fi}
  3435. \compilesto
  3436. \begin{lstlisting}
  3437. movq |$\Arg_1$|, %rax
  3438. addq |$\Arg_2$|, %rax
  3439. movq %rax, |$\itm{var}$|
  3440. \end{lstlisting}
  3441. \end{transformation}
  3442. %
  3443. However, with some care we can generate shorter sequences of
  3444. instructions. Suppose that one or more of the arguments of the
  3445. addition is the same variable as the left-hand side of the assignment.
  3446. Then the assignment statement can be translated into a single
  3447. \key{addq} instruction, as follows.
  3448. \begin{transformation}
  3449. {\if\edition\racketEd
  3450. \begin{lstlisting}
  3451. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3452. \end{lstlisting}
  3453. \fi}
  3454. {\if\edition\pythonEd\pythonColor
  3455. \begin{lstlisting}
  3456. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3457. \end{lstlisting}
  3458. \fi}
  3459. \compilesto
  3460. \begin{lstlisting}
  3461. addq |$\Arg_1$|, |$\itm{var}$|
  3462. \end{lstlisting}
  3463. \end{transformation}
  3464. %
  3465. On the other hand, if $\Atm_1$ is not the same variable as the
  3466. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3467. and then add $\Arg_2$ to \itm{var}.
  3468. %
  3469. \begin{transformation}
  3470. {\if\edition\racketEd
  3471. \begin{lstlisting}
  3472. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3473. \end{lstlisting}
  3474. \fi}
  3475. {\if\edition\pythonEd\pythonColor
  3476. \begin{lstlisting}
  3477. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3478. \end{lstlisting}
  3479. \fi}
  3480. \compilesto
  3481. \begin{lstlisting}
  3482. movq |$\Arg_1$|, |$\itm{var}$|
  3483. addq |$\Arg_2$|, |$\itm{var}$|
  3484. \end{lstlisting}
  3485. \end{transformation}
  3486. The \READOP{} operation does not have a direct counterpart in x86
  3487. assembly, so we provide this functionality with the function
  3488. \code{read\_int} in the file \code{runtime.c}, written in
  3489. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3490. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3491. system}, or simply the \emph{runtime} for short. When compiling your
  3492. generated x86 assembly code, you need to compile \code{runtime.c} to
  3493. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3494. \code{-c}) and link it into the executable. For our purposes of code
  3495. generation, all you need to do is translate an assignment of
  3496. \READOP{} into a call to the \code{read\_int} function followed by a
  3497. move from \code{rax} to the left-hand side variable. (The
  3498. return value of a function is placed in \code{rax}.)
  3499. \begin{transformation}
  3500. {\if\edition\racketEd
  3501. \begin{lstlisting}
  3502. |$\itm{var}$| = (read);
  3503. \end{lstlisting}
  3504. \fi}
  3505. {\if\edition\pythonEd\pythonColor
  3506. \begin{lstlisting}
  3507. |$\itm{var}$| = input_int();
  3508. \end{lstlisting}
  3509. \fi}
  3510. \compilesto
  3511. \begin{lstlisting}
  3512. callq read_int
  3513. movq %rax, |$\itm{var}$|
  3514. \end{lstlisting}
  3515. \end{transformation}
  3516. {\if\edition\pythonEd\pythonColor
  3517. %
  3518. Similarly, we translate the \code{print} operation, shown below, into
  3519. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3520. In x86, the first six arguments to functions are passed in registers,
  3521. with the first argument passed in register \code{rdi}. So we move the
  3522. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3523. \code{callq} instruction.
  3524. \begin{transformation}
  3525. \begin{lstlisting}
  3526. print(|$\Atm$|)
  3527. \end{lstlisting}
  3528. \compilesto
  3529. \begin{lstlisting}
  3530. movq |$\Arg$|, %rdi
  3531. callq print_int
  3532. \end{lstlisting}
  3533. \end{transformation}
  3534. %
  3535. \fi}
  3536. {\if\edition\racketEd
  3537. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3538. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3539. assignment to the \key{rax} register followed by a jump to the
  3540. conclusion of the program (so the conclusion needs to be labeled).
  3541. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3542. recursively and then append the resulting instructions.
  3543. \fi}
  3544. {\if\edition\pythonEd\pythonColor
  3545. We recommend that you use the function \code{utils.label\_name} to
  3546. transform strings into labels, for example, in
  3547. the target of the \code{callq} instruction. This practice makes your
  3548. compiler portable across Linux and Mac OS X, which requires an underscore
  3549. prefixed to all labels.
  3550. \fi}
  3551. \begin{exercise}
  3552. \normalfont\normalsize
  3553. {\if\edition\racketEd
  3554. Implement the \code{select\_instructions} pass in
  3555. \code{compiler.rkt}. Create three new example programs that are
  3556. designed to exercise all the interesting cases in this pass.
  3557. %
  3558. In the \code{run-tests.rkt} script, add the following entry to the
  3559. list of \code{passes} and then run the script to test your compiler.
  3560. \begin{lstlisting}
  3561. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3562. \end{lstlisting}
  3563. \fi}
  3564. {\if\edition\pythonEd\pythonColor
  3565. Implement the \key{select\_instructions} pass in
  3566. \code{compiler.py}. Create three new example programs that are
  3567. designed to exercise all the interesting cases in this pass.
  3568. Run the \code{run-tests.py} script to check
  3569. whether the output programs produce the same result as the input
  3570. programs.
  3571. \fi}
  3572. \end{exercise}
  3573. \section{Assign Homes}
  3574. \label{sec:assign-Lvar}
  3575. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3576. \LangXVar{} programs that no longer use program variables. Thus, the
  3577. \code{assign\_homes} pass is responsible for placing all the program
  3578. variables in registers or on the stack. For runtime efficiency, it is
  3579. better to place variables in registers, but because there are only
  3580. sixteen registers, some programs must necessarily resort to placing
  3581. some variables on the stack. In this chapter we focus on the mechanics
  3582. of placing variables on the stack. We study an algorithm for placing
  3583. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3584. Consider again the following \LangVar{} program from
  3585. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3586. % var_test_20.rkt
  3587. \begin{minipage}{0.96\textwidth}
  3588. {\if\edition\racketEd
  3589. \begin{lstlisting}
  3590. (let ([a 42])
  3591. (let ([b a])
  3592. b))
  3593. \end{lstlisting}
  3594. \fi}
  3595. {\if\edition\pythonEd\pythonColor
  3596. \begin{lstlisting}
  3597. a = 42
  3598. b = a
  3599. print(b)
  3600. \end{lstlisting}
  3601. \fi}
  3602. \end{minipage}\\
  3603. %
  3604. The output of \code{select\_instructions} is shown next, on the left,
  3605. and the output of \code{assign\_homes} is on the right. In this
  3606. example, we assign variable \code{a} to stack location
  3607. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3608. \begin{transformation}
  3609. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3610. movq $42, a
  3611. movq a, b
  3612. movq b, %rax
  3613. \end{lstlisting}
  3614. \compilesto
  3615. %stack-space: 16
  3616. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3617. movq $42, -8(%rbp)
  3618. movq -8(%rbp), -16(%rbp)
  3619. movq -16(%rbp), %rax
  3620. \end{lstlisting}
  3621. \end{transformation}
  3622. \racket{
  3623. The \code{assign\_homes} pass should replace all variables
  3624. with stack locations.
  3625. The list of variables can be obtained from
  3626. the \code{locals-types} entry in the $\itm{info}$ of the
  3627. \code{X86Program} node. The \code{locals-types} entry is an alist
  3628. mapping all the variables in the program to their types
  3629. (for now, just \code{Integer}).
  3630. As an aside, the \code{locals-types} entry is
  3631. computed by \code{type-check-Cvar} in the support code, which
  3632. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3633. which you should propagate to the \code{X86Program} node.}
  3634. %
  3635. \python{The \code{assign\_homes} pass should replace all uses of
  3636. variables with stack locations.}
  3637. %
  3638. In the process of assigning variables to stack locations, it is
  3639. convenient for you to compute and store the size of the frame (in
  3640. bytes) in
  3641. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3642. %
  3643. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3644. %
  3645. which is needed later to generate the conclusion of the \code{main}
  3646. procedure. The x86-64 standard requires the frame size to be a
  3647. multiple of 16 bytes.\index{subject}{frame}
  3648. % TODO: store the number of variables instead? -Jeremy
  3649. \begin{exercise}\normalfont\normalsize
  3650. Implement the \code{assign\_homes} pass in
  3651. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3652. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3653. grammar. We recommend that the auxiliary functions take an extra
  3654. parameter that maps variable names to homes (stack locations for now).
  3655. %
  3656. {\if\edition\racketEd
  3657. In the \code{run-tests.rkt} script, add the following entry to the
  3658. list of \code{passes} and then run the script to test your compiler.
  3659. \begin{lstlisting}
  3660. (list "assign homes" assign-homes interp_x86-0)
  3661. \end{lstlisting}
  3662. \fi}
  3663. {\if\edition\pythonEd\pythonColor
  3664. Run the \code{run-tests.py} script to check
  3665. whether the output programs produce the same result as the input
  3666. programs.
  3667. \fi}
  3668. \end{exercise}
  3669. \section{Patch Instructions}
  3670. \label{sec:patch-s0}
  3671. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3672. \LangXInt{} by making sure that each instruction adheres to the
  3673. restriction that at most one argument of an instruction may be a
  3674. memory reference.
  3675. We return to the following example.\\
  3676. \begin{minipage}{0.5\textwidth}
  3677. % var_test_20.rkt
  3678. {\if\edition\racketEd
  3679. \begin{lstlisting}
  3680. (let ([a 42])
  3681. (let ([b a])
  3682. b))
  3683. \end{lstlisting}
  3684. \fi}
  3685. {\if\edition\pythonEd\pythonColor
  3686. \begin{lstlisting}
  3687. a = 42
  3688. b = a
  3689. print(b)
  3690. \end{lstlisting}
  3691. \fi}
  3692. \end{minipage}\\
  3693. The \code{assign\_homes} pass produces the following translation. \\
  3694. \begin{minipage}{0.5\textwidth}
  3695. {\if\edition\racketEd
  3696. \begin{lstlisting}
  3697. movq $42, -8(%rbp)
  3698. movq -8(%rbp), -16(%rbp)
  3699. movq -16(%rbp), %rax
  3700. \end{lstlisting}
  3701. \fi}
  3702. {\if\edition\pythonEd\pythonColor
  3703. \begin{lstlisting}
  3704. movq $42, -8(%rbp)
  3705. movq -8(%rbp), -16(%rbp)
  3706. movq -16(%rbp), %rdi
  3707. callq print_int
  3708. \end{lstlisting}
  3709. \fi}
  3710. \end{minipage}\\
  3711. The second \key{movq} instruction is problematic because both
  3712. arguments are stack locations. We suggest fixing this problem by
  3713. moving from the source location to the register \key{rax} and then
  3714. from \key{rax} to the destination location, as follows.
  3715. \begin{lstlisting}
  3716. movq -8(%rbp), %rax
  3717. movq %rax, -16(%rbp)
  3718. \end{lstlisting}
  3719. There is a similar corner case that also needs to be dealt with. If
  3720. one argument is an immediate integer larger than $2^{16}$ and the
  3721. other is a memory reference, then the instruction is invalid. One can
  3722. fix this, for example, by first moving the immediate integer into
  3723. \key{rax} and then using \key{rax} in place of the integer.
  3724. \begin{exercise}
  3725. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3726. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3727. Create three new example programs that are
  3728. designed to exercise all the interesting cases in this pass.
  3729. %
  3730. {\if\edition\racketEd
  3731. In the \code{run-tests.rkt} script, add the following entry to the
  3732. list of \code{passes} and then run the script to test your compiler.
  3733. \begin{lstlisting}
  3734. (list "patch instructions" patch_instructions interp_x86-0)
  3735. \end{lstlisting}
  3736. \fi}
  3737. {\if\edition\pythonEd\pythonColor
  3738. Run the \code{run-tests.py} script to check
  3739. whether the output programs produce the same result as the input
  3740. programs.
  3741. \fi}
  3742. \end{exercise}
  3743. \section{Generate Prelude and Conclusion}
  3744. \label{sec:print-x86}
  3745. \index{subject}{prelude}\index{subject}{conclusion}
  3746. The last step of the compiler from \LangVar{} to x86 is to generate
  3747. the \code{main} function with a prelude and conclusion wrapped around
  3748. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3749. discussed in section~\ref{sec:x86}.
  3750. When running on Mac OS X, your compiler should prefix an underscore to
  3751. all labels (for example, changing \key{main} to \key{\_main}).
  3752. %
  3753. \racket{The Racket call \code{(system-type 'os)} is useful for
  3754. determining which operating system the compiler is running on. It
  3755. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3756. %
  3757. \python{The Python \code{platform.system}
  3758. function returns \code{\textquotesingle Linux\textquotesingle},
  3759. \code{\textquotesingle Windows\textquotesingle}, or
  3760. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3761. \begin{exercise}\normalfont\normalsize
  3762. %
  3763. Implement the \key{prelude\_and\_conclusion} pass in
  3764. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3765. %
  3766. {\if\edition\racketEd
  3767. In the \code{run-tests.rkt} script, add the following entry to the
  3768. list of \code{passes} and then run the script to test your compiler.
  3769. \begin{lstlisting}
  3770. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3771. \end{lstlisting}
  3772. %
  3773. Uncomment the call to the \key{compiler-tests} function
  3774. (appendix~\ref{appendix:utilities}), which tests your complete
  3775. compiler by executing the generated x86 code. It translates the x86
  3776. AST that you produce into a string by invoking the \code{print-x86}
  3777. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3778. the provided \key{runtime.c} file to \key{runtime.o} using
  3779. \key{gcc}. Run the script to test your compiler.
  3780. %
  3781. \fi}
  3782. {\if\edition\pythonEd\pythonColor
  3783. %
  3784. Run the \code{run-tests.py} script to check whether the output
  3785. programs produce the same result as the input programs. That script
  3786. translates the x86 AST that you produce into a string by invoking the
  3787. \code{repr} method that is implemented by the x86 AST classes in
  3788. \code{x86\_ast.py}.
  3789. %
  3790. \fi}
  3791. \end{exercise}
  3792. \section{Challenge: Partial Evaluator for \LangVar{}}
  3793. \label{sec:pe-Lvar}
  3794. \index{subject}{partialevaluation@partial evaluation}
  3795. This section describes two optional challenge exercises that involve
  3796. adapting and improving the partial evaluator for \LangInt{} that was
  3797. introduced in section~\ref{sec:partial-evaluation}.
  3798. \begin{exercise}\label{ex:pe-Lvar}
  3799. \normalfont\normalsize
  3800. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3801. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3802. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3803. %
  3804. \racket{\key{let} binding}\python{assignment}
  3805. %
  3806. to the \LangInt{} language, so you will need to add cases for them in
  3807. the \code{pe\_exp}
  3808. %
  3809. \racket{function.}
  3810. %
  3811. \python{and \code{pe\_stmt} functions.}
  3812. %
  3813. Once complete, add the partial evaluation pass to the front of your
  3814. compiler, and check that your compiler still passes all the
  3815. tests.
  3816. \end{exercise}
  3817. \begin{exercise}
  3818. \normalfont\normalsize
  3819. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3820. \code{pe\_add} auxiliary functions with functions that know more about
  3821. arithmetic. For example, your partial evaluator should translate
  3822. {\if\edition\racketEd
  3823. \[
  3824. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3825. \code{(+ 2 (read))}
  3826. \]
  3827. \fi}
  3828. {\if\edition\pythonEd\pythonColor
  3829. \[
  3830. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3831. \code{2 + input\_int()}
  3832. \]
  3833. \fi}
  3834. %
  3835. To accomplish this, the \code{pe\_exp} function should produce output
  3836. in the form of the $\itm{residual}$ nonterminal of the following
  3837. grammar. The idea is that when processing an addition expression, we
  3838. can always produce one of the following: (1) an integer constant, (2)
  3839. an addition expression with an integer constant on the left-hand side
  3840. but not the right-hand side, or (3) an addition expression in which
  3841. neither subexpression is a constant.
  3842. %
  3843. {\if\edition\racketEd
  3844. \[
  3845. \begin{array}{lcl}
  3846. \itm{inert} &::=& \Var
  3847. \MID \LP\key{read}\RP
  3848. \MID \LP\key{-} ~\Var\RP
  3849. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3850. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3851. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3852. \itm{residual} &::=& \Int
  3853. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3854. \MID \itm{inert}
  3855. \end{array}
  3856. \]
  3857. \fi}
  3858. {\if\edition\pythonEd\pythonColor
  3859. \[
  3860. \begin{array}{lcl}
  3861. \itm{inert} &::=& \Var
  3862. \MID \key{input\_int}\LP\RP
  3863. \MID \key{-} \Var
  3864. \MID \key{-} \key{input\_int}\LP\RP
  3865. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3866. \itm{residual} &::=& \Int
  3867. \MID \Int ~ \key{+} ~ \itm{inert}
  3868. \MID \itm{inert}
  3869. \end{array}
  3870. \]
  3871. \fi}
  3872. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3873. inputs are $\itm{residual}$ expressions and they should return
  3874. $\itm{residual}$ expressions. Once the improvements are complete,
  3875. make sure that your compiler still passes all the tests. After
  3876. all, fast code is useless if it produces incorrect results!
  3877. \end{exercise}
  3878. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3879. {\if\edition\pythonEd\pythonColor
  3880. \chapter{Parsing}
  3881. \label{ch:parsing}
  3882. \setcounter{footnote}{0}
  3883. \index{subject}{parsing}
  3884. In this chapter we learn how to use the Lark parser
  3885. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3886. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3887. You are then asked to create a parser for \LangVar{} using Lark.
  3888. We also describe the parsing algorithms used inside Lark, studying the
  3889. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3890. A parser framework such as Lark takes in a specification of the
  3891. concrete syntax and an input program and produces a parse tree. Even
  3892. though a parser framework does most of the work for us, using one
  3893. properly requires some knowledge. In particular, we must learn about
  3894. its specification languages and we must learn how to deal with
  3895. ambiguity in our language specifications. Also, some algorithms, such
  3896. as LALR(1), place restrictions on the grammars they can handle, in
  3897. which case knowing the algorithm helps with trying to decipher the
  3898. error messages.
  3899. The process of parsing is traditionally subdivided into two phases:
  3900. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3901. analysis} (also called parsing). The lexical analysis phase
  3902. translates the sequence of characters into a sequence of
  3903. \emph{tokens}, that is, words consisting of several characters. The
  3904. parsing phase organizes the tokens into a \emph{parse tree} that
  3905. captures how the tokens were matched by rules in the grammar of the
  3906. language. The reason for the subdivision into two phases is to enable
  3907. the use of a faster but less powerful algorithm for lexical analysis
  3908. and the use of a slower but more powerful algorithm for parsing.
  3909. %
  3910. %% Likewise, parser generators typical come in pairs, with separate
  3911. %% generators for the lexical analyzer (or lexer for short) and for the
  3912. %% parser. A particularly influential pair of generators were
  3913. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3914. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3915. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3916. %% Compiler Compiler.
  3917. %
  3918. The Lark parser framework that we use in this chapter includes both
  3919. lexical analyzers and parsers. The next section discusses lexical
  3920. analysis, and the remainder of the chapter discusses parsing.
  3921. \section{Lexical Analysis and Regular Expressions}
  3922. \label{sec:lex}
  3923. The lexical analyzers produced by Lark turn a sequence of characters
  3924. (a string) into a sequence of token objects. For example, a Lark
  3925. generated lexer for \LangInt{} converts the string
  3926. \begin{lstlisting}
  3927. 'print(1 + 3)'
  3928. \end{lstlisting}
  3929. \noindent into the following sequence of token objects:
  3930. \begin{center}
  3931. \begin{minipage}{0.95\textwidth}
  3932. \begin{lstlisting}
  3933. Token('PRINT', 'print')
  3934. Token('LPAR', '(')
  3935. Token('INT', '1')
  3936. Token('PLUS', '+')
  3937. Token('INT', '3')
  3938. Token('RPAR', ')')
  3939. Token('NEWLINE', '\n')
  3940. \end{lstlisting}
  3941. \end{minipage}
  3942. \end{center}
  3943. Each token includes a field for its \code{type}, such as \skey{INT},
  3944. and a field for its \code{value}, such as \skey{1}.
  3945. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3946. specification language for Lark's lexer is one regular expression for
  3947. each type of token. The term \emph{regular} comes from the term
  3948. \emph{regular languages}, which are the languages that can be
  3949. recognized by a finite state machine. A \emph{regular expression} is a
  3950. pattern formed of the following core elements:\index{subject}{regular
  3951. expression}\footnote{Regular expressions traditionally include the
  3952. empty regular expression that matches any zero-length part of a
  3953. string, but Lark does not support the empty regular expression.}
  3954. \begin{itemize}
  3955. \item A single character $c$ is a regular expression, and it matches
  3956. only itself. For example, the regular expression \code{a} matches
  3957. only the string \skey{a}.
  3958. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3959. R_2$ form a regular expression that matches any string that matches
  3960. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3961. matches the string \skey{a} and the string \skey{c}.
  3962. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3963. expression that matches any string that can be formed by
  3964. concatenating two strings, where the first string matches $R_1$ and
  3965. the second string matches $R_2$. For example, the regular expression
  3966. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3967. (Parentheses can be used to control the grouping of operators within
  3968. a regular expression.)
  3969. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3970. Kleene closure) is a regular expression that matches any string that
  3971. can be formed by concatenating zero or more strings that each match
  3972. the regular expression $R$. For example, the regular expression
  3973. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3974. \skey{abc}.
  3975. \end{itemize}
  3976. For our convenience, Lark also accepts the following extended set of
  3977. regular expressions that are automatically translated into the core
  3978. regular expressions.
  3979. \begin{itemize}
  3980. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3981. c_n]$ is a regular expression that matches any one of the
  3982. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3983. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3984. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3985. a regular expression that matches any character between $c_1$ and
  3986. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3987. letter in the alphabet.
  3988. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3989. is a regular expression that matches any string that can
  3990. be formed by concatenating one or more strings that each match $R$.
  3991. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3992. matches \skey{b} and \skey{bzca}.
  3993. \item A regular expression followed by a question mark $R\ttm{?}$
  3994. is a regular expression that matches any string that either
  3995. matches $R$ or is the empty string.
  3996. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3997. \end{itemize}
  3998. In a Lark grammar file, each kind of token is specified by a
  3999. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4000. that consists of the name of the terminal followed by a colon followed
  4001. by a sequence of literals. The literals include strings such as
  4002. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4003. terminal names, and literals composed using the regular expression
  4004. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4005. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4006. \begin{center}
  4007. \begin{minipage}{0.95\textwidth}
  4008. \begin{lstlisting}
  4009. DIGIT: /[0-9]/
  4010. INT: "-"? DIGIT+
  4011. NEWLINE: (/\r/? /\n/)+
  4012. \end{lstlisting}
  4013. \end{minipage}
  4014. \end{center}
  4015. \section{Grammars and Parse Trees}
  4016. \label{sec:CFG}
  4017. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4018. specify the abstract syntax of a language. We now take a closer look
  4019. at using grammar rules to specify the concrete syntax. Recall that
  4020. each rule has a left-hand side and a right-hand side, where the
  4021. left-hand side is a nonterminal and the right-hand side is a pattern
  4022. that defines what can be parsed as that nonterminal. For concrete
  4023. syntax, each right-hand side expresses a pattern for a string instead
  4024. of a pattern for an abstract syntax tree. In particular, each
  4025. right-hand side is a sequence of
  4026. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4027. terminal or a nonterminal. The nonterminals play the same role as in
  4028. the abstract syntax, defining categories of syntax. The nonterminals
  4029. of a grammar include the tokens defined in the lexer and all the
  4030. nonterminals defined by the grammar rules.
  4031. As an example, let us take a closer look at the concrete syntax of the
  4032. \LangInt{} language, repeated here.
  4033. \[
  4034. \begin{array}{l}
  4035. \LintGrammarPython \\
  4036. \begin{array}{rcl}
  4037. \LangInt{} &::=& \Stmt^{*}
  4038. \end{array}
  4039. \end{array}
  4040. \]
  4041. The Lark syntax for grammar rules differs slightly from the variant of
  4042. BNF that we use in this book. In particular, the notation $::=$ is
  4043. replaced by a single colon, and the use of typewriter font for string
  4044. literals is replaced by quotation marks. The following grammar serves
  4045. as a first draft of a Lark grammar for \LangInt{}.
  4046. \begin{center}
  4047. \begin{minipage}{0.95\textwidth}
  4048. \begin{lstlisting}[escapechar=$]
  4049. exp: INT
  4050. | "input_int" "(" ")"
  4051. | "-" exp
  4052. | exp "+" exp
  4053. | exp "-" exp
  4054. | "(" exp ")"
  4055. stmt_list:
  4056. | stmt NEWLINE stmt_list
  4057. lang_int: stmt_list
  4058. \end{lstlisting}
  4059. \end{minipage}
  4060. \end{center}
  4061. Let us begin by discussing the rule \code{exp: INT}, which says that
  4062. if the lexer matches a string to \code{INT}, then the parser also
  4063. categorizes the string as an \code{exp}. Recall that in
  4064. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4065. nonterminal with a sentence in English. Here we specify \code{INT}
  4066. more formally using a type of token \code{INT} and its regular
  4067. expression \code{"-"? DIGIT+}.
  4068. The rule \code{exp: exp "+" exp} says that any string that matches
  4069. \code{exp}, followed by the \code{+} character, followed by another
  4070. string that matches \code{exp}, is itself an \code{exp}. For example,
  4071. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4072. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4073. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4074. \code{exp}. We can visualize the application of grammar rules to parse
  4075. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4076. internal node in the tree is an application of a grammar rule and is
  4077. labeled with its left-hand side nonterminal. Each leaf node is a
  4078. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4079. shown in figure~\ref{fig:simple-parse-tree}.
  4080. \begin{figure}[tbp]
  4081. \begin{tcolorbox}[colback=white]
  4082. \centering
  4083. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4084. \end{tcolorbox}
  4085. \caption{The parse tree for \lstinline{'1+3'}.}
  4086. \label{fig:simple-parse-tree}
  4087. \end{figure}
  4088. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4089. following parse tree as represented by \code{Tree} and \code{Token}
  4090. objects.
  4091. \begin{lstlisting}
  4092. Tree('lang_int',
  4093. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4094. Tree('exp', [Token('INT', '3')])])]),
  4095. Token('NEWLINE', '\n')])
  4096. \end{lstlisting}
  4097. The nodes that come from the lexer are \code{Token} objects, whereas
  4098. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4099. object has a \code{data} field containing the name of the nonterminal
  4100. for the grammar rule that was applied. Each \code{Tree} object also
  4101. has a \code{children} field that is a list containing trees and/or
  4102. tokens. Note that Lark does not produce nodes for string literals in
  4103. the grammar. For example, the \code{Tree} node for the addition
  4104. expression has only two children for the two integers but is missing
  4105. its middle child for the \code{"+"} terminal. This would be
  4106. problematic except that Lark provides a mechanism for customizing the
  4107. \code{data} field of each \code{Tree} node on the basis of which rule was
  4108. applied. Next to each alternative in a grammar rule, write \code{->}
  4109. followed by a string that you want to appear in the \code{data}
  4110. field. The following is a second draft of a Lark grammar for
  4111. \LangInt{}, this time with more specific labels on the \code{Tree}
  4112. nodes.
  4113. \begin{center}
  4114. \begin{minipage}{0.95\textwidth}
  4115. \begin{lstlisting}[escapechar=$]
  4116. exp: INT -> int
  4117. | "input_int" "(" ")" -> input_int
  4118. | "-" exp -> usub
  4119. | exp "+" exp -> add
  4120. | exp "-" exp -> sub
  4121. | "(" exp ")" -> paren
  4122. stmt: "print" "(" exp ")" -> print
  4123. | exp -> expr
  4124. stmt_list: -> empty_stmt
  4125. | stmt NEWLINE stmt_list -> add_stmt
  4126. lang_int: stmt_list -> module
  4127. \end{lstlisting}
  4128. \end{minipage}
  4129. \end{center}
  4130. Here is the resulting parse tree.
  4131. \begin{lstlisting}
  4132. Tree('module',
  4133. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4134. Tree('int', [Token('INT', '3')])])]),
  4135. Token('NEWLINE', '\n')])
  4136. \end{lstlisting}
  4137. \section{Ambiguous Grammars}
  4138. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4139. can be parsed in more than one way. For example, consider the string
  4140. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4141. our draft grammar, resulting in the two parse trees shown in
  4142. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4143. interpreting the second parse tree would yield \code{-4} even through
  4144. the correct answer is \code{2}.
  4145. \begin{figure}[tbp]
  4146. \begin{tcolorbox}[colback=white]
  4147. \centering
  4148. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4149. \end{tcolorbox}
  4150. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4151. \label{fig:ambig-parse-tree}
  4152. \end{figure}
  4153. To deal with this problem we can change the grammar by categorizing
  4154. the syntax in a more fine-grained fashion. In this case we want to
  4155. disallow the application of the rule \code{exp: exp "-" exp} when the
  4156. child on the right is an addition. To do this we can replace the
  4157. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4158. the expressions except for addition, as in the following.
  4159. \begin{center}
  4160. \begin{minipage}{0.95\textwidth}
  4161. \begin{lstlisting}[escapechar=$]
  4162. exp: exp "-" exp_no_add -> sub
  4163. | exp "+" exp -> add
  4164. | exp_no_add
  4165. exp_no_add: INT -> int
  4166. | "input_int" "(" ")" -> input_int
  4167. | "-" exp -> usub
  4168. | exp "-" exp_no_add -> sub
  4169. | "(" exp ")" -> paren
  4170. \end{lstlisting}
  4171. \end{minipage}
  4172. \end{center}
  4173. However, there remains some ambiguity in the grammar. For example, the
  4174. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4175. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4176. (incorrect). That is, subtraction is left associative. Likewise,
  4177. addition in Python is left associative. We also need to consider the
  4178. interaction of unary subtraction with both addition and
  4179. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4180. has higher \emph{precedence}\index{subject}{precedence} than addition
  4181. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4182. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4183. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4184. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4185. all the other expressions, and it uses \code{exp\_hi} for the second
  4186. child in the rules for addition and subtraction. Furthermore, unary
  4187. subtraction uses \code{exp\_hi} for its child.
  4188. For languages with more operators and more precedence levels, one must
  4189. refine the \code{exp} nonterminal into several nonterminals, one for
  4190. each precedence level.
  4191. \begin{figure}[tbp]
  4192. \begin{tcolorbox}[colback=white]
  4193. \centering
  4194. \begin{lstlisting}[escapechar=$]
  4195. exp: exp "+" exp_hi -> add
  4196. | exp "-" exp_hi -> sub
  4197. | exp_hi
  4198. exp_hi: INT -> int
  4199. | "input_int" "(" ")" -> input_int
  4200. | "-" exp_hi -> usub
  4201. | "(" exp ")" -> paren
  4202. stmt: "print" "(" exp ")" -> print
  4203. | exp -> expr
  4204. stmt_list: -> empty_stmt
  4205. | stmt NEWLINE stmt_list -> add_stmt
  4206. lang_int: stmt_list -> module
  4207. \end{lstlisting}
  4208. \end{tcolorbox}
  4209. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4210. \label{fig:Lint-lark-grammar}
  4211. \end{figure}
  4212. \section{From Parse Trees to Abstract Syntax Trees}
  4213. As we have seen, the output of a Lark parser is a parse tree, that is,
  4214. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4215. step is to convert the parse tree to an abstract syntax tree. This can
  4216. be accomplished with a recursive function that inspects the
  4217. \code{data} field of each node and then constructs the corresponding
  4218. AST node, using recursion to handle its children. The following is an
  4219. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4220. \begin{center}
  4221. \begin{minipage}{0.95\textwidth}
  4222. \begin{lstlisting}
  4223. def parse_tree_to_ast(e):
  4224. if e.data == 'int':
  4225. return Constant(int(e.children[0].value))
  4226. elif e.data == 'input_int':
  4227. return Call(Name('input_int'), [])
  4228. elif e.data == 'add':
  4229. e1, e2 = e.children
  4230. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4231. ...
  4232. else:
  4233. raise Exception('unhandled parse tree', e)
  4234. \end{lstlisting}
  4235. \end{minipage}
  4236. \end{center}
  4237. \begin{exercise}
  4238. \normalfont\normalsize
  4239. %
  4240. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4241. default parsing algorithm (Earley) with the \code{ambiguity} option
  4242. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4243. output will include multiple parse trees that will indicate to you
  4244. that there is a problem with your grammar. Your parser should ignore
  4245. white space, so we recommend using Lark's \code{\%ignore} directive
  4246. as follows.
  4247. \begin{lstlisting}
  4248. WS: /[ \t\f\r\n]/+
  4249. %ignore WS
  4250. \end{lstlisting}
  4251. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4252. Lark parser instead of using the \code{parse} function from
  4253. the \code{ast} module. Test your compiler on all the \LangVar{}
  4254. programs that you have created, and create four additional programs
  4255. that test for ambiguities in your grammar.
  4256. \end{exercise}
  4257. \section{Earley's Algorithm}
  4258. \label{sec:earley}
  4259. In this section we discuss the parsing algorithm of
  4260. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4261. algorithm is powerful in that it can handle any context-free grammar,
  4262. which makes it easy to use, but it is not a particularly
  4263. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4264. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4265. the number of tokens in the input
  4266. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4267. learn about the LALR(1) algorithm, which is more efficient but cannot
  4268. handle all context-free grammars.
  4269. Earley's algorithm can be viewed as an interpreter; it treats the
  4270. grammar as the program being interpreted, and it treats the concrete
  4271. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4272. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4273. keep track of its progress and to store its results. The chart is an
  4274. array with one slot for each position in the input string, where
  4275. position $0$ is before the first character and position $n$ is
  4276. immediately after the last character. So, the array has length $n+1$
  4277. for an input string of length $n$. Each slot in the chart contains a
  4278. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4279. with a period indicating how much of its right-hand side has already
  4280. been parsed. For example, the dotted rule
  4281. \begin{lstlisting}
  4282. exp: exp "+" . exp_hi
  4283. \end{lstlisting}
  4284. represents a partial parse that has matched an \code{exp} followed by
  4285. \code{+} but has not yet parsed an \code{exp} to the right of
  4286. \code{+}.
  4287. %
  4288. Earley's algorithm starts with an initialization phase and then
  4289. repeats three actions---prediction, scanning, and completion---for as
  4290. long as opportunities arise. We demonstrate Earley's algorithm on a
  4291. running example, parsing the following program:
  4292. \begin{lstlisting}
  4293. print(1 + 3)
  4294. \end{lstlisting}
  4295. The algorithm's initialization phase creates dotted rules for all the
  4296. grammar rules whose left-hand side is the start symbol and places them
  4297. in slot $0$ of the chart. We also record the starting position of the
  4298. dotted rule in parentheses on the right. For example, given the
  4299. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4300. \begin{lstlisting}
  4301. lang_int: . stmt_list (0)
  4302. \end{lstlisting}
  4303. in slot $0$ of the chart. The algorithm then proceeds with
  4304. \emph{prediction} actions in which it adds more dotted rules to the
  4305. chart based on the nonterminals that come immediately after a period. In
  4306. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4307. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4308. period at the beginning of their right-hand sides, as follows:
  4309. \begin{lstlisting}
  4310. stmt_list: . (0)
  4311. stmt_list: . stmt NEWLINE stmt_list (0)
  4312. \end{lstlisting}
  4313. We continue to perform prediction actions as more opportunities
  4314. arise. For example, the \code{stmt} nonterminal now appears after a
  4315. period, so we add all the rules for \code{stmt}.
  4316. \begin{lstlisting}
  4317. stmt: . "print" "(" exp ")" (0)
  4318. stmt: . exp (0)
  4319. \end{lstlisting}
  4320. This reveals yet more opportunities for prediction, so we add the grammar
  4321. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4322. \begin{lstlisting}[escapechar=$]
  4323. exp: . exp "+" exp_hi (0)
  4324. exp: . exp "-" exp_hi (0)
  4325. exp: . exp_hi (0)
  4326. exp_hi: . INT (0)
  4327. exp_hi: . "input_int" "(" ")" (0)
  4328. exp_hi: . "-" exp_hi (0)
  4329. exp_hi: . "(" exp ")" (0)
  4330. \end{lstlisting}
  4331. We have exhausted the opportunities for prediction, so the algorithm
  4332. proceeds to \emph{scanning}, in which we inspect the next input token
  4333. and look for a dotted rule at the current position that has a matching
  4334. terminal immediately following the period. In our running example, the
  4335. first input token is \code{"print"}, so we identify the rule in slot
  4336. $0$ of the chart where \code{"print"} follows the period:
  4337. \begin{lstlisting}
  4338. stmt: . "print" "(" exp ")" (0)
  4339. \end{lstlisting}
  4340. We advance the period past \code{"print"} and add the resulting rule
  4341. to slot $1$:
  4342. \begin{lstlisting}
  4343. stmt: "print" . "(" exp ")" (0)
  4344. \end{lstlisting}
  4345. If the new dotted rule had a nonterminal after the period, we would
  4346. need to carry out a prediction action, adding more dotted rules to
  4347. slot $1$. That is not the case, so we continue scanning. The next
  4348. input token is \code{"("}, so we add the following to slot $2$ of the
  4349. chart.
  4350. \begin{lstlisting}
  4351. stmt: "print" "(" . exp ")" (0)
  4352. \end{lstlisting}
  4353. Now we have a nonterminal after the period, so we carry out several
  4354. prediction actions, adding dotted rules for \code{exp} and
  4355. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4356. starting position $2$.
  4357. \begin{lstlisting}[escapechar=$]
  4358. exp: . exp "+" exp_hi (2)
  4359. exp: . exp "-" exp_hi (2)
  4360. exp: . exp_hi (2)
  4361. exp_hi: . INT (2)
  4362. exp_hi: . "input_int" "(" ")" (2)
  4363. exp_hi: . "-" exp_hi (2)
  4364. exp_hi: . "(" exp ")" (2)
  4365. \end{lstlisting}
  4366. With this prediction complete, we return to scanning, noting that the
  4367. next input token is \code{"1"}, which the lexer parses as an
  4368. \code{INT}. There is a matching rule in slot $2$:
  4369. \begin{lstlisting}
  4370. exp_hi: . INT (2)
  4371. \end{lstlisting}
  4372. so we advance the period and put the following rule into slot $3$.
  4373. \begin{lstlisting}
  4374. exp_hi: INT . (2)
  4375. \end{lstlisting}
  4376. This brings us to \emph{completion} actions. When the period reaches
  4377. the end of a dotted rule, we recognize that the substring
  4378. has matched the nonterminal on the left-hand side of the rule, in this case
  4379. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4380. rules into slot $2$ (the starting position for the finished rule) if
  4381. the period is immediately followed by \code{exp\_hi}. So we identify
  4382. \begin{lstlisting}
  4383. exp: . exp_hi (2)
  4384. \end{lstlisting}
  4385. and add the following dotted rule to slot $3$
  4386. \begin{lstlisting}
  4387. exp: exp_hi . (2)
  4388. \end{lstlisting}
  4389. This triggers another completion step for the nonterminal \code{exp},
  4390. adding two more dotted rules to slot $3$.
  4391. \begin{lstlisting}[escapechar=$]
  4392. exp: exp . "+" exp_hi (2)
  4393. exp: exp . "-" exp_hi (2)
  4394. \end{lstlisting}
  4395. Returning to scanning, the next input token is \code{"+"}, so
  4396. we add the following to slot $4$.
  4397. \begin{lstlisting}[escapechar=$]
  4398. exp: exp "+" . exp_hi (2)
  4399. \end{lstlisting}
  4400. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4401. the following dotted rules to slot $4$ of the chart.
  4402. \begin{lstlisting}[escapechar=$]
  4403. exp_hi: . INT (4)
  4404. exp_hi: . "input_int" "(" ")" (4)
  4405. exp_hi: . "-" exp_hi (4)
  4406. exp_hi: . "(" exp ")" (4)
  4407. \end{lstlisting}
  4408. The next input token is \code{"3"} which the lexer categorized as an
  4409. \code{INT}, so we advance the period past \code{INT} for the rules in
  4410. slot $4$, of which there is just one, and put the following into slot $5$.
  4411. \begin{lstlisting}[escapechar=$]
  4412. exp_hi: INT . (4)
  4413. \end{lstlisting}
  4414. The period at the end of the rule triggers a completion action for the
  4415. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4416. So we advance the period and put the following into slot $5$.
  4417. \begin{lstlisting}[escapechar=$]
  4418. exp: exp "+" exp_hi . (2)
  4419. \end{lstlisting}
  4420. This triggers another completion action for the rules in slot $2$ that
  4421. have a period before \code{exp}.
  4422. \begin{lstlisting}[escapechar=$]
  4423. stmt: "print" "(" exp . ")" (0)
  4424. exp: exp . "+" exp_hi (2)
  4425. exp: exp . "-" exp_hi (2)
  4426. \end{lstlisting}
  4427. We scan the next input token \code{")"}, placing the following dotted
  4428. rule into slot $6$.
  4429. \begin{lstlisting}[escapechar=$]
  4430. stmt: "print" "(" exp ")" . (0)
  4431. \end{lstlisting}
  4432. This triggers the completion of \code{stmt} in slot $0$
  4433. \begin{lstlisting}
  4434. stmt_list: stmt . NEWLINE stmt_list (0)
  4435. \end{lstlisting}
  4436. The last input token is a \code{NEWLINE}, so we advance the period
  4437. and place the new dotted rule into slot $7$.
  4438. \begin{lstlisting}
  4439. stmt_list: stmt NEWLINE . stmt_list (0)
  4440. \end{lstlisting}
  4441. We are close to the end of parsing the input!
  4442. The period is before the \code{stmt\_list} nonterminal, so we
  4443. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4444. \begin{lstlisting}
  4445. stmt_list: . (7)
  4446. stmt_list: . stmt NEWLINE stmt_list (7)
  4447. stmt: . "print" "(" exp ")" (7)
  4448. stmt: . exp (7)
  4449. \end{lstlisting}
  4450. There is immediately an opportunity for completion of \code{stmt\_list},
  4451. so we add the following to slot $7$.
  4452. \begin{lstlisting}
  4453. stmt_list: stmt NEWLINE stmt_list . (0)
  4454. \end{lstlisting}
  4455. This triggers another completion action for \code{stmt\_list} in slot $0$
  4456. \begin{lstlisting}
  4457. lang_int: stmt_list . (0)
  4458. \end{lstlisting}
  4459. which in turn completes \code{lang\_int}, the start symbol of the
  4460. grammar, so the parsing of the input is complete.
  4461. For reference, we give a general description of Earley's
  4462. algorithm.
  4463. \begin{enumerate}
  4464. \item The algorithm begins by initializing slot $0$ of the chart with the
  4465. grammar rule for the start symbol, placing a period at the beginning
  4466. of the right-hand side, and recording its starting position as $0$.
  4467. \item The algorithm repeatedly applies the following three kinds of
  4468. actions for as long as there are opportunities to do so.
  4469. \begin{itemize}
  4470. \item Prediction: If there is a rule in slot $k$ whose period comes
  4471. before a nonterminal, add the rules for that nonterminal into slot
  4472. $k$, placing a period at the beginning of their right-hand sides
  4473. and recording their starting position as $k$.
  4474. \item Scanning: If the token at position $k$ of the input string
  4475. matches the symbol after the period in a dotted rule in slot $k$
  4476. of the chart, advance the period in the dotted rule, adding
  4477. the result to slot $k+1$.
  4478. \item Completion: If a dotted rule in slot $k$ has a period at the
  4479. end, inspect the rules in the slot corresponding to the starting
  4480. position of the completed rule. If any of those rules have a
  4481. nonterminal following their period that matches the left-hand side
  4482. of the completed rule, then advance their period, placing the new
  4483. dotted rule in slot $k$.
  4484. \end{itemize}
  4485. While repeating these three actions, take care never to add
  4486. duplicate dotted rules to the chart.
  4487. \end{enumerate}
  4488. We have described how Earley's algorithm recognizes that an input
  4489. string matches a grammar, but we have not described how it builds a
  4490. parse tree. The basic idea is simple, but building parse trees in an
  4491. efficient way is more complex, requiring a data structure called a
  4492. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4493. to attach a partial parse tree to every dotted rule in the chart.
  4494. Initially, the node associated with a dotted rule has no
  4495. children. As the period moves to the right, the nodes from the
  4496. subparses are added as children to the node.
  4497. As mentioned at the beginning of this section, Earley's algorithm is
  4498. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4499. files that contain thousands of tokens in a reasonable amount of time,
  4500. but not millions.
  4501. %
  4502. In the next section we discuss the LALR(1) parsing algorithm, which is
  4503. efficient enough to use with even the largest of input files.
  4504. \section{The LALR(1) Algorithm}
  4505. \label{sec:lalr}
  4506. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4507. two-phase approach in which it first compiles the grammar into a state
  4508. machine and then runs the state machine to parse an input string. The
  4509. second phase has time complexity $O(n)$ where $n$ is the number of
  4510. tokens in the input, so LALR(1) is the best one could hope for with
  4511. respect to efficiency.
  4512. %
  4513. A particularly influential implementation of LALR(1) is the
  4514. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4515. \texttt{yacc} stands for ``yet another compiler compiler.''
  4516. %
  4517. The LALR(1) state machine uses a stack to record its progress in
  4518. parsing the input string. Each element of the stack is a pair: a
  4519. state number and a grammar symbol (a terminal or a nonterminal). The
  4520. symbol characterizes the input that has been parsed so far, and the
  4521. state number is used to remember how to proceed once the next
  4522. symbol's worth of input has been parsed. Each state in the machine
  4523. represents where the parser stands in the parsing process with respect
  4524. to certain grammar rules. In particular, each state is associated with
  4525. a set of dotted rules.
  4526. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4527. (also called parse table) for the following simple but ambiguous
  4528. grammar:
  4529. \begin{lstlisting}[escapechar=$]
  4530. exp: INT
  4531. | exp "+" exp
  4532. stmt: "print" exp
  4533. start: stmt
  4534. \end{lstlisting}
  4535. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4536. read in a \lstinline{"print"} token, so the top of the stack is
  4537. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4538. the input according to grammar rule 1, which is signified by showing
  4539. rule 1 with a period after the \code{"print"} token and before the
  4540. \code{exp} nonterminal. There are two rules that could apply next,
  4541. rules 2 and 3, so state 1 also shows those rules with a period at
  4542. the beginning of their right-hand sides. The edges between states
  4543. indicate which transitions the machine should make depending on the
  4544. next input token. So, for example, if the next input token is
  4545. \code{INT} then the parser will push \code{INT} and the target state 4
  4546. on the stack and transition to state 4. Suppose that we are now at the end
  4547. of the input. State 4 says that we should reduce by rule 3, so we pop
  4548. from the stack the same number of items as the number of symbols in
  4549. the right-hand side of the rule, in this case just one. We then
  4550. momentarily jump to the state at the top of the stack (state 1) and
  4551. then follow the goto edge that corresponds to the left-hand side of
  4552. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4553. state 3. (A slightly longer example parse is shown in
  4554. figure~\ref{fig:shift-reduce}.)
  4555. \begin{figure}[tbp]
  4556. \centering
  4557. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4558. \caption{An LALR(1) parse table and a trace of an example run.}
  4559. \label{fig:shift-reduce}
  4560. \end{figure}
  4561. In general, the algorithm works as follows. First, set the current state to
  4562. state $0$. Then repeat the following, looking at the next input token.
  4563. \begin{itemize}
  4564. \item If there there is a shift edge for the input token in the
  4565. current state, push the edge's target state and the input token onto
  4566. the stack and proceed to the edge's target state.
  4567. \item If there is a reduce action for the input token in the current
  4568. state, pop $k$ elements from the stack, where $k$ is the number of
  4569. symbols in the right-hand side of the rule being reduced. Jump to
  4570. the state at the top of the stack and then follow the goto edge for
  4571. the nonterminal that matches the left-hand side of the rule that we
  4572. are reducing by. Push the edge's target state and the nonterminal on the
  4573. stack.
  4574. \end{itemize}
  4575. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4576. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4577. algorithm does not know which action to take in this case. When a
  4578. state has both a shift and a reduce action for the same token, we say
  4579. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4580. will arise, for example, in trying to parse the input
  4581. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4582. the parser will be in state 6 and will not know whether to
  4583. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4584. to proceed by shifting the next \lstinline{+} from the input.
  4585. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4586. arises when there are two reduce actions in a state for the same
  4587. token. To understand which grammars give rise to shift/reduce and
  4588. reduce/reduce conflicts, it helps to know how the parse table is
  4589. generated from the grammar, which we discuss next.
  4590. The parse table is generated one state at a time. State 0 represents
  4591. the start of the parser. We add the grammar rule for the start symbol
  4592. to this state with a period at the beginning of the right-hand side,
  4593. similarly to the initialization phase of the Earley parser. If the
  4594. period appears immediately before another nonterminal, we add all the
  4595. rules with that nonterminal on the left-hand side. Again, we place a
  4596. period at the beginning of the right-hand side of each new
  4597. rule. This process, called \emph{state closure}, is continued
  4598. until there are no more rules to add (similarly to the prediction
  4599. actions of an Earley parser). We then examine each dotted rule in the
  4600. current state $I$. Suppose that a dotted rule has the form $A ::=
  4601. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4602. are sequences of symbols. We create a new state and call it $J$. If $X$
  4603. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4604. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4605. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4606. state $J$. We start by adding all dotted rules from state $I$ that
  4607. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4608. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4609. the period moved past the $X$. (This is analogous to completion in
  4610. Earley's algorithm.) We then perform state closure on $J$. This
  4611. process repeats until there are no more states or edges to add.
  4612. We then mark states as accepting states if they have a dotted rule
  4613. that is the start rule with a period at the end. Also, to add
  4614. the reduce actions, we look for any state containing a dotted rule
  4615. with a period at the end. Let $n$ be the rule number for this dotted
  4616. rule. We then put a reduce $n$ action into that state for every token
  4617. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4618. dotted rule with a period at the end. We therefore put a reduce by
  4619. rule 3 action into state 4 for every
  4620. token.
  4621. When inserting reduce actions, take care to spot any shift/reduce or
  4622. reduce/reduce conflicts. If there are any, abort the construction of
  4623. the parse table.
  4624. \begin{exercise}
  4625. \normalfont\normalsize
  4626. %
  4627. Working on paper, walk through the parse table generation process for
  4628. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4629. your results against the parse table shown in
  4630. figure~\ref{fig:shift-reduce}.
  4631. \end{exercise}
  4632. \begin{exercise}
  4633. \normalfont\normalsize
  4634. %
  4635. Change the parser in your compiler for \LangVar{} to set the
  4636. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4637. all the \LangVar{} programs that you have created. In doing so, Lark
  4638. may signal an error due to shift/reduce or reduce/reduce conflicts
  4639. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4640. remove those conflicts.
  4641. \end{exercise}
  4642. \section{Further Reading}
  4643. In this chapter we have just scratched the surface of the field of
  4644. parsing, with the study of a very general but less efficient algorithm
  4645. (Earley) and with a more limited but highly efficient algorithm
  4646. (LALR). There are many more algorithms and classes of grammars that
  4647. fall between these two ends of the spectrum. We recommend to the reader
  4648. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4649. Regarding lexical analysis, we have described the specification
  4650. language, which are the regular expressions, but not the algorithms
  4651. for recognizing them. In short, regular expressions can be translated
  4652. to nondeterministic finite automata, which in turn are translated to
  4653. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4654. all the details on lexical analysis.
  4655. \fi}
  4656. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4657. \chapter{Register Allocation}
  4658. \label{ch:register-allocation-Lvar}
  4659. \setcounter{footnote}{0}
  4660. \index{subject}{register allocation}
  4661. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4662. storing variables on the procedure call stack. The CPU may require tens
  4663. to hundreds of cycles to access a location on the stack, whereas
  4664. accessing a register takes only a single cycle. In this chapter we
  4665. improve the efficiency of our generated code by storing some variables
  4666. in registers. The goal of register allocation is to fit as many
  4667. variables into registers as possible. Some programs have more
  4668. variables than registers, so we cannot always map each variable to a
  4669. different register. Fortunately, it is common for different variables
  4670. to be in use during different periods of time during program
  4671. execution, and in those cases we can map multiple variables to the
  4672. same register.
  4673. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4674. example. The source program is on the left and the output of
  4675. instruction selection\index{subject}{instruction selection}
  4676. is on the right. The program is almost
  4677. completely in the x86 assembly language, but it still uses variables.
  4678. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4679. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4680. the other hand, is used only after this point, so \code{x} and
  4681. \code{z} could share the same register.
  4682. \begin{figure}
  4683. \begin{tcolorbox}[colback=white]
  4684. \begin{minipage}{0.45\textwidth}
  4685. Example \LangVar{} program:
  4686. % var_test_28.rkt
  4687. {\if\edition\racketEd
  4688. \begin{lstlisting}
  4689. (let ([v 1])
  4690. (let ([w 42])
  4691. (let ([x (+ v 7)])
  4692. (let ([y x])
  4693. (let ([z (+ x w)])
  4694. (+ z (- y)))))))
  4695. \end{lstlisting}
  4696. \fi}
  4697. {\if\edition\pythonEd\pythonColor
  4698. \begin{lstlisting}
  4699. v = 1
  4700. w = 42
  4701. x = v + 7
  4702. y = x
  4703. z = x + w
  4704. print(z + (- y))
  4705. \end{lstlisting}
  4706. \fi}
  4707. \end{minipage}
  4708. \begin{minipage}{0.45\textwidth}
  4709. After instruction selection:
  4710. {\if\edition\racketEd
  4711. \begin{lstlisting}
  4712. locals-types:
  4713. x : Integer, y : Integer,
  4714. z : Integer, t : Integer,
  4715. v : Integer, w : Integer
  4716. start:
  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, t
  4725. negq t
  4726. movq z, %rax
  4727. addq t, %rax
  4728. jmp conclusion
  4729. \end{lstlisting}
  4730. \fi}
  4731. {\if\edition\pythonEd\pythonColor
  4732. \begin{lstlisting}
  4733. movq $1, v
  4734. movq $42, w
  4735. movq v, x
  4736. addq $7, x
  4737. movq x, y
  4738. movq x, z
  4739. addq w, z
  4740. movq y, tmp_0
  4741. negq tmp_0
  4742. movq z, tmp_1
  4743. addq tmp_0, tmp_1
  4744. movq tmp_1, %rdi
  4745. callq print_int
  4746. \end{lstlisting}
  4747. \fi}
  4748. \end{minipage}
  4749. \end{tcolorbox}
  4750. \caption{A running example for register allocation.}
  4751. \label{fig:reg-eg}
  4752. \end{figure}
  4753. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4754. compute where a variable is in use. Once we have that information, we
  4755. compute which variables are in use at the same time, that is, which ones
  4756. \emph{interfere}\index{subject}{interfere} with each other, and
  4757. represent this relation as an undirected graph whose vertices are
  4758. variables and edges indicate when two variables interfere
  4759. (section~\ref{sec:build-interference}). We then model register
  4760. allocation as a graph coloring problem
  4761. (section~\ref{sec:graph-coloring}).
  4762. If we run out of registers despite these efforts, we place the
  4763. remaining variables on the stack, similarly to how we handled
  4764. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4765. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4766. location. The decision to spill a variable is handled as part of the
  4767. graph coloring process.
  4768. We make the simplifying assumption that each variable is assigned to
  4769. one location (a register or stack address). A more sophisticated
  4770. approach is to assign a variable to one or more locations in different
  4771. regions of the program. For example, if a variable is used many times
  4772. in short sequence and then used again only after many other
  4773. instructions, it could be more efficient to assign the variable to a
  4774. register during the initial sequence and then move it to the stack for
  4775. the rest of its lifetime. We refer the interested reader to
  4776. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4777. approach.
  4778. % discuss prioritizing variables based on how much they are used.
  4779. \section{Registers and Calling Conventions}
  4780. \label{sec:calling-conventions}
  4781. \index{subject}{calling conventions}
  4782. As we perform register allocation, we must be aware of the
  4783. \emph{calling conventions} \index{subject}{calling conventions} that
  4784. govern how function calls are performed in x86.
  4785. %
  4786. Even though \LangVar{} does not include programmer-defined functions,
  4787. our generated code includes a \code{main} function that is called by
  4788. the operating system and our generated code contains calls to the
  4789. \code{read\_int} function.
  4790. Function calls require coordination between two pieces of code that
  4791. may be written by different programmers or generated by different
  4792. compilers. Here we follow the System V calling conventions that are
  4793. used by the GNU C compiler on Linux and
  4794. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4795. %
  4796. The calling conventions include rules about how functions share the
  4797. use of registers. In particular, the caller is responsible for freeing
  4798. some registers prior to the function call for use by the callee.
  4799. These are called the \emph{caller-saved registers}
  4800. \index{subject}{caller-saved registers}
  4801. and they are
  4802. \begin{lstlisting}
  4803. rax rcx rdx rsi rdi r8 r9 r10 r11
  4804. \end{lstlisting}
  4805. On the other hand, the callee is responsible for preserving the values
  4806. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4807. which are
  4808. \begin{lstlisting}
  4809. rsp rbp rbx r12 r13 r14 r15
  4810. \end{lstlisting}
  4811. We can think about this caller/callee convention from two points of
  4812. view, the caller view and the callee view, as follows:
  4813. \begin{itemize}
  4814. \item The caller should assume that all the caller-saved registers get
  4815. overwritten with arbitrary values by the callee. On the other hand,
  4816. the caller can safely assume that all the callee-saved registers
  4817. retain their original values.
  4818. \item The callee can freely use any of the caller-saved registers.
  4819. However, if the callee wants to use a callee-saved register, the
  4820. callee must arrange to put the original value back in the register
  4821. prior to returning to the caller. This can be accomplished by saving
  4822. the value to the stack in the prelude of the function and restoring
  4823. the value in the conclusion of the function.
  4824. \end{itemize}
  4825. In x86, registers are also used for passing arguments to a function
  4826. and for the return value. In particular, the first six arguments of a
  4827. function are passed in the following six registers, in this order.
  4828. \begin{lstlisting}
  4829. rdi rsi rdx rcx r8 r9
  4830. \end{lstlisting}
  4831. We refer to these six registers are the argument-passing registers
  4832. \index{subject}{argument-passing registers}.
  4833. If there are more than six arguments, the convention is to use space
  4834. on the frame of the caller for the rest of the arguments. In
  4835. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4836. argument and the rest of the arguments, which simplifies the treatment
  4837. of efficient tail calls.
  4838. %
  4839. \racket{For now, the only function we care about is \code{read\_int},
  4840. which takes zero arguments.}
  4841. %
  4842. \python{For now, the only functions we care about are \code{read\_int}
  4843. and \code{print\_int}, which take zero and one argument, respectively.}
  4844. %
  4845. The register \code{rax} is used for the return value of a function.
  4846. The next question is how these calling conventions impact register
  4847. allocation. Consider the \LangVar{} program presented in
  4848. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4849. example from the caller point of view and then from the callee point
  4850. of view. We refer to a variable that is in use during a function call
  4851. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4852. The program makes two calls to \READOP{}. The variable \code{x} is
  4853. call-live because it is in use during the second call to \READOP{}; we
  4854. must ensure that the value in \code{x} does not get overwritten during
  4855. the call to \READOP{}. One obvious approach is to save all the values
  4856. that reside in caller-saved registers to the stack prior to each
  4857. function call and to restore them after each call. That way, if the
  4858. register allocator chooses to assign \code{x} to a caller-saved
  4859. register, its value will be preserved across the call to \READOP{}.
  4860. However, saving and restoring to the stack is relatively slow. If
  4861. \code{x} is not used many times, it may be better to assign \code{x}
  4862. to a stack location in the first place. Or better yet, if we can
  4863. arrange for \code{x} to be placed in a callee-saved register, then it
  4864. won't need to be saved and restored during function calls.
  4865. We recommend an approach that captures these issues in the
  4866. interference graph, without complicating the graph coloring algorithm.
  4867. During liveness analysis we know which variables are call-live because
  4868. we compute which variables are in use at every instruction
  4869. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4870. interference graph (section~\ref{sec:build-interference}), we can
  4871. place an edge in the interference graph between each call-live
  4872. variable and the caller-saved registers. This will prevent the graph
  4873. coloring algorithm from assigning call-live variables to caller-saved
  4874. registers.
  4875. On the other hand, for variables that are not call-live, we prefer
  4876. placing them in caller-saved registers to leave more room for
  4877. call-live variables in the callee-saved registers. This can also be
  4878. implemented without complicating the graph coloring algorithm. We
  4879. recommend that the graph coloring algorithm assign variables to
  4880. natural numbers, choosing the lowest number for which there is no
  4881. interference. After the coloring is complete, we map the numbers to
  4882. registers and stack locations: mapping the lowest numbers to
  4883. caller-saved registers, the next lowest to callee-saved registers, and
  4884. the largest numbers to stack locations. This ordering gives preference
  4885. to registers over stack locations and to caller-saved registers over
  4886. callee-saved registers.
  4887. Returning to the example in
  4888. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4889. generated x86 code on the right-hand side. Variable \code{x} is
  4890. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4891. in a safe place during the second call to \code{read\_int}. Next,
  4892. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4893. because \code{y} is not a call-live variable.
  4894. We have completed the analysis from the caller point of view, so now
  4895. we switch to the callee point of view, focusing on the prelude and
  4896. conclusion of the \code{main} function. As usual, the prelude begins
  4897. with saving the \code{rbp} register to the stack and setting the
  4898. \code{rbp} to the current stack pointer. We now know why it is
  4899. necessary to save the \code{rbp}: it is a callee-saved register. The
  4900. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4901. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4902. (\code{x}). The other callee-saved registers are not saved in the
  4903. prelude because they are not used. The prelude subtracts 8 bytes from
  4904. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4905. conclusion, we see that \code{rbx} is restored from the stack with a
  4906. \code{popq} instruction.
  4907. \index{subject}{prelude}\index{subject}{conclusion}
  4908. \begin{figure}[tp]
  4909. \begin{tcolorbox}[colback=white]
  4910. \begin{minipage}{0.45\textwidth}
  4911. Example \LangVar{} program:
  4912. %var_test_14.rkt
  4913. {\if\edition\racketEd
  4914. \begin{lstlisting}
  4915. (let ([x (read)])
  4916. (let ([y (read)])
  4917. (+ (+ x y) 42)))
  4918. \end{lstlisting}
  4919. \fi}
  4920. {\if\edition\pythonEd\pythonColor
  4921. \begin{lstlisting}
  4922. x = input_int()
  4923. y = input_int()
  4924. print((x + y) + 42)
  4925. \end{lstlisting}
  4926. \fi}
  4927. \end{minipage}
  4928. \begin{minipage}{0.45\textwidth}
  4929. Generated x86 assembly:
  4930. {\if\edition\racketEd
  4931. \begin{lstlisting}
  4932. start:
  4933. callq read_int
  4934. movq %rax, %rbx
  4935. callq read_int
  4936. movq %rax, %rcx
  4937. addq %rcx, %rbx
  4938. movq %rbx, %rax
  4939. addq $42, %rax
  4940. jmp _conclusion
  4941. .globl main
  4942. main:
  4943. pushq %rbp
  4944. movq %rsp, %rbp
  4945. pushq %rbx
  4946. subq $8, %rsp
  4947. jmp start
  4948. conclusion:
  4949. addq $8, %rsp
  4950. popq %rbx
  4951. popq %rbp
  4952. retq
  4953. \end{lstlisting}
  4954. \fi}
  4955. {\if\edition\pythonEd\pythonColor
  4956. \begin{lstlisting}
  4957. .globl main
  4958. main:
  4959. pushq %rbp
  4960. movq %rsp, %rbp
  4961. pushq %rbx
  4962. subq $8, %rsp
  4963. callq read_int
  4964. movq %rax, %rbx
  4965. callq read_int
  4966. movq %rax, %rcx
  4967. movq %rbx, %rdx
  4968. addq %rcx, %rdx
  4969. movq %rdx, %rcx
  4970. addq $42, %rcx
  4971. movq %rcx, %rdi
  4972. callq print_int
  4973. addq $8, %rsp
  4974. popq %rbx
  4975. popq %rbp
  4976. retq
  4977. \end{lstlisting}
  4978. \fi}
  4979. \end{minipage}
  4980. \end{tcolorbox}
  4981. \caption{An example with function calls.}
  4982. \label{fig:example-calling-conventions}
  4983. \end{figure}
  4984. %\clearpage
  4985. \section{Liveness Analysis}
  4986. \label{sec:liveness-analysis-Lvar}
  4987. \index{subject}{liveness analysis}
  4988. The \code{uncover\_live} \racket{pass}\python{function} performs
  4989. \emph{liveness analysis}; that is, it discovers which variables are
  4990. in use in different regions of a program.
  4991. %
  4992. A variable or register is \emph{live} at a program point if its
  4993. current value is used at some later point in the program. We refer to
  4994. variables, stack locations, and registers collectively as
  4995. \emph{locations}.
  4996. %
  4997. Consider the following code fragment in which there are two writes to
  4998. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4999. time?
  5000. \begin{center}
  5001. \begin{minipage}{0.85\textwidth}
  5002. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5003. movq $5, a
  5004. movq $30, b
  5005. movq a, c
  5006. movq $10, b
  5007. addq b, c
  5008. \end{lstlisting}
  5009. \end{minipage}
  5010. \end{center}
  5011. The answer is no, because \code{a} is live from line 1 to 3 and
  5012. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5013. line 2 is never used because it is overwritten (line 4) before the
  5014. next read (line 5).
  5015. The live locations for each instruction can be computed by traversing
  5016. the instruction sequence back to front (i.e., backward in execution
  5017. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5018. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5019. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5020. locations before instruction $I_k$. \racket{We recommend representing
  5021. these sets with the Racket \code{set} data structure described in
  5022. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5023. with the Python
  5024. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5025. data structure.}
  5026. {\if\edition\racketEd
  5027. \begin{figure}[tp]
  5028. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5029. \small
  5030. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5031. A \emph{set} is an unordered collection of elements without duplicates.
  5032. Here are some of the operations defined on sets.
  5033. \index{subject}{set}
  5034. \begin{description}
  5035. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5036. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5037. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5038. difference of the two sets.
  5039. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5040. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5041. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5042. \end{description}
  5043. \end{tcolorbox}
  5044. %\end{wrapfigure}
  5045. \caption{The \code{set} data structure.}
  5046. \label{fig:set}
  5047. \end{figure}
  5048. \fi}
  5049. % TODO: add a python version of the reference box for sets. -Jeremy
  5050. The locations that are live after an instruction are its
  5051. \emph{live-after}\index{subject}{live-after} set, and the locations
  5052. that are live before an instruction are its
  5053. \emph{live-before}\index{subject}{live-before} set. The live-after
  5054. set of an instruction is always the same as the live-before set of the
  5055. next instruction.
  5056. \begin{equation} \label{eq:live-after-before-next}
  5057. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5058. \end{equation}
  5059. To start things off, there are no live locations after the last
  5060. instruction, so
  5061. \begin{equation}\label{eq:live-last-empty}
  5062. L_{\mathsf{after}}(n) = \emptyset
  5063. \end{equation}
  5064. We then apply the following rule repeatedly, traversing the
  5065. instruction sequence back to front.
  5066. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5067. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5068. \end{equation}
  5069. where $W(k)$ are the locations written to by instruction $I_k$, and
  5070. $R(k)$ are the locations read by instruction $I_k$.
  5071. {\if\edition\racketEd
  5072. %
  5073. There is a special case for \code{jmp} instructions. The locations
  5074. that are live before a \code{jmp} should be the locations in
  5075. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5076. maintaining an alist named \code{label->live} that maps each label to
  5077. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5078. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5079. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5080. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5081. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5082. %
  5083. \fi}
  5084. Let us walk through the previous example, applying these formulas
  5085. starting with the instruction on line 5 of the code fragment. We
  5086. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5087. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5088. $\emptyset$ because it is the last instruction
  5089. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5090. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5091. variables \code{b} and \code{c}
  5092. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5093. \[
  5094. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5095. \]
  5096. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5097. the live-before set from line 5 to be the live-after set for this
  5098. instruction (formula~\eqref{eq:live-after-before-next}).
  5099. \[
  5100. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5101. \]
  5102. This move instruction writes to \code{b} and does not read from any
  5103. variables, so we have the following live-before set
  5104. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5105. \[
  5106. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5107. \]
  5108. The live-before for instruction \code{movq a, c}
  5109. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5110. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5111. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5112. variable that is not live and does not read from a variable.
  5113. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5114. because it writes to variable \code{a}.
  5115. \begin{figure}[tbp]
  5116. \centering
  5117. \begin{tcolorbox}[colback=white]
  5118. \hspace{10pt}
  5119. \begin{minipage}{0.4\textwidth}
  5120. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5121. movq $5, a
  5122. movq $30, b
  5123. movq a, c
  5124. movq $10, b
  5125. addq b, c
  5126. \end{lstlisting}
  5127. \end{minipage}
  5128. \vrule\hspace{10pt}
  5129. \begin{minipage}{0.45\textwidth}
  5130. \begin{align*}
  5131. L_{\mathsf{before}}(1)= \emptyset,
  5132. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5133. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5134. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5135. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5136. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5137. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5138. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5139. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5140. L_{\mathsf{after}}(5)= \emptyset
  5141. \end{align*}
  5142. \end{minipage}
  5143. \end{tcolorbox}
  5144. \caption{Example output of liveness analysis on a short example.}
  5145. \label{fig:liveness-example-0}
  5146. \end{figure}
  5147. \begin{exercise}\normalfont\normalsize
  5148. Perform liveness analysis by hand on the running example in
  5149. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5150. sets for each instruction. Compare your answers to the solution
  5151. shown in figure~\ref{fig:live-eg}.
  5152. \end{exercise}
  5153. \begin{figure}[tp]
  5154. \hspace{20pt}
  5155. \begin{minipage}{0.55\textwidth}
  5156. \begin{tcolorbox}[colback=white]
  5157. {\if\edition\racketEd
  5158. \begin{lstlisting}
  5159. |$\{\ttm{rsp}\}$|
  5160. movq $1, v
  5161. |$\{\ttm{v},\ttm{rsp}\}$|
  5162. movq $42, w
  5163. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5164. movq v, x
  5165. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5166. addq $7, x
  5167. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5168. movq x, y
  5169. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5170. movq x, z
  5171. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5172. addq w, z
  5173. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5174. movq y, t
  5175. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5176. negq t
  5177. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5178. movq z, %rax
  5179. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5180. addq t, %rax
  5181. |$\{\ttm{rax},\ttm{rsp}\}$|
  5182. jmp conclusion
  5183. \end{lstlisting}
  5184. \fi}
  5185. {\if\edition\pythonEd\pythonColor
  5186. \begin{lstlisting}
  5187. movq $1, v
  5188. |$\{\ttm{v}\}$|
  5189. movq $42, w
  5190. |$\{\ttm{w}, \ttm{v}\}$|
  5191. movq v, x
  5192. |$\{\ttm{w}, \ttm{x}\}$|
  5193. addq $7, x
  5194. |$\{\ttm{w}, \ttm{x}\}$|
  5195. movq x, y
  5196. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5197. movq x, z
  5198. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5199. addq w, z
  5200. |$\{\ttm{y}, \ttm{z}\}$|
  5201. movq y, tmp_0
  5202. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5203. negq tmp_0
  5204. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5205. movq z, tmp_1
  5206. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5207. addq tmp_0, tmp_1
  5208. |$\{\ttm{tmp\_1}\}$|
  5209. movq tmp_1, %rdi
  5210. |$\{\ttm{rdi}\}$|
  5211. callq print_int
  5212. |$\{\}$|
  5213. \end{lstlisting}
  5214. \fi}
  5215. \end{tcolorbox}
  5216. \end{minipage}
  5217. \caption{The running example annotated with live-after sets.}
  5218. \label{fig:live-eg}
  5219. \end{figure}
  5220. \begin{exercise}\normalfont\normalsize
  5221. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5222. %
  5223. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5224. field of the \code{Block} structure.}
  5225. %
  5226. \python{Return a dictionary that maps each instruction to its
  5227. live-after set.}
  5228. %
  5229. \racket{We recommend creating an auxiliary function that takes a list
  5230. of instructions and an initial live-after set (typically empty) and
  5231. returns the list of live-after sets.}
  5232. %
  5233. We recommend creating auxiliary functions to (1) compute the set
  5234. of locations that appear in an \Arg{}, (2) compute the locations read
  5235. by an instruction (the $R$ function), and (3) the locations written by
  5236. an instruction (the $W$ function). The \code{callq} instruction should
  5237. include all the caller-saved registers in its write set $W$ because
  5238. the calling convention says that those registers may be written to
  5239. during the function call. Likewise, the \code{callq} instruction
  5240. should include the appropriate argument-passing registers in its
  5241. read set $R$, depending on the arity of the function being
  5242. called. (This is why the abstract syntax for \code{callq} includes the
  5243. arity.)
  5244. \end{exercise}
  5245. %\clearpage
  5246. \section{Build the Interference Graph}
  5247. \label{sec:build-interference}
  5248. {\if\edition\racketEd
  5249. \begin{figure}[tp]
  5250. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5251. \small
  5252. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5253. A \emph{graph} is a collection of vertices and edges where each
  5254. edge connects two vertices. A graph is \emph{directed} if each
  5255. edge points from a source to a target. Otherwise the graph is
  5256. \emph{undirected}.
  5257. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5258. \begin{description}
  5259. %% We currently don't use directed graphs. We instead use
  5260. %% directed multi-graphs. -Jeremy
  5261. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5262. directed graph from a list of edges. Each edge is a list
  5263. containing the source and target vertex.
  5264. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5265. undirected graph from a list of edges. Each edge is represented by
  5266. a list containing two vertices.
  5267. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5268. inserts a vertex into the graph.
  5269. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5270. inserts an edge between the two vertices.
  5271. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5272. returns a sequence of vertices adjacent to the vertex.
  5273. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5274. returns a sequence of all vertices in the graph.
  5275. \end{description}
  5276. \end{tcolorbox}
  5277. %\end{wrapfigure}
  5278. \caption{The Racket \code{graph} package.}
  5279. \label{fig:graph}
  5280. \end{figure}
  5281. \fi}
  5282. On the basis of the liveness analysis, we know where each location is
  5283. live. However, during register allocation, we need to answer
  5284. questions of the specific form: are locations $u$ and $v$ live at the
  5285. same time? (If so, they cannot be assigned to the same register.) To
  5286. make this question more efficient to answer, we create an explicit
  5287. data structure, an \emph{interference
  5288. graph}\index{subject}{interference graph}. An interference graph is
  5289. an undirected graph that has a node for every variable and register
  5290. and has an edge between two nodes if they are
  5291. live at the same time, that is, if they interfere with each other.
  5292. %
  5293. \racket{We recommend using the Racket \code{graph} package
  5294. (figure~\ref{fig:graph}) to represent the interference graph.}
  5295. %
  5296. \python{We provide implementations of directed and undirected graph
  5297. data structures in the file \code{graph.py} of the support code.}
  5298. A straightforward way to compute the interference graph is to look at
  5299. the set of live locations between each instruction and add an edge to
  5300. the graph for every pair of variables in the same set. This approach
  5301. is less than ideal for two reasons. First, it can be expensive because
  5302. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5303. locations. Second, in the special case in which two locations hold the
  5304. same value (because one was assigned to the other), they can be live
  5305. at the same time without interfering with each other.
  5306. A better way to compute the interference graph is to focus on
  5307. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5308. must not overwrite something in a live location. So for each
  5309. instruction, we create an edge between the locations being written to
  5310. and the live locations. (However, a location never interferes with
  5311. itself.) For the \key{callq} instruction, we consider all the
  5312. caller-saved registers to have been written to, so an edge is added
  5313. between every live variable and every caller-saved register. Also, for
  5314. \key{movq} there is the special case of two variables holding the same
  5315. value. If a live variable $v$ is the same as the source of the
  5316. \key{movq}, then there is no need to add an edge between $v$ and the
  5317. destination, because they both hold the same value.
  5318. %
  5319. Hence we have the following two rules:
  5320. \begin{enumerate}
  5321. \item If instruction $I_k$ is a move instruction of the form
  5322. \key{movq} $s$\key{,} $d$, then for every $v \in
  5323. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5324. $(d,v)$.
  5325. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5326. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5327. $(d,v)$.
  5328. \end{enumerate}
  5329. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5330. these rules to each instruction. We highlight a few of the
  5331. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5332. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5333. so \code{v} interferes with \code{rsp}.}
  5334. %
  5335. \python{The first instruction is \lstinline{movq $1, v}, and the
  5336. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5337. no interference because $\ttm{v}$ is the destination of the move.}
  5338. %
  5339. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5340. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5341. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5342. %
  5343. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5344. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5345. $\ttm{x}$ interferes with \ttm{w}.}
  5346. %
  5347. \racket{The next instruction is \lstinline{movq x, y}, and the
  5348. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5349. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5350. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5351. \ttm{x} and \ttm{y} hold the same value.}
  5352. %
  5353. \python{The next instruction is \lstinline{movq x, y}, and the
  5354. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5355. applies, so \ttm{y} interferes with \ttm{w} but not
  5356. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5357. \ttm{x} and \ttm{y} hold the same value.}
  5358. %
  5359. Figure~\ref{fig:interference-results} lists the interference results
  5360. for all the instructions, and the resulting interference graph is
  5361. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5362. the interference graph in figure~\ref{fig:interfere} because there
  5363. were no interference edges involving registers and we did not wish to
  5364. clutter the graph, but in general one needs to include all the
  5365. registers in the interference graph.
  5366. \begin{figure}[tbp]
  5367. \begin{tcolorbox}[colback=white]
  5368. \begin{quote}
  5369. {\if\edition\racketEd
  5370. \begin{tabular}{ll}
  5371. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5372. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5373. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5374. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5375. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5376. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5377. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5378. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5379. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5380. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5381. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5382. \lstinline!jmp conclusion!& no interference.
  5383. \end{tabular}
  5384. \fi}
  5385. {\if\edition\pythonEd\pythonColor
  5386. \begin{tabular}{ll}
  5387. \lstinline!movq $1, v!& no interference\\
  5388. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5389. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5390. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5391. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5392. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5393. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5394. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5395. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5396. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5397. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5398. \lstinline!movq tmp_1, %rdi! & no interference \\
  5399. \lstinline!callq print_int!& no interference.
  5400. \end{tabular}
  5401. \fi}
  5402. \end{quote}
  5403. \end{tcolorbox}
  5404. \caption{Interference results for the running example.}
  5405. \label{fig:interference-results}
  5406. \end{figure}
  5407. \begin{figure}[tbp]
  5408. \begin{tcolorbox}[colback=white]
  5409. \large
  5410. {\if\edition\racketEd
  5411. \[
  5412. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5413. \node (rax) at (0,0) {$\ttm{rax}$};
  5414. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5415. \node (t1) at (0,2) {$\ttm{t}$};
  5416. \node (z) at (3,2) {$\ttm{z}$};
  5417. \node (x) at (6,2) {$\ttm{x}$};
  5418. \node (y) at (3,0) {$\ttm{y}$};
  5419. \node (w) at (6,0) {$\ttm{w}$};
  5420. \node (v) at (9,0) {$\ttm{v}$};
  5421. \draw (t1) to (rax);
  5422. \draw (t1) to (z);
  5423. \draw (z) to (y);
  5424. \draw (z) to (w);
  5425. \draw (x) to (w);
  5426. \draw (y) to (w);
  5427. \draw (v) to (w);
  5428. \draw (v) to (rsp);
  5429. \draw (w) to (rsp);
  5430. \draw (x) to (rsp);
  5431. \draw (y) to (rsp);
  5432. \path[-.,bend left=15] (z) edge node {} (rsp);
  5433. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5434. \draw (rax) to (rsp);
  5435. \end{tikzpicture}
  5436. \]
  5437. \fi}
  5438. {\if\edition\pythonEd\pythonColor
  5439. \[
  5440. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5441. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5442. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5443. \node (z) at (3,2) {$\ttm{z}$};
  5444. \node (x) at (6,2) {$\ttm{x}$};
  5445. \node (y) at (3,0) {$\ttm{y}$};
  5446. \node (w) at (6,0) {$\ttm{w}$};
  5447. \node (v) at (9,0) {$\ttm{v}$};
  5448. \draw (t0) to (t1);
  5449. \draw (t0) to (z);
  5450. \draw (z) to (y);
  5451. \draw (z) to (w);
  5452. \draw (x) to (w);
  5453. \draw (y) to (w);
  5454. \draw (v) to (w);
  5455. \end{tikzpicture}
  5456. \]
  5457. \fi}
  5458. \end{tcolorbox}
  5459. \caption{The interference graph of the example program.}
  5460. \label{fig:interfere}
  5461. \end{figure}
  5462. \begin{exercise}\normalfont\normalsize
  5463. \racket{Implement the compiler pass named \code{build\_interference} according
  5464. to the algorithm suggested here. We recommend using the Racket
  5465. \code{graph} package to create and inspect the interference graph.
  5466. The output graph of this pass should be stored in the $\itm{info}$ field of
  5467. the program, under the key \code{conflicts}.}
  5468. %
  5469. \python{Implement a function named \code{build\_interference}
  5470. according to the algorithm suggested above that
  5471. returns the interference graph.}
  5472. \end{exercise}
  5473. \section{Graph Coloring via Sudoku}
  5474. \label{sec:graph-coloring}
  5475. \index{subject}{graph coloring}
  5476. \index{subject}{sudoku}
  5477. \index{subject}{color}
  5478. We come to the main event discussed in this chapter, mapping variables
  5479. to registers and stack locations. Variables that interfere with each
  5480. other must be mapped to different locations. In terms of the
  5481. interference graph, this means that adjacent vertices must be mapped
  5482. to different locations. If we think of locations as colors, the
  5483. register allocation problem becomes the graph coloring
  5484. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5485. The reader may be more familiar with the graph coloring problem than he
  5486. or she realizes; the popular game of sudoku is an instance of the
  5487. graph coloring problem. The following describes how to build a graph
  5488. out of an initial sudoku board.
  5489. \begin{itemize}
  5490. \item There is one vertex in the graph for each sudoku square.
  5491. \item There is an edge between two vertices if the corresponding squares
  5492. are in the same row, in the same column, or in the same $3\times 3$ region.
  5493. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5494. \item On the basis of the initial assignment of numbers to squares on the
  5495. sudoku board, assign the corresponding colors to the corresponding
  5496. vertices in the graph.
  5497. \end{itemize}
  5498. If you can color the remaining vertices in the graph with the nine
  5499. colors, then you have also solved the corresponding game of sudoku.
  5500. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5501. the corresponding graph with colored vertices. Here we use a
  5502. monochrome representation of colors, mapping the sudoku number 1 to
  5503. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5504. of the vertices (the colored ones) because showing edges for all the
  5505. vertices would make the graph unreadable.
  5506. \begin{figure}[tbp]
  5507. \begin{tcolorbox}[colback=white]
  5508. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5509. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5510. \end{tcolorbox}
  5511. \caption{A sudoku game board and the corresponding colored graph.}
  5512. \label{fig:sudoku-graph}
  5513. \end{figure}
  5514. Some techniques for playing sudoku correspond to heuristics used in
  5515. graph coloring algorithms. For example, one of the basic techniques
  5516. for sudoku is called Pencil Marks. The idea is to use a process of
  5517. elimination to determine what numbers are no longer available for a
  5518. square and to write those numbers in the square (writing very
  5519. small). For example, if the number $1$ is assigned to a square, then
  5520. write the pencil mark $1$ in all the squares in the same row, column,
  5521. and region to indicate that $1$ is no longer an option for those other
  5522. squares.
  5523. %
  5524. The Pencil Marks technique corresponds to the notion of
  5525. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5526. saturation of a vertex, in sudoku terms, is the set of numbers that
  5527. are no longer available. In graph terminology, we have the following
  5528. definition:
  5529. \begin{equation*}
  5530. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5531. \text{ and } \mathrm{color}(v) = c \}
  5532. \end{equation*}
  5533. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5534. edge with $u$.
  5535. The Pencil Marks technique leads to a simple strategy for filling in
  5536. numbers: if there is a square with only one possible number left, then
  5537. choose that number! But what if there are no squares with only one
  5538. possibility left? One brute-force approach is to try them all: choose
  5539. the first one, and if that ultimately leads to a solution, great. If
  5540. not, backtrack and choose the next possibility. One good thing about
  5541. Pencil Marks is that it reduces the degree of branching in the search
  5542. tree. Nevertheless, backtracking can be terribly time consuming. One
  5543. way to reduce the amount of backtracking is to use the
  5544. most-constrained-first heuristic (aka minimum remaining
  5545. values)~\citep{Russell2003}. That is, in choosing a square, always
  5546. choose one with the fewest possibilities left (the vertex with the
  5547. highest saturation). The idea is that choosing highly constrained
  5548. squares earlier rather than later is better, because later on there may
  5549. not be any possibilities left in the highly saturated squares.
  5550. However, register allocation is easier than sudoku, because the
  5551. register allocator can fall back to assigning variables to stack
  5552. locations when the registers run out. Thus, it makes sense to replace
  5553. backtracking with greedy search: make the best choice at the time and
  5554. keep going. We still wish to minimize the number of colors needed, so
  5555. we use the most-constrained-first heuristic in the greedy search.
  5556. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5557. algorithm for register allocation based on saturation and the
  5558. most-constrained-first heuristic. It is roughly equivalent to the
  5559. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5560. sudoku, the algorithm represents colors with integers. The integers
  5561. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5562. register allocation. In particular, we recommend the following
  5563. correspondence, with $k=11$.
  5564. \begin{lstlisting}
  5565. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5566. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5567. \end{lstlisting}
  5568. The integers $k$ and larger correspond to stack locations. The
  5569. registers that are not used for register allocation, such as
  5570. \code{rax}, are assigned to negative integers. In particular, we
  5571. recommend the following correspondence.
  5572. \begin{lstlisting}
  5573. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5574. \end{lstlisting}
  5575. \begin{figure}[btp]
  5576. \begin{tcolorbox}[colback=white]
  5577. \centering
  5578. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5579. Algorithm: DSATUR
  5580. Input: A graph |$G$|
  5581. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5582. |$W \gets \mathrm{vertices}(G)$|
  5583. while |$W \neq \emptyset$| do
  5584. pick a vertex |$u$| from |$W$| with the highest saturation,
  5585. breaking ties randomly
  5586. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5587. |$\mathrm{color}[u] \gets c$|
  5588. |$W \gets W - \{u\}$|
  5589. \end{lstlisting}
  5590. \end{tcolorbox}
  5591. \caption{The saturation-based greedy graph coloring algorithm.}
  5592. \label{fig:satur-algo}
  5593. \end{figure}
  5594. {\if\edition\racketEd
  5595. With the DSATUR algorithm in hand, let us return to the running
  5596. example and consider how to color the interference graph shown in
  5597. figure~\ref{fig:interfere}.
  5598. %
  5599. We start by assigning each register node to its own color. For
  5600. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5601. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5602. (To reduce clutter in the interference graph, we elide nodes
  5603. that do not have interference edges, such as \code{rcx}.)
  5604. The variables are not yet colored, so they are annotated with a dash. We
  5605. then update the saturation for vertices that are adjacent to a
  5606. register, obtaining the following annotated graph. For example, the
  5607. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5608. \code{rax} and \code{rsp}.
  5609. \[
  5610. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5611. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5612. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5613. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5614. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5615. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5616. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5617. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5618. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5619. \draw (t1) to (rax);
  5620. \draw (t1) to (z);
  5621. \draw (z) to (y);
  5622. \draw (z) to (w);
  5623. \draw (x) to (w);
  5624. \draw (y) to (w);
  5625. \draw (v) to (w);
  5626. \draw (v) to (rsp);
  5627. \draw (w) to (rsp);
  5628. \draw (x) to (rsp);
  5629. \draw (y) to (rsp);
  5630. \path[-.,bend left=15] (z) edge node {} (rsp);
  5631. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5632. \draw (rax) to (rsp);
  5633. \end{tikzpicture}
  5634. \]
  5635. The algorithm says to select a maximally saturated vertex. So, we pick
  5636. $\ttm{t}$ and color it with the first available integer, which is
  5637. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5638. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5639. \[
  5640. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5641. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5642. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5643. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5644. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5645. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5646. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5647. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5648. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5649. \draw (t1) to (rax);
  5650. \draw (t1) to (z);
  5651. \draw (z) to (y);
  5652. \draw (z) to (w);
  5653. \draw (x) to (w);
  5654. \draw (y) to (w);
  5655. \draw (v) to (w);
  5656. \draw (v) to (rsp);
  5657. \draw (w) to (rsp);
  5658. \draw (x) to (rsp);
  5659. \draw (y) to (rsp);
  5660. \path[-.,bend left=15] (z) edge node {} (rsp);
  5661. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5662. \draw (rax) to (rsp);
  5663. \end{tikzpicture}
  5664. \]
  5665. We repeat the process, selecting a maximally saturated vertex,
  5666. choosing \code{z}, and coloring it with the first available number, which
  5667. is $1$. We add $1$ to the saturation for the neighboring vertices
  5668. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5669. \[
  5670. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5671. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5672. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5673. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5674. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5675. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5676. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5677. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5678. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5679. \draw (t1) to (rax);
  5680. \draw (t1) to (z);
  5681. \draw (z) to (y);
  5682. \draw (z) to (w);
  5683. \draw (x) to (w);
  5684. \draw (y) to (w);
  5685. \draw (v) to (w);
  5686. \draw (v) to (rsp);
  5687. \draw (w) to (rsp);
  5688. \draw (x) to (rsp);
  5689. \draw (y) to (rsp);
  5690. \path[-.,bend left=15] (z) edge node {} (rsp);
  5691. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5692. \draw (rax) to (rsp);
  5693. \end{tikzpicture}
  5694. \]
  5695. The most saturated vertices are now \code{w} and \code{y}. We color
  5696. \code{w} with the first available color, which is $0$.
  5697. \[
  5698. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5699. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5700. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5701. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5702. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5703. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5704. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5705. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5706. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5707. \draw (t1) to (rax);
  5708. \draw (t1) to (z);
  5709. \draw (z) to (y);
  5710. \draw (z) to (w);
  5711. \draw (x) to (w);
  5712. \draw (y) to (w);
  5713. \draw (v) to (w);
  5714. \draw (v) to (rsp);
  5715. \draw (w) to (rsp);
  5716. \draw (x) to (rsp);
  5717. \draw (y) to (rsp);
  5718. \path[-.,bend left=15] (z) edge node {} (rsp);
  5719. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5720. \draw (rax) to (rsp);
  5721. \end{tikzpicture}
  5722. \]
  5723. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5724. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5725. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5726. and \code{z}, whose colors are $0$ and $1$ respectively.
  5727. \[
  5728. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5729. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5730. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5731. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5732. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5733. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5734. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5735. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5736. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5737. \draw (t1) to (rax);
  5738. \draw (t1) to (z);
  5739. \draw (z) to (y);
  5740. \draw (z) to (w);
  5741. \draw (x) to (w);
  5742. \draw (y) to (w);
  5743. \draw (v) to (w);
  5744. \draw (v) to (rsp);
  5745. \draw (w) to (rsp);
  5746. \draw (x) to (rsp);
  5747. \draw (y) to (rsp);
  5748. \path[-.,bend left=15] (z) edge node {} (rsp);
  5749. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5750. \draw (rax) to (rsp);
  5751. \end{tikzpicture}
  5752. \]
  5753. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5754. \[
  5755. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5756. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5757. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5758. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5759. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5760. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5761. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5762. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5763. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5764. \draw (t1) to (rax);
  5765. \draw (t1) to (z);
  5766. \draw (z) to (y);
  5767. \draw (z) to (w);
  5768. \draw (x) to (w);
  5769. \draw (y) to (w);
  5770. \draw (v) to (w);
  5771. \draw (v) to (rsp);
  5772. \draw (w) to (rsp);
  5773. \draw (x) to (rsp);
  5774. \draw (y) to (rsp);
  5775. \path[-.,bend left=15] (z) edge node {} (rsp);
  5776. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5777. \draw (rax) to (rsp);
  5778. \end{tikzpicture}
  5779. \]
  5780. In the last step of the algorithm, we color \code{x} with $1$.
  5781. \[
  5782. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5783. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5784. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5785. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5786. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5787. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5788. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5789. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5790. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5791. \draw (t1) to (rax);
  5792. \draw (t1) to (z);
  5793. \draw (z) to (y);
  5794. \draw (z) to (w);
  5795. \draw (x) to (w);
  5796. \draw (y) to (w);
  5797. \draw (v) to (w);
  5798. \draw (v) to (rsp);
  5799. \draw (w) to (rsp);
  5800. \draw (x) to (rsp);
  5801. \draw (y) to (rsp);
  5802. \path[-.,bend left=15] (z) edge node {} (rsp);
  5803. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5804. \draw (rax) to (rsp);
  5805. \end{tikzpicture}
  5806. \]
  5807. So, we obtain the following coloring:
  5808. \[
  5809. \{
  5810. \ttm{rax} \mapsto -1,
  5811. \ttm{rsp} \mapsto -2,
  5812. \ttm{t} \mapsto 0,
  5813. \ttm{z} \mapsto 1,
  5814. \ttm{x} \mapsto 1,
  5815. \ttm{y} \mapsto 2,
  5816. \ttm{w} \mapsto 0,
  5817. \ttm{v} \mapsto 1
  5818. \}
  5819. \]
  5820. \fi}
  5821. %
  5822. {\if\edition\pythonEd\pythonColor
  5823. %
  5824. With the DSATUR algorithm in hand, let us return to the running
  5825. example and consider how to color the interference graph shown in
  5826. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5827. to indicate that it has not yet been assigned a color. Each register
  5828. node (not shown) should be assigned the number that the register
  5829. corresponds to, for example, color \code{rcx} with the number \code{0}
  5830. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5831. each node; all of them start as the empty set.
  5832. %
  5833. \[
  5834. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5835. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5836. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5837. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5838. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5839. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5840. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5841. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5842. \draw (t0) to (t1);
  5843. \draw (t0) to (z);
  5844. \draw (z) to (y);
  5845. \draw (z) to (w);
  5846. \draw (x) to (w);
  5847. \draw (y) to (w);
  5848. \draw (v) to (w);
  5849. \end{tikzpicture}
  5850. \]
  5851. The algorithm says to select a maximally saturated vertex, but they
  5852. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5853. and then we color it with the first available integer, which is $0$. We mark
  5854. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5855. they interfere with $\ttm{tmp\_0}$.
  5856. \[
  5857. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5858. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5859. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5860. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5861. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5862. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5863. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5864. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5865. \draw (t0) to (t1);
  5866. \draw (t0) to (z);
  5867. \draw (z) to (y);
  5868. \draw (z) to (w);
  5869. \draw (x) to (w);
  5870. \draw (y) to (w);
  5871. \draw (v) to (w);
  5872. \end{tikzpicture}
  5873. \]
  5874. We repeat the process. The most saturated vertices are \code{z} and
  5875. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5876. available number, which is $1$. We add $1$ to the saturation for the
  5877. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5878. \[
  5879. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5880. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5881. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5882. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5883. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5884. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5885. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5886. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5887. \draw (t0) to (t1);
  5888. \draw (t0) to (z);
  5889. \draw (z) to (y);
  5890. \draw (z) to (w);
  5891. \draw (x) to (w);
  5892. \draw (y) to (w);
  5893. \draw (v) to (w);
  5894. \end{tikzpicture}
  5895. \]
  5896. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5897. \code{y}. We color \code{w} with the first available color, which
  5898. is $0$.
  5899. \[
  5900. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5901. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5902. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5903. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5904. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5905. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5906. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5907. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5908. \draw (t0) to (t1);
  5909. \draw (t0) to (z);
  5910. \draw (z) to (y);
  5911. \draw (z) to (w);
  5912. \draw (x) to (w);
  5913. \draw (y) to (w);
  5914. \draw (v) to (w);
  5915. \end{tikzpicture}
  5916. \]
  5917. Now \code{y} is the most saturated, so we color it with $2$.
  5918. \[
  5919. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5920. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5921. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5922. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5923. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5924. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5925. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5926. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5927. \draw (t0) to (t1);
  5928. \draw (t0) to (z);
  5929. \draw (z) to (y);
  5930. \draw (z) to (w);
  5931. \draw (x) to (w);
  5932. \draw (y) to (w);
  5933. \draw (v) to (w);
  5934. \end{tikzpicture}
  5935. \]
  5936. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5937. We choose to color \code{v} with $1$.
  5938. \[
  5939. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5940. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5941. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5942. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5943. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5944. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5945. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5946. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5947. \draw (t0) to (t1);
  5948. \draw (t0) to (z);
  5949. \draw (z) to (y);
  5950. \draw (z) to (w);
  5951. \draw (x) to (w);
  5952. \draw (y) to (w);
  5953. \draw (v) to (w);
  5954. \end{tikzpicture}
  5955. \]
  5956. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5957. \[
  5958. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5959. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5960. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5961. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5962. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5963. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5964. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5965. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5966. \draw (t0) to (t1);
  5967. \draw (t0) to (z);
  5968. \draw (z) to (y);
  5969. \draw (z) to (w);
  5970. \draw (x) to (w);
  5971. \draw (y) to (w);
  5972. \draw (v) to (w);
  5973. \end{tikzpicture}
  5974. \]
  5975. So, we obtain the following coloring:
  5976. \[
  5977. \{ \ttm{tmp\_0} \mapsto 0,
  5978. \ttm{tmp\_1} \mapsto 1,
  5979. \ttm{z} \mapsto 1,
  5980. \ttm{x} \mapsto 1,
  5981. \ttm{y} \mapsto 2,
  5982. \ttm{w} \mapsto 0,
  5983. \ttm{v} \mapsto 1 \}
  5984. \]
  5985. \fi}
  5986. We recommend creating an auxiliary function named \code{color\_graph}
  5987. that takes an interference graph and a list of all the variables in
  5988. the program. This function should return a mapping of variables to
  5989. their colors (represented as natural numbers). By creating this helper
  5990. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5991. when we add support for functions.
  5992. To prioritize the processing of highly saturated nodes inside the
  5993. \code{color\_graph} function, we recommend using the priority queue
  5994. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5995. addition, you will need to maintain a mapping from variables to their
  5996. handles in the priority queue so that you can notify the priority
  5997. queue when their saturation changes.}
  5998. {\if\edition\racketEd
  5999. \begin{figure}[tp]
  6000. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6001. \small
  6002. \begin{tcolorbox}[title=Priority Queue]
  6003. A \emph{priority queue}\index{subject}{priority queue}
  6004. is a collection of items in which the
  6005. removal of items is governed by priority. In a \emph{min} queue,
  6006. lower priority items are removed first. An implementation is in
  6007. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6008. \begin{description}
  6009. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6010. priority queue that uses the $\itm{cmp}$ predicate to determine
  6011. whether its first argument has lower or equal priority to its
  6012. second argument.
  6013. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6014. items in the queue.
  6015. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6016. the item into the queue and returns a handle for the item in the
  6017. queue.
  6018. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6019. the lowest priority.
  6020. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6021. notifies the queue that the priority has decreased for the item
  6022. associated with the given handle.
  6023. \end{description}
  6024. \end{tcolorbox}
  6025. %\end{wrapfigure}
  6026. \caption{The priority queue data structure.}
  6027. \label{fig:priority-queue}
  6028. \end{figure}
  6029. \fi}
  6030. With the coloring complete, we finalize the assignment of variables to
  6031. registers and stack locations. We map the first $k$ colors to the $k$
  6032. registers and the rest of the colors to stack locations. Suppose for
  6033. the moment that we have just one register to use for register
  6034. allocation, \key{rcx}. Then we have the following assignment.
  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. \begin{center}
  6066. {\if\edition\racketEd
  6067. \begin{minipage}{0.35\textwidth}
  6068. \begin{lstlisting}
  6069. movq $1, v
  6070. movq $42, w
  6071. movq v, x
  6072. addq $7, x
  6073. movq x, y
  6074. movq x, z
  6075. addq w, z
  6076. movq y, t
  6077. negq t
  6078. movq z, %rax
  6079. addq t, %rax
  6080. jmp conclusion
  6081. \end{lstlisting}
  6082. \end{minipage}
  6083. $\Rightarrow\qquad$
  6084. \begin{minipage}{0.45\textwidth}
  6085. \begin{lstlisting}
  6086. movq $1, -8(%rbp)
  6087. movq $42, %rcx
  6088. movq -8(%rbp), -8(%rbp)
  6089. addq $7, -8(%rbp)
  6090. movq -8(%rbp), -16(%rbp)
  6091. movq -8(%rbp), -8(%rbp)
  6092. addq %rcx, -8(%rbp)
  6093. movq -16(%rbp), %rcx
  6094. negq %rcx
  6095. movq -8(%rbp), %rax
  6096. addq %rcx, %rax
  6097. jmp conclusion
  6098. \end{lstlisting}
  6099. \end{minipage}
  6100. \fi}
  6101. {\if\edition\pythonEd\pythonColor
  6102. \begin{minipage}{0.35\textwidth}
  6103. \begin{lstlisting}
  6104. movq $1, v
  6105. movq $42, w
  6106. movq v, x
  6107. addq $7, x
  6108. movq x, y
  6109. movq x, z
  6110. addq w, z
  6111. movq y, tmp_0
  6112. negq tmp_0
  6113. movq z, tmp_1
  6114. addq tmp_0, tmp_1
  6115. movq tmp_1, %rdi
  6116. callq print_int
  6117. \end{lstlisting}
  6118. \end{minipage}
  6119. $\Rightarrow\qquad$
  6120. \begin{minipage}{0.45\textwidth}
  6121. \begin{lstlisting}
  6122. movq $1, -8(%rbp)
  6123. movq $42, %rcx
  6124. movq -8(%rbp), -8(%rbp)
  6125. addq $7, -8(%rbp)
  6126. movq -8(%rbp), -16(%rbp)
  6127. movq -8(%rbp), -8(%rbp)
  6128. addq %rcx, -8(%rbp)
  6129. movq -16(%rbp), %rcx
  6130. negq %rcx
  6131. movq -8(%rbp), -8(%rbp)
  6132. addq %rcx, -8(%rbp)
  6133. movq -8(%rbp), %rdi
  6134. callq print_int
  6135. \end{lstlisting}
  6136. \end{minipage}
  6137. \fi}
  6138. \end{center}
  6139. \begin{exercise}\normalfont\normalsize
  6140. Implement the \code{allocate\_registers} pass.
  6141. Create five programs that exercise all aspects of the register
  6142. allocation algorithm, including spilling variables to the stack.
  6143. %
  6144. {\if\edition\racketEd
  6145. Replace \code{assign\_homes} in the list of \code{passes} in the
  6146. \code{run-tests.rkt} script with the three new passes:
  6147. \code{uncover\_live}, \code{build\_interference}, and
  6148. \code{allocate\_registers}.
  6149. Temporarily remove the call to \code{compiler-tests}.
  6150. Run the script to test the register allocator.
  6151. \fi}
  6152. %
  6153. {\if\edition\pythonEd\pythonColor
  6154. Run the \code{run-tests.py} script to check whether the
  6155. output programs produce the same result as the input programs.
  6156. \fi}
  6157. \end{exercise}
  6158. \section{Patch Instructions}
  6159. \label{sec:patch-instructions}
  6160. The remaining step in the compilation to x86 is to ensure that the
  6161. instructions have at most one argument that is a memory access.
  6162. %
  6163. In the running example, the instruction \code{movq -8(\%rbp),
  6164. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6165. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6166. then move \code{rax} into \code{-16(\%rbp)}.
  6167. %
  6168. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6169. problematic, but they can simply be deleted. In general, we recommend
  6170. deleting all the trivial moves whose source and destination are the
  6171. same location.
  6172. %
  6173. The following is the output of \code{patch\_instructions} on the
  6174. running example.
  6175. \begin{center}
  6176. {\if\edition\racketEd
  6177. \begin{minipage}{0.35\textwidth}
  6178. \begin{lstlisting}
  6179. movq $1, -8(%rbp)
  6180. movq $42, %rcx
  6181. movq -8(%rbp), -8(%rbp)
  6182. addq $7, -8(%rbp)
  6183. movq -8(%rbp), -16(%rbp)
  6184. movq -8(%rbp), -8(%rbp)
  6185. addq %rcx, -8(%rbp)
  6186. movq -16(%rbp), %rcx
  6187. negq %rcx
  6188. movq -8(%rbp), %rax
  6189. addq %rcx, %rax
  6190. jmp conclusion
  6191. \end{lstlisting}
  6192. \end{minipage}
  6193. $\Rightarrow\qquad$
  6194. \begin{minipage}{0.45\textwidth}
  6195. \begin{lstlisting}
  6196. movq $1, -8(%rbp)
  6197. movq $42, %rcx
  6198. addq $7, -8(%rbp)
  6199. movq -8(%rbp), %rax
  6200. movq %rax, -16(%rbp)
  6201. addq %rcx, -8(%rbp)
  6202. movq -16(%rbp), %rcx
  6203. negq %rcx
  6204. movq -8(%rbp), %rax
  6205. addq %rcx, %rax
  6206. jmp conclusion
  6207. \end{lstlisting}
  6208. \end{minipage}
  6209. \fi}
  6210. {\if\edition\pythonEd\pythonColor
  6211. \begin{minipage}{0.35\textwidth}
  6212. \begin{lstlisting}
  6213. movq $1, -8(%rbp)
  6214. movq $42, %rcx
  6215. movq -8(%rbp), -8(%rbp)
  6216. addq $7, -8(%rbp)
  6217. movq -8(%rbp), -16(%rbp)
  6218. movq -8(%rbp), -8(%rbp)
  6219. addq %rcx, -8(%rbp)
  6220. movq -16(%rbp), %rcx
  6221. negq %rcx
  6222. movq -8(%rbp), -8(%rbp)
  6223. addq %rcx, -8(%rbp)
  6224. movq -8(%rbp), %rdi
  6225. callq print_int
  6226. \end{lstlisting}
  6227. \end{minipage}
  6228. $\Rightarrow\qquad$
  6229. \begin{minipage}{0.45\textwidth}
  6230. \begin{lstlisting}
  6231. movq $1, -8(%rbp)
  6232. movq $42, %rcx
  6233. addq $7, -8(%rbp)
  6234. movq -8(%rbp), %rax
  6235. movq %rax, -16(%rbp)
  6236. addq %rcx, -8(%rbp)
  6237. movq -16(%rbp), %rcx
  6238. negq %rcx
  6239. addq %rcx, -8(%rbp)
  6240. movq -8(%rbp), %rdi
  6241. callq print_int
  6242. \end{lstlisting}
  6243. \end{minipage}
  6244. \fi}
  6245. \end{center}
  6246. \begin{exercise}\normalfont\normalsize
  6247. %
  6248. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6249. %
  6250. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6251. %in the \code{run-tests.rkt} script.
  6252. %
  6253. Run the script to test the \code{patch\_instructions} pass.
  6254. \end{exercise}
  6255. \section{Generate Prelude and Conclusion}
  6256. \label{sec:print-x86-reg-alloc}
  6257. \index{subject}{calling conventions}
  6258. \index{subject}{prelude}\index{subject}{conclusion}
  6259. Recall that this pass generates the prelude and conclusion
  6260. instructions to satisfy the x86 calling conventions
  6261. (section~\ref{sec:calling-conventions}). With the addition of the
  6262. register allocator, the callee-saved registers used by the register
  6263. allocator must be saved in the prelude and restored in the conclusion.
  6264. In the \code{allocate\_registers} pass,
  6265. %
  6266. \racket{add an entry to the \itm{info}
  6267. of \code{X86Program} named \code{used\_callee}}
  6268. %
  6269. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6270. %
  6271. that stores the set of callee-saved registers that were assigned to
  6272. variables. The \code{prelude\_and\_conclusion} pass can then access
  6273. this information to decide which callee-saved registers need to be
  6274. saved and restored.
  6275. %
  6276. When calculating the amount to adjust the \code{rsp} in the prelude,
  6277. make sure to take into account the space used for saving the
  6278. callee-saved registers. Also, remember that the frame needs to be a
  6279. multiple of 16 bytes! We recommend using the following equation for
  6280. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6281. of stack locations used by spilled variables\footnote{Sometimes two or
  6282. more spilled variables are assigned to the same stack location, so
  6283. $S$ can be less than the number of spilled variables.} and $C$ be
  6284. the number of callee-saved registers that were
  6285. allocated\index{subject}{allocate} to
  6286. variables. The $\itm{align}$ function rounds a number up to the
  6287. nearest 16 bytes.
  6288. \[
  6289. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6290. \]
  6291. The reason we subtract $8\itm{C}$ in this equation is that the
  6292. prelude uses \code{pushq} to save each of the callee-saved registers,
  6293. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6294. \racket{An overview of all the passes involved in register
  6295. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6296. {\if\edition\racketEd
  6297. \begin{figure}[tbp]
  6298. \begin{tcolorbox}[colback=white]
  6299. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6300. \node (Lvar) at (0,2) {\large \LangVar{}};
  6301. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6302. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6303. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6304. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6305. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6306. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6307. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6308. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6309. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6310. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6311. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6312. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6313. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6314. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6315. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6316. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6317. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6318. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6319. \end{tikzpicture}
  6320. \end{tcolorbox}
  6321. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6322. \label{fig:reg-alloc-passes}
  6323. \end{figure}
  6324. \fi}
  6325. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6326. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6327. use of registers and the stack, we limit the register allocator for
  6328. this example to use just two registers: \code{rcx} (color $0$) and
  6329. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6330. \code{main} function, we push \code{rbx} onto the stack because it is
  6331. a callee-saved register and it was assigned to a variable by the
  6332. register allocator. We subtract \code{8} from the \code{rsp} at the
  6333. end of the prelude to reserve space for the one spilled variable.
  6334. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6335. Moving on to the program proper, we see how the registers were
  6336. allocated.
  6337. %
  6338. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6339. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6340. %
  6341. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6342. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6343. were assigned to \code{rbx}.}
  6344. %
  6345. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6346. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6347. callee-save register \code{rbx} onto the stack. The spilled variables
  6348. must be placed lower on the stack than the saved callee-save
  6349. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6350. \code{-16(\%rbp)}.
  6351. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6352. done in the prelude. We move the stack pointer up by \code{8} bytes
  6353. (the room for spilled variables), then pop the old values of
  6354. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6355. \code{retq} to return control to the operating system.
  6356. \begin{figure}[tbp]
  6357. \begin{minipage}{0.55\textwidth}
  6358. \begin{tcolorbox}[colback=white]
  6359. % var_test_28.rkt
  6360. % (use-minimal-set-of-registers! #t)
  6361. % 0 -> rcx
  6362. % 1 -> rbx
  6363. %
  6364. % t 0 rcx
  6365. % z 1 rbx
  6366. % w 0 rcx
  6367. % y 2 rbp -16
  6368. % v 1 rbx
  6369. % x 1 rbx
  6370. {\if\edition\racketEd
  6371. \begin{lstlisting}
  6372. start:
  6373. movq $1, %rbx
  6374. movq $42, %rcx
  6375. addq $7, %rbx
  6376. movq %rbx, -16(%rbp)
  6377. addq %rcx, %rbx
  6378. movq -16(%rbp), %rcx
  6379. negq %rcx
  6380. movq %rbx, %rax
  6381. addq %rcx, %rax
  6382. jmp conclusion
  6383. .globl main
  6384. main:
  6385. pushq %rbp
  6386. movq %rsp, %rbp
  6387. pushq %rbx
  6388. subq $8, %rsp
  6389. jmp start
  6390. conclusion:
  6391. addq $8, %rsp
  6392. popq %rbx
  6393. popq %rbp
  6394. retq
  6395. \end{lstlisting}
  6396. \fi}
  6397. {\if\edition\pythonEd\pythonColor
  6398. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6399. \begin{lstlisting}
  6400. .globl main
  6401. main:
  6402. pushq %rbp
  6403. movq %rsp, %rbp
  6404. pushq %rbx
  6405. subq $8, %rsp
  6406. movq $1, %rcx
  6407. movq $42, %rbx
  6408. addq $7, %rcx
  6409. movq %rcx, -16(%rbp)
  6410. addq %rbx, -16(%rbp)
  6411. negq %rcx
  6412. movq -16(%rbp), %rbx
  6413. addq %rcx, %rbx
  6414. movq %rbx, %rdi
  6415. callq print_int
  6416. addq $8, %rsp
  6417. popq %rbx
  6418. popq %rbp
  6419. retq
  6420. \end{lstlisting}
  6421. \fi}
  6422. \end{tcolorbox}
  6423. \end{minipage}
  6424. \caption{The x86 output from the running example
  6425. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6426. and \code{rcx}.}
  6427. \label{fig:running-example-x86}
  6428. \end{figure}
  6429. \begin{exercise}\normalfont\normalsize
  6430. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6431. %
  6432. \racket{
  6433. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6434. list of passes and the call to \code{compiler-tests}.}
  6435. %
  6436. Run the script to test the complete compiler for \LangVar{} that
  6437. performs register allocation.
  6438. \end{exercise}
  6439. \section{Challenge: Move Biasing}
  6440. \label{sec:move-biasing}
  6441. \index{subject}{move biasing}
  6442. This section describes an enhancement to the register allocator,
  6443. called move biasing, for students who are looking for an extra
  6444. challenge.
  6445. {\if\edition\racketEd
  6446. To motivate the need for move biasing we return to the running example,
  6447. but this time we use all the general purpose registers. So, we have
  6448. the following mapping of color numbers to registers.
  6449. \[
  6450. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6451. \]
  6452. Using the same assignment of variables to color numbers that was
  6453. produced by the register allocator described in the last section, we
  6454. get the following program.
  6455. \begin{center}
  6456. \begin{minipage}{0.35\textwidth}
  6457. \begin{lstlisting}
  6458. movq $1, v
  6459. movq $42, w
  6460. movq v, x
  6461. addq $7, x
  6462. movq x, y
  6463. movq x, z
  6464. addq w, z
  6465. movq y, t
  6466. negq t
  6467. movq z, %rax
  6468. addq t, %rax
  6469. jmp conclusion
  6470. \end{lstlisting}
  6471. \end{minipage}
  6472. $\Rightarrow\qquad$
  6473. \begin{minipage}{0.45\textwidth}
  6474. \begin{lstlisting}
  6475. movq $1, %rdx
  6476. movq $42, %rcx
  6477. movq %rdx, %rdx
  6478. addq $7, %rdx
  6479. movq %rdx, %rsi
  6480. movq %rdx, %rdx
  6481. addq %rcx, %rdx
  6482. movq %rsi, %rcx
  6483. negq %rcx
  6484. movq %rdx, %rax
  6485. addq %rcx, %rax
  6486. jmp conclusion
  6487. \end{lstlisting}
  6488. \end{minipage}
  6489. \end{center}
  6490. In this output code there are two \key{movq} instructions that
  6491. can be removed because their source and target are the same. However,
  6492. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6493. register, we could instead remove three \key{movq} instructions. We
  6494. can accomplish this by taking into account which variables appear in
  6495. \key{movq} instructions with which other variables.
  6496. \fi}
  6497. {\if\edition\pythonEd\pythonColor
  6498. %
  6499. To motivate the need for move biasing we return to the running example
  6500. and recall that in section~\ref{sec:patch-instructions} we were able to
  6501. remove three trivial move instructions from the running
  6502. example. However, we could remove another trivial move if we were able
  6503. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6504. We say that two variables $p$ and $q$ are \emph{move
  6505. related}\index{subject}{move related} if they participate together in
  6506. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6507. \key{movq} $q$\key{,} $p$.
  6508. %
  6509. Recall that we color variables that are more saturated before coloring
  6510. variables that are less saturated, and in the case of equally
  6511. saturated variables, we choose randomly. Now we break such ties by
  6512. giving preference to variables that have an available color that is
  6513. the same as the color of a move-related variable.
  6514. %
  6515. Furthermore, when the register allocator chooses a color for a
  6516. variable, it should prefer a color that has already been used for a
  6517. move-related variable if one exists (and assuming that they do not
  6518. interfere). This preference should not override the preference for
  6519. registers over stack locations. So, this preference should be used as
  6520. a tie breaker in choosing between two registers or in choosing between
  6521. two stack locations.
  6522. We recommend representing the move relationships in a graph, similarly
  6523. to how we represented interference. The following is the \emph{move
  6524. graph} for our example.
  6525. {\if\edition\racketEd
  6526. \[
  6527. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6528. \node (rax) at (0,0) {$\ttm{rax}$};
  6529. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6530. \node (t) at (0,2) {$\ttm{t}$};
  6531. \node (z) at (3,2) {$\ttm{z}$};
  6532. \node (x) at (6,2) {$\ttm{x}$};
  6533. \node (y) at (3,0) {$\ttm{y}$};
  6534. \node (w) at (6,0) {$\ttm{w}$};
  6535. \node (v) at (9,0) {$\ttm{v}$};
  6536. \draw (v) to (x);
  6537. \draw (x) to (y);
  6538. \draw (x) to (z);
  6539. \draw (y) to (t);
  6540. \end{tikzpicture}
  6541. \]
  6542. \fi}
  6543. %
  6544. {\if\edition\pythonEd\pythonColor
  6545. \[
  6546. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6547. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6548. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6549. \node (z) at (3,2) {$\ttm{z}$};
  6550. \node (x) at (6,2) {$\ttm{x}$};
  6551. \node (y) at (3,0) {$\ttm{y}$};
  6552. \node (w) at (6,0) {$\ttm{w}$};
  6553. \node (v) at (9,0) {$\ttm{v}$};
  6554. \draw (y) to (t0);
  6555. \draw (z) to (x);
  6556. \draw (z) to (t1);
  6557. \draw (x) to (y);
  6558. \draw (x) to (v);
  6559. \end{tikzpicture}
  6560. \]
  6561. \fi}
  6562. {\if\edition\racketEd
  6563. Now we replay the graph coloring, pausing to see the coloring of
  6564. \code{y}. Recall the following configuration. The most saturated vertices
  6565. were \code{w} and \code{y}.
  6566. \[
  6567. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6568. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6569. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6570. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6571. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6572. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6573. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6574. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6575. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6576. \draw (t1) to (rax);
  6577. \draw (t1) to (z);
  6578. \draw (z) to (y);
  6579. \draw (z) to (w);
  6580. \draw (x) to (w);
  6581. \draw (y) to (w);
  6582. \draw (v) to (w);
  6583. \draw (v) to (rsp);
  6584. \draw (w) to (rsp);
  6585. \draw (x) to (rsp);
  6586. \draw (y) to (rsp);
  6587. \path[-.,bend left=15] (z) edge node {} (rsp);
  6588. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6589. \draw (rax) to (rsp);
  6590. \end{tikzpicture}
  6591. \]
  6592. %
  6593. The last time, we chose to color \code{w} with $0$. This time, we see
  6594. that \code{w} is not move-related to any vertex, but \code{y} is
  6595. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6596. the same color as \code{t}.
  6597. \[
  6598. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6599. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6600. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6601. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6602. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6603. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6604. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6605. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6606. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6607. \draw (t1) to (rax);
  6608. \draw (t1) to (z);
  6609. \draw (z) to (y);
  6610. \draw (z) to (w);
  6611. \draw (x) to (w);
  6612. \draw (y) to (w);
  6613. \draw (v) to (w);
  6614. \draw (v) to (rsp);
  6615. \draw (w) to (rsp);
  6616. \draw (x) to (rsp);
  6617. \draw (y) to (rsp);
  6618. \path[-.,bend left=15] (z) edge node {} (rsp);
  6619. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6620. \draw (rax) to (rsp);
  6621. \end{tikzpicture}
  6622. \]
  6623. Now \code{w} is the most saturated, so we color it $2$.
  6624. \[
  6625. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6626. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6627. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6628. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6629. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6630. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6631. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6632. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6633. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6634. \draw (t1) to (rax);
  6635. \draw (t1) to (z);
  6636. \draw (z) to (y);
  6637. \draw (z) to (w);
  6638. \draw (x) to (w);
  6639. \draw (y) to (w);
  6640. \draw (v) to (w);
  6641. \draw (v) to (rsp);
  6642. \draw (w) to (rsp);
  6643. \draw (x) to (rsp);
  6644. \draw (y) to (rsp);
  6645. \path[-.,bend left=15] (z) edge node {} (rsp);
  6646. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6647. \draw (rax) to (rsp);
  6648. \end{tikzpicture}
  6649. \]
  6650. At this point, vertices \code{x} and \code{v} are most saturated, but
  6651. \code{x} is move related to \code{y} and \code{z}, so we color
  6652. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6653. \[
  6654. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6655. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6656. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6657. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6658. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6659. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6660. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6661. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6662. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6663. \draw (t1) to (rax);
  6664. \draw (t) to (z);
  6665. \draw (z) to (y);
  6666. \draw (z) to (w);
  6667. \draw (x) to (w);
  6668. \draw (y) to (w);
  6669. \draw (v) to (w);
  6670. \draw (v) to (rsp);
  6671. \draw (w) to (rsp);
  6672. \draw (x) to (rsp);
  6673. \draw (y) to (rsp);
  6674. \path[-.,bend left=15] (z) edge node {} (rsp);
  6675. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6676. \draw (rax) to (rsp);
  6677. \end{tikzpicture}
  6678. \]
  6679. \fi}
  6680. %
  6681. {\if\edition\pythonEd\pythonColor
  6682. Now we replay the graph coloring, pausing before the coloring of
  6683. \code{w}. Recall the following configuration. The most saturated vertices
  6684. were \code{tmp\_1}, \code{w}, and \code{y}.
  6685. \[
  6686. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6687. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6688. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6689. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6690. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6691. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6692. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6693. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6694. \draw (t0) to (t1);
  6695. \draw (t0) to (z);
  6696. \draw (z) to (y);
  6697. \draw (z) to (w);
  6698. \draw (x) to (w);
  6699. \draw (y) to (w);
  6700. \draw (v) to (w);
  6701. \end{tikzpicture}
  6702. \]
  6703. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6704. or \code{y}. Note, however, that \code{w} is not move related to any
  6705. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6706. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6707. \code{y} and color it $0$, we can delete another move instruction.
  6708. \[
  6709. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6710. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6711. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6712. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6713. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6714. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6715. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6716. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6717. \draw (t0) to (t1);
  6718. \draw (t0) to (z);
  6719. \draw (z) to (y);
  6720. \draw (z) to (w);
  6721. \draw (x) to (w);
  6722. \draw (y) to (w);
  6723. \draw (v) to (w);
  6724. \end{tikzpicture}
  6725. \]
  6726. Now \code{w} is the most saturated, so we color it $2$.
  6727. \[
  6728. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6729. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6730. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6731. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6732. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6733. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6734. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6735. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6736. \draw (t0) to (t1);
  6737. \draw (t0) to (z);
  6738. \draw (z) to (y);
  6739. \draw (z) to (w);
  6740. \draw (x) to (w);
  6741. \draw (y) to (w);
  6742. \draw (v) to (w);
  6743. \end{tikzpicture}
  6744. \]
  6745. To finish the coloring, \code{x} and \code{v} get $0$ and
  6746. \code{tmp\_1} gets $1$.
  6747. \[
  6748. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6749. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6750. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6751. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6752. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6753. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6754. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6755. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6756. \draw (t0) to (t1);
  6757. \draw (t0) to (z);
  6758. \draw (z) to (y);
  6759. \draw (z) to (w);
  6760. \draw (x) to (w);
  6761. \draw (y) to (w);
  6762. \draw (v) to (w);
  6763. \end{tikzpicture}
  6764. \]
  6765. \fi}
  6766. So, we have the following assignment of variables to registers.
  6767. {\if\edition\racketEd
  6768. \begin{gather*}
  6769. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6770. \ttm{w} \mapsto \key{\%rsi}, \,
  6771. \ttm{x} \mapsto \key{\%rcx}, \,
  6772. \ttm{y} \mapsto \key{\%rcx}, \,
  6773. \ttm{z} \mapsto \key{\%rdx}, \,
  6774. \ttm{t} \mapsto \key{\%rcx} \}
  6775. \end{gather*}
  6776. \fi}
  6777. {\if\edition\pythonEd\pythonColor
  6778. \begin{gather*}
  6779. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6780. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6781. \ttm{x} \mapsto \key{\%rcx}, \,
  6782. \ttm{y} \mapsto \key{\%rcx}, \\
  6783. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6784. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6785. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6786. \end{gather*}
  6787. \fi}
  6788. %
  6789. We apply this register assignment to the running example shown next,
  6790. on the left, to obtain the code in the middle. The
  6791. \code{patch\_instructions} then deletes the trivial moves to obtain
  6792. the code on the right.
  6793. {\if\edition\racketEd
  6794. \begin{center}
  6795. \begin{minipage}{0.2\textwidth}
  6796. \begin{lstlisting}
  6797. movq $1, v
  6798. movq $42, w
  6799. movq v, x
  6800. addq $7, x
  6801. movq x, y
  6802. movq x, z
  6803. addq w, z
  6804. movq y, t
  6805. negq t
  6806. movq z, %rax
  6807. addq t, %rax
  6808. jmp conclusion
  6809. \end{lstlisting}
  6810. \end{minipage}
  6811. $\Rightarrow\qquad$
  6812. \begin{minipage}{0.25\textwidth}
  6813. \begin{lstlisting}
  6814. movq $1, %rcx
  6815. movq $42, %rsi
  6816. movq %rcx, %rcx
  6817. addq $7, %rcx
  6818. movq %rcx, %rcx
  6819. movq %rcx, %rdx
  6820. addq %rsi, %rdx
  6821. movq %rcx, %rcx
  6822. negq %rcx
  6823. movq %rdx, %rax
  6824. addq %rcx, %rax
  6825. jmp conclusion
  6826. \end{lstlisting}
  6827. \end{minipage}
  6828. $\Rightarrow\qquad$
  6829. \begin{minipage}{0.23\textwidth}
  6830. \begin{lstlisting}
  6831. movq $1, %rcx
  6832. movq $42, %rsi
  6833. addq $7, %rcx
  6834. movq %rcx, %rdx
  6835. addq %rsi, %rdx
  6836. negq %rcx
  6837. movq %rdx, %rax
  6838. addq %rcx, %rax
  6839. jmp conclusion
  6840. \end{lstlisting}
  6841. \end{minipage}
  6842. \end{center}
  6843. \fi}
  6844. {\if\edition\pythonEd\pythonColor
  6845. \begin{center}
  6846. \begin{minipage}{0.20\textwidth}
  6847. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6848. movq $1, v
  6849. movq $42, w
  6850. movq v, x
  6851. addq $7, x
  6852. movq x, y
  6853. movq x, z
  6854. addq w, z
  6855. movq y, tmp_0
  6856. negq tmp_0
  6857. movq z, tmp_1
  6858. addq tmp_0, tmp_1
  6859. movq tmp_1, %rdi
  6860. callq _print_int
  6861. \end{lstlisting}
  6862. \end{minipage}
  6863. ${\Rightarrow\qquad}$
  6864. \begin{minipage}{0.35\textwidth}
  6865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6866. movq $1, %rcx
  6867. movq $42, -16(%rbp)
  6868. movq %rcx, %rcx
  6869. addq $7, %rcx
  6870. movq %rcx, %rcx
  6871. movq %rcx, -8(%rbp)
  6872. addq -16(%rbp), -8(%rbp)
  6873. movq %rcx, %rcx
  6874. negq %rcx
  6875. movq -8(%rbp), -8(%rbp)
  6876. addq %rcx, -8(%rbp)
  6877. movq -8(%rbp), %rdi
  6878. callq _print_int
  6879. \end{lstlisting}
  6880. \end{minipage}
  6881. ${\Rightarrow\qquad}$
  6882. \begin{minipage}{0.20\textwidth}
  6883. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6884. movq $1, %rcx
  6885. movq $42, -16(%rbp)
  6886. addq $7, %rcx
  6887. movq %rcx, -8(%rbp)
  6888. movq -16(%rbp), %rax
  6889. addq %rax, -8(%rbp)
  6890. negq %rcx
  6891. addq %rcx, -8(%rbp)
  6892. movq -8(%rbp), %rdi
  6893. callq print_int
  6894. \end{lstlisting}
  6895. \end{minipage}
  6896. \end{center}
  6897. \fi}
  6898. \begin{exercise}\normalfont\normalsize
  6899. Change your implementation of \code{allocate\_registers} to take move
  6900. biasing into account. Create two new tests that include at least one
  6901. opportunity for move biasing, and visually inspect the output x86
  6902. programs to make sure that your move biasing is working properly. Make
  6903. sure that your compiler still passes all the tests.
  6904. \end{exercise}
  6905. %To do: another neat challenge would be to do
  6906. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6907. %% \subsection{Output of the Running Example}
  6908. %% \label{sec:reg-alloc-output}
  6909. % challenge: prioritize variables based on execution frequencies
  6910. % and the number of uses of a variable
  6911. % challenge: enhance the coloring algorithm using Chaitin's
  6912. % approach of prioritizing high-degree variables
  6913. % by removing low-degree variables (coloring them later)
  6914. % from the interference graph
  6915. \section{Further Reading}
  6916. \label{sec:register-allocation-further-reading}
  6917. Early register allocation algorithms were developed for Fortran
  6918. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6919. of graph coloring began in the late 1970s and early 1980s with the
  6920. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6921. algorithm is based on the following observation of
  6922. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6923. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6924. $v$ removed is also $k$ colorable. To see why, suppose that the
  6925. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6926. different colors, but because there are fewer than $k$ neighbors, there
  6927. will be one or more colors left over to use for coloring $v$ in $G$.
  6928. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6929. less than $k$ from the graph and recursively colors the rest of the
  6930. graph. Upon returning from the recursion, it colors $v$ with one of
  6931. the available colors and returns. \citet{Chaitin:1982vn} augments
  6932. this algorithm to handle spilling as follows. If there are no vertices
  6933. of degree lower than $k$ then pick a vertex at random, spill it,
  6934. remove it from the graph, and proceed recursively to color the rest of
  6935. the graph.
  6936. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6937. move-related and that don't interfere with each other, in a process
  6938. called \emph{coalescing}. Although coalescing decreases the number of
  6939. moves, it can make the graph more difficult to
  6940. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6941. which two variables are merged only if they have fewer than $k$
  6942. neighbors of high degree. \citet{George:1996aa} observes that
  6943. conservative coalescing is sometimes too conservative and made it more
  6944. aggressive by iterating the coalescing with the removal of low-degree
  6945. vertices.
  6946. %
  6947. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6948. also proposed \emph{biased coloring}, in which a variable is assigned to
  6949. the same color as another move-related variable if possible, as
  6950. discussed in section~\ref{sec:move-biasing}.
  6951. %
  6952. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6953. performs coalescing, graph coloring, and spill code insertion until
  6954. all variables have been assigned a location.
  6955. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6956. spilled variables that don't have to be: a high-degree variable can be
  6957. colorable if many of its neighbors are assigned the same color.
  6958. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6959. high-degree vertex is not immediately spilled. Instead the decision is
  6960. deferred until after the recursive call, when it is apparent whether
  6961. there is an available color or not. We observe that this algorithm is
  6962. equivalent to the smallest-last ordering
  6963. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6964. be registers and the rest to be stack locations.
  6965. %% biased coloring
  6966. Earlier editions of the compiler course at Indiana University
  6967. \citep{Dybvig:2010aa} were based on the algorithm of
  6968. \citet{Briggs:1994kx}.
  6969. The smallest-last ordering algorithm is one of many \emph{greedy}
  6970. coloring algorithms. A greedy coloring algorithm visits all the
  6971. vertices in a particular order and assigns each one the first
  6972. available color. An \emph{offline} greedy algorithm chooses the
  6973. ordering up front, prior to assigning colors. The algorithm of
  6974. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6975. ordering does not depend on the colors assigned. Other orderings are
  6976. possible. For example, \citet{Chow:1984ys} ordered variables according
  6977. to an estimate of runtime cost.
  6978. An \emph{online} greedy coloring algorithm uses information about the
  6979. current assignment of colors to influence the order in which the
  6980. remaining vertices are colored. The saturation-based algorithm
  6981. described in this chapter is one such algorithm. We choose to use
  6982. saturation-based coloring because it is fun to introduce graph
  6983. coloring via sudoku!
  6984. A register allocator may choose to map each variable to just one
  6985. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6986. variable to one or more locations. The latter can be achieved by
  6987. \emph{live range splitting}, where a variable is replaced by several
  6988. variables that each handle part of its live
  6989. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6990. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6991. %% replacement algorithm, bottom-up local
  6992. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6993. %% Cooper: top-down (priority bassed), bottom-up
  6994. %% top-down
  6995. %% order variables by priority (estimated cost)
  6996. %% caveat: split variables into two groups:
  6997. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6998. %% color the constrained ones first
  6999. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7000. %% cite J. Cocke for an algorithm that colors variables
  7001. %% in a high-degree first ordering
  7002. %Register Allocation via Usage Counts, Freiburghouse CACM
  7003. \citet{Palsberg:2007si} observes that many of the interference graphs
  7004. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7005. that is, every cycle with four or more edges has an edge that is not
  7006. part of the cycle but that connects two vertices on the cycle. Such
  7007. graphs can be optimally colored by the greedy algorithm with a vertex
  7008. ordering determined by maximum cardinality search.
  7009. In situations in which compile time is of utmost importance, such as
  7010. in just-in-time compilers, graph coloring algorithms can be too
  7011. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7012. be more appropriate.
  7013. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7014. {\if\edition\racketEd
  7015. \addtocontents{toc}{\newpage}
  7016. \fi}
  7017. \chapter{Booleans and Conditionals}
  7018. \label{ch:Lif}
  7019. \setcounter{footnote}{0}
  7020. The \LangVar{} language has only a single kind of value, the
  7021. integers. In this chapter we add a second kind of value, the Booleans,
  7022. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7023. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7024. are written
  7025. \TRUE{}\index{subject}{True@\TRUE{}} and
  7026. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7027. language includes several operations that involve Booleans
  7028. (\key{and}\index{subject}{and@\ANDNAME{}},
  7029. \key{or}\index{subject}{or@\ORNAME{}},
  7030. \key{not}\index{subject}{not@\NOTNAME{}},
  7031. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7032. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7033. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7034. conditional expression\index{subject}{conditional expression}%
  7035. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7036. With the addition of \key{if}, programs can have
  7037. nontrivial control flow\index{subject}{control flow}, which
  7038. %
  7039. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7040. %
  7041. \python{impacts liveness analysis and motivates a new pass named
  7042. \code{explicate\_control}.}
  7043. %
  7044. Also, because we now have two kinds of values, we need to handle
  7045. programs that apply an operation to the wrong kind of value, such as
  7046. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7047. There are two language design options for such situations. One option
  7048. is to signal an error and the other is to provide a wider
  7049. interpretation of the operation. \racket{The Racket
  7050. language}\python{Python} uses a mixture of these two options,
  7051. depending on the operation and the kind of value. For example, the
  7052. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7053. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7054. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7055. %
  7056. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7057. in Racket because \code{car} expects a pair.}
  7058. %
  7059. \python{On the other hand, \code{1[0]} results in a runtime error
  7060. in Python because an ``\code{int} object is not subscriptable.''}
  7061. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7062. design choices as \racket{Racket}\python{Python}, except that much of the
  7063. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7064. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7065. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7066. \python{MyPy} reports a compile-time error
  7067. %
  7068. \racket{because Racket expects the type of the argument to be of the form
  7069. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7070. %
  7071. \python{stating that a ``value of type \code{int} is not indexable.''}
  7072. The \LangIf{} language performs type checking during compilation just as
  7073. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7074. the alternative choice, that is, a dynamically typed language like
  7075. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7076. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7077. restrictive, for example, rejecting \racket{\code{(not
  7078. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7079. fairly simple because the focus of this book is on compilation and not
  7080. type systems, about which there are already several excellent
  7081. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7082. This chapter is organized as follows. We begin by defining the syntax
  7083. and interpreter for the \LangIf{} language
  7084. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7085. checking (aka semantic analysis\index{subject}{semantic analysis})
  7086. and define a type checker for \LangIf{}
  7087. (section~\ref{sec:type-check-Lif}).
  7088. %
  7089. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7090. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7091. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7092. %
  7093. The remaining sections of this chapter discuss how Booleans and
  7094. conditional control flow require changes to the existing compiler
  7095. passes and the addition of new ones. We introduce the \code{shrink}
  7096. pass to translate some operators into others, thereby reducing the
  7097. number of operators that need to be handled in later passes.
  7098. %
  7099. The main event of this chapter is the \code{explicate\_control} pass
  7100. that is responsible for translating \code{if}s into conditional
  7101. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7102. %
  7103. Regarding register allocation, there is the interesting question of
  7104. how to handle conditional \code{goto}s during liveness analysis.
  7105. \section{The \LangIf{} Language}
  7106. \label{sec:lang-if}
  7107. Definitions of the concrete syntax and abstract syntax of the
  7108. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7109. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7110. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7111. literals\index{subject}{literals}
  7112. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7113. \python{, and the \code{if} statement}. We expand the set of
  7114. operators to include
  7115. \begin{enumerate}
  7116. \item the logical operators \key{and}, \key{or}, and \key{not},
  7117. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7118. for comparing integers or Booleans for equality, and
  7119. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7120. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7121. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7122. comparing integers.
  7123. \end{enumerate}
  7124. \racket{We reorganize the abstract syntax for the primitive
  7125. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7126. rule for all of them. This means that the grammar no longer checks
  7127. whether the arity of an operator matches the number of
  7128. arguments. That responsibility is moved to the type checker for
  7129. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7130. \newcommand{\LifGrammarRacket}{
  7131. \begin{array}{lcl}
  7132. \Type &::=& \key{Boolean} \\
  7133. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7134. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7135. \Exp &::=& \itm{bool}
  7136. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7137. \MID (\key{not}\;\Exp) \\
  7138. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7139. \end{array}
  7140. }
  7141. \newcommand{\LifASTRacket}{
  7142. \begin{array}{lcl}
  7143. \Type &::=& \key{Boolean} \\
  7144. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7145. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7146. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7147. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7148. \end{array}
  7149. }
  7150. \newcommand{\LintOpAST}{
  7151. \begin{array}{rcl}
  7152. \Type &::=& \key{Integer} \\
  7153. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7154. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7155. \end{array}
  7156. }
  7157. \newcommand{\LifGrammarPython}{
  7158. \begin{array}{rcl}
  7159. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7160. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7161. \MID \key{not}~\Exp \\
  7162. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7163. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7164. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7165. \end{array}
  7166. }
  7167. \newcommand{\LifASTPython}{
  7168. \begin{array}{lcl}
  7169. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7170. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7171. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7172. \Exp &::=& \BOOL{\itm{bool}}
  7173. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7174. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7175. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7176. &\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 constants \TRUE{} and \FALSE{}
  7257. evaluate to the corresponding Boolean values, which is
  7258. inherited from the interpreter for \LangInt{} (figure~\ref{fig:interp-Lint-class}).
  7259. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7260. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7261. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7262. \code{and}, \code{or}, and \code{not} behave according to propositional
  7263. logic. In addition, the \code{and} and \code{or} operations perform
  7264. \emph{short-circuit evaluation}.
  7265. %
  7266. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7267. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7268. %
  7269. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7270. evaluated if $e_1$ evaluates to \TRUE{}.
  7271. \racket{With the increase in the number of primitive operations, the
  7272. interpreter would become repetitive without some care. We refactor
  7273. the case for \code{Prim}, moving the code that differs with each
  7274. operation into the \code{interp\_op} method shown in
  7275. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7276. \code{or} operations separately because of their short-circuiting
  7277. behavior.}
  7278. \begin{figure}[tbp]
  7279. \begin{tcolorbox}[colback=white]
  7280. {\if\edition\racketEd
  7281. \begin{lstlisting}
  7282. (define interp-Lif-class
  7283. (class interp-Lvar-class
  7284. (super-new)
  7285. (define/public (interp_op op) ...)
  7286. (define/override ((interp_exp env) e)
  7287. (define recur (interp_exp env))
  7288. (match e
  7289. [(Bool b) b]
  7290. [(If cnd thn els)
  7291. (match (recur cnd)
  7292. [#t (recur thn)]
  7293. [#f (recur els)])]
  7294. [(Prim 'and (list e1 e2))
  7295. (match (recur e1)
  7296. [#t (match (recur e2) [#t #t] [#f #f])]
  7297. [#f #f])]
  7298. [(Prim 'or (list e1 e2))
  7299. (define v1 (recur e1))
  7300. (match v1
  7301. [#t #t]
  7302. [#f (match (recur e2) [#t #t] [#f #f])])]
  7303. [(Prim op args)
  7304. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7305. [else ((super interp_exp env) e)]))
  7306. ))
  7307. (define (interp_Lif p)
  7308. (send (new interp-Lif-class) interp_program p))
  7309. \end{lstlisting}
  7310. \fi}
  7311. {\if\edition\pythonEd\pythonColor
  7312. \begin{lstlisting}
  7313. class InterpLif(InterpLvar):
  7314. def interp_exp(self, e, env):
  7315. match e:
  7316. case IfExp(test, body, orelse):
  7317. if self.interp_exp(test, env):
  7318. return self.interp_exp(body, env)
  7319. else:
  7320. return self.interp_exp(orelse, env)
  7321. case UnaryOp(Not(), v):
  7322. return not self.interp_exp(v, env)
  7323. case BoolOp(And(), values):
  7324. if self.interp_exp(values[0], env):
  7325. return self.interp_exp(values[1], env)
  7326. else:
  7327. return False
  7328. case BoolOp(Or(), values):
  7329. if self.interp_exp(values[0], env):
  7330. return True
  7331. else:
  7332. return self.interp_exp(values[1], env)
  7333. case Compare(left, [cmp], [right]):
  7334. l = self.interp_exp(left, env)
  7335. r = self.interp_exp(right, env)
  7336. return self.interp_cmp(cmp)(l, r)
  7337. case _:
  7338. return super().interp_exp(e, env)
  7339. def interp_stmt(self, s, env, cont):
  7340. match s:
  7341. case If(test, body, orelse):
  7342. match self.interp_exp(test, env):
  7343. case True:
  7344. return self.interp_stmts(body + cont, env)
  7345. case False:
  7346. return self.interp_stmts(orelse + cont, env)
  7347. case _:
  7348. return super().interp_stmt(s, env, cont)
  7349. ...
  7350. \end{lstlisting}
  7351. \fi}
  7352. \end{tcolorbox}
  7353. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7354. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7355. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7356. \label{fig:interp-Lif}
  7357. \end{figure}
  7358. {\if\edition\racketEd
  7359. \begin{figure}[tbp]
  7360. \begin{tcolorbox}[colback=white]
  7361. \begin{lstlisting}
  7362. (define/public (interp_op op)
  7363. (match op
  7364. ['+ fx+]
  7365. ['- fx-]
  7366. ['read read-fixnum]
  7367. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7368. ['eq? (lambda (v1 v2)
  7369. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7370. (and (boolean? v1) (boolean? v2))
  7371. (and (vector? v1) (vector? v2)))
  7372. (eq? v1 v2)]))]
  7373. ['< (lambda (v1 v2)
  7374. (cond [(and (fixnum? v1) (fixnum? v2))
  7375. (< v1 v2)]))]
  7376. ['<= (lambda (v1 v2)
  7377. (cond [(and (fixnum? v1) (fixnum? v2))
  7378. (<= v1 v2)]))]
  7379. ['> (lambda (v1 v2)
  7380. (cond [(and (fixnum? v1) (fixnum? v2))
  7381. (> v1 v2)]))]
  7382. ['>= (lambda (v1 v2)
  7383. (cond [(and (fixnum? v1) (fixnum? v2))
  7384. (>= v1 v2)]))]
  7385. [else (error 'interp_op "unknown operator")]))
  7386. \end{lstlisting}
  7387. \end{tcolorbox}
  7388. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7389. \label{fig:interp-op-Lif}
  7390. \end{figure}
  7391. \fi}
  7392. {\if\edition\pythonEd\pythonColor
  7393. \begin{figure}
  7394. \begin{tcolorbox}[colback=white]
  7395. \begin{lstlisting}
  7396. class InterpLif(InterpLvar):
  7397. ...
  7398. def interp_cmp(self, cmp):
  7399. match cmp:
  7400. case Lt():
  7401. return lambda x, y: x < y
  7402. case LtE():
  7403. return lambda x, y: x <= y
  7404. case Gt():
  7405. return lambda x, y: x > y
  7406. case GtE():
  7407. return lambda x, y: x >= y
  7408. case Eq():
  7409. return lambda x, y: x == y
  7410. case NotEq():
  7411. return lambda x, y: x != y
  7412. \end{lstlisting}
  7413. \end{tcolorbox}
  7414. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7415. \label{fig:interp-cmp-Lif}
  7416. \end{figure}
  7417. \fi}
  7418. \section{Type Checking \LangIf{} Programs}
  7419. \label{sec:type-check-Lif}
  7420. It is helpful to think about type checking\index{subject}{type
  7421. checking} in two complementary ways. A type checker predicts the
  7422. type of value that will be produced by each expression in the program.
  7423. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7424. type checker should predict that {\if\edition\racketEd
  7425. \begin{lstlisting}
  7426. (+ 10 (- (+ 12 20)))
  7427. \end{lstlisting}
  7428. \fi}
  7429. {\if\edition\pythonEd\pythonColor
  7430. \begin{lstlisting}
  7431. 10 + -(12 + 20)
  7432. \end{lstlisting}
  7433. \fi}
  7434. \noindent produces a value of type \INTTY{}, whereas
  7435. {\if\edition\racketEd
  7436. \begin{lstlisting}
  7437. (and (not #f) #t)
  7438. \end{lstlisting}
  7439. \fi}
  7440. {\if\edition\pythonEd\pythonColor
  7441. \begin{lstlisting}
  7442. (not False) and True
  7443. \end{lstlisting}
  7444. \fi}
  7445. \noindent produces a value of type \BOOLTY{}.
  7446. A second way to think about type checking is that it enforces a set of
  7447. rules about which operators can be applied to which kinds of
  7448. values. For example, our type checker for \LangIf{} signals an error
  7449. for the following expression:
  7450. %
  7451. {\if\edition\racketEd
  7452. \begin{lstlisting}
  7453. (not (+ 10 (- (+ 12 20))))
  7454. \end{lstlisting}
  7455. \fi}
  7456. {\if\edition\pythonEd\pythonColor
  7457. \begin{lstlisting}
  7458. not (10 + -(12 + 20))
  7459. \end{lstlisting}
  7460. \fi}
  7461. \noindent The subexpression
  7462. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7463. \python{\code{(10 + -(12 + 20))}}
  7464. has type \INTTY{}, but the type checker enforces the rule that the
  7465. argument of \code{not} must be an expression of type \BOOLTY{}.
  7466. We implement type checking using classes and methods because they
  7467. provide the open recursion needed to reuse code as we extend the type
  7468. checker in subsequent chapters, analogous to the use of classes and methods
  7469. for the interpreters (section~\ref{sec:extensible-interp}).
  7470. We separate the type checker for the \LangVar{} subset into its own
  7471. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7472. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7473. from the type checker for \LangVar{}. These type checkers are in the
  7474. files
  7475. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7476. and
  7477. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7478. of the support code.
  7479. %
  7480. Each type checker is a structurally recursive function over the AST.
  7481. Given an input expression \code{e}, the type checker either signals an
  7482. error or returns \racket{an expression and its type.}\python{its type.}
  7483. %
  7484. \racket{It returns an expression because there are situations in which
  7485. we want to change or update the expression.}
  7486. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7487. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7488. constant is \INTTY{}. To handle variables, the type checker uses the
  7489. environment \code{env} to map variables to types.
  7490. %
  7491. \racket{Consider the case for \key{let}. We type check the
  7492. initializing expression to obtain its type \key{T} and then
  7493. associate type \code{T} with the variable \code{x} in the
  7494. environment used to type check the body of the \key{let}. Thus,
  7495. when the type checker encounters a use of variable \code{x}, it can
  7496. find its type in the environment.}
  7497. %
  7498. \python{Consider the case for assignment. We type check the
  7499. initializing expression to obtain its type \key{t}. If the variable
  7500. \code{id} is already in the environment because there was a
  7501. prior assignment, we check that this initializer has the same type
  7502. as the prior one. If this is the first assignment to the variable,
  7503. we associate type \code{t} with the variable \code{id} in the
  7504. environment. Thus, when the type checker encounters a use of
  7505. variable \code{x}, it can find its type in the environment.}
  7506. %
  7507. \racket{Regarding primitive operators, we recursively analyze the
  7508. arguments and then invoke \code{type\_check\_op} to check whether
  7509. the argument types are allowed.}
  7510. %
  7511. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7512. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7513. \racket{Several auxiliary methods are used in the type checker. The
  7514. method \code{operator-types} defines a dictionary that maps the
  7515. operator names to their parameter and return types. The
  7516. \code{type-equal?} method determines whether two types are equal,
  7517. which for now simply dispatches to \code{equal?} (deep
  7518. equality). The \code{check-type-equal?} method triggers an error if
  7519. the two types are not equal. The \code{type-check-op} method looks
  7520. up the operator in the \code{operator-types} dictionary and then
  7521. checks whether the argument types are equal to the parameter types.
  7522. The result is the return type of the operator.}
  7523. %
  7524. \python{The auxiliary method \code{check\_type\_equal} triggers
  7525. an error if the two types are not equal.}
  7526. \begin{figure}[tbp]
  7527. \begin{tcolorbox}[colback=white]
  7528. {\if\edition\racketEd
  7529. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7530. (define type-check-Lvar-class
  7531. (class object%
  7532. (super-new)
  7533. (define/public (operator-types)
  7534. '((+ . ((Integer Integer) . Integer))
  7535. (- . ((Integer Integer) . Integer))
  7536. (read . (() . Integer))))
  7537. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7538. (define/public (check-type-equal? t1 t2 e)
  7539. (unless (type-equal? t1 t2)
  7540. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7541. (define/public (type-check-op op arg-types e)
  7542. (match (dict-ref (operator-types) op)
  7543. [`(,param-types . ,return-type)
  7544. (for ([at arg-types] [pt param-types])
  7545. (check-type-equal? at pt e))
  7546. return-type]
  7547. [else (error 'type-check-op "unrecognized ~a" op)]))
  7548. (define/public (type-check-exp env)
  7549. (lambda (e)
  7550. (match e
  7551. [(Int n) (values (Int n) 'Integer)]
  7552. [(Var x) (values (Var x) (dict-ref env x))]
  7553. [(Let x e body)
  7554. (define-values (e^ Te) ((type-check-exp env) e))
  7555. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7556. (values (Let x e^ b) Tb)]
  7557. [(Prim op es)
  7558. (define-values (new-es ts)
  7559. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7560. (values (Prim op new-es) (type-check-op op ts e))]
  7561. [else (error 'type-check-exp "couldn't match" e)])))
  7562. (define/public (type-check-program e)
  7563. (match e
  7564. [(Program info body)
  7565. (define-values (body^ Tb) ((type-check-exp '()) body))
  7566. (check-type-equal? Tb 'Integer body)
  7567. (Program info body^)]
  7568. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7569. ))
  7570. (define (type-check-Lvar p)
  7571. (send (new type-check-Lvar-class) type-check-program p))
  7572. \end{lstlisting}
  7573. \fi}
  7574. {\if\edition\pythonEd\pythonColor
  7575. \begin{lstlisting}[escapechar=`]
  7576. class TypeCheckLvar:
  7577. def check_type_equal(self, t1, t2, e):
  7578. if t1 != t2:
  7579. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7580. raise Exception(msg)
  7581. def type_check_exp(self, e, env):
  7582. match e:
  7583. case BinOp(left, (Add() | Sub()), right):
  7584. l = self.type_check_exp(left, env)
  7585. check_type_equal(l, int, left)
  7586. r = self.type_check_exp(right, env)
  7587. check_type_equal(r, int, right)
  7588. return int
  7589. case UnaryOp(USub(), v):
  7590. t = self.type_check_exp(v, env)
  7591. check_type_equal(t, int, v)
  7592. return int
  7593. case Name(id):
  7594. return env[id]
  7595. case Constant(value) if isinstance(value, int):
  7596. return int
  7597. case Call(Name('input_int'), []):
  7598. return int
  7599. def type_check_stmts(self, ss, env):
  7600. if len(ss) == 0:
  7601. return
  7602. match ss[0]:
  7603. case Assign([Name(id)], value):
  7604. t = self.type_check_exp(value, env)
  7605. if id in env:
  7606. check_type_equal(env[id], t, value)
  7607. else:
  7608. env[id] = t
  7609. return self.type_check_stmts(ss[1:], env)
  7610. case Expr(Call(Name('print'), [arg])):
  7611. t = self.type_check_exp(arg, env)
  7612. check_type_equal(t, int, arg)
  7613. return self.type_check_stmts(ss[1:], env)
  7614. case Expr(value):
  7615. self.type_check_exp(value, env)
  7616. return self.type_check_stmts(ss[1:], env)
  7617. def type_check_P(self, p):
  7618. match p:
  7619. case Module(body):
  7620. self.type_check_stmts(body, {})
  7621. \end{lstlisting}
  7622. \fi}
  7623. \end{tcolorbox}
  7624. \caption{Type checker for the \LangVar{} language.}
  7625. \label{fig:type-check-Lvar}
  7626. \end{figure}
  7627. \begin{figure}[tbp]
  7628. \begin{tcolorbox}[colback=white]
  7629. {\if\edition\racketEd
  7630. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7631. (define type-check-Lif-class
  7632. (class type-check-Lvar-class
  7633. (super-new)
  7634. (inherit check-type-equal?)
  7635. (define/override (operator-types)
  7636. (append '((and . ((Boolean Boolean) . Boolean))
  7637. (or . ((Boolean Boolean) . Boolean))
  7638. (< . ((Integer Integer) . Boolean))
  7639. (<= . ((Integer Integer) . Boolean))
  7640. (> . ((Integer Integer) . Boolean))
  7641. (>= . ((Integer Integer) . Boolean))
  7642. (not . ((Boolean) . Boolean)))
  7643. (super operator-types)))
  7644. (define/override (type-check-exp env)
  7645. (lambda (e)
  7646. (match e
  7647. [(Bool b) (values (Bool b) 'Boolean)]
  7648. [(Prim 'eq? (list e1 e2))
  7649. (define-values (e1^ T1) ((type-check-exp env) e1))
  7650. (define-values (e2^ T2) ((type-check-exp env) e2))
  7651. (check-type-equal? T1 T2 e)
  7652. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7653. [(If cnd thn els)
  7654. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7655. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7656. (define-values (els^ Te) ((type-check-exp env) els))
  7657. (check-type-equal? Tc 'Boolean e)
  7658. (check-type-equal? Tt Te e)
  7659. (values (If cnd^ thn^ els^) Te)]
  7660. [else ((super type-check-exp env) e)])))
  7661. ))
  7662. (define (type-check-Lif p)
  7663. (send (new type-check-Lif-class) type-check-program p))
  7664. \end{lstlisting}
  7665. \fi}
  7666. {\if\edition\pythonEd\pythonColor
  7667. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7668. class TypeCheckLif(TypeCheckLvar):
  7669. def type_check_exp(self, e, env):
  7670. match e:
  7671. case Constant(value) if isinstance(value, bool):
  7672. return bool
  7673. case BinOp(left, Sub(), right):
  7674. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7675. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7676. return int
  7677. case UnaryOp(Not(), v):
  7678. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7679. return bool
  7680. case BoolOp(op, values):
  7681. left = values[0] ; right = values[1]
  7682. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7683. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7684. return bool
  7685. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7686. or isinstance(cmp, NotEq):
  7687. l = self.type_check_exp(left, env)
  7688. r = self.type_check_exp(right, env)
  7689. check_type_equal(l, r, e)
  7690. return bool
  7691. case Compare(left, [cmp], [right]):
  7692. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7693. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7694. return bool
  7695. case IfExp(test, body, orelse):
  7696. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7697. b = self.type_check_exp(body, env)
  7698. o = self.type_check_exp(orelse, env)
  7699. check_type_equal(b, o, e)
  7700. return b
  7701. case _:
  7702. return super().type_check_exp(e, env)
  7703. def type_check_stmts(self, ss, env):
  7704. if len(ss) == 0:
  7705. return
  7706. match ss[0]:
  7707. case If(test, body, orelse):
  7708. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7709. b = self.type_check_stmts(body, env)
  7710. o = self.type_check_stmts(orelse, env)
  7711. check_type_equal(b, o, ss[0])
  7712. return self.type_check_stmts(ss[1:], env)
  7713. case _:
  7714. return super().type_check_stmts(ss, env)
  7715. \end{lstlisting}
  7716. \fi}
  7717. \end{tcolorbox}
  7718. \caption{Type checker for the \LangIf{} language.}
  7719. \label{fig:type-check-Lif}
  7720. \end{figure}
  7721. The definition of the type checker for \LangIf{} is shown in
  7722. figure~\ref{fig:type-check-Lif}.
  7723. %
  7724. The type of a Boolean constant is \BOOLTY{}.
  7725. %
  7726. \racket{The \code{operator-types} function adds dictionary entries for
  7727. the new operators.}
  7728. %
  7729. \python{The logical \code{not} operator requires its argument to be a
  7730. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7731. and logical \code{or} operators.}
  7732. %
  7733. The equality operator requires the two arguments to have the same type,
  7734. and therefore we handle it separately from the other operators.
  7735. %
  7736. \python{The other comparisons (less-than, etc.) require their
  7737. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7738. %
  7739. The condition of an \code{if} must
  7740. be of \BOOLTY{} type, and the two branches must have the same type.
  7741. \begin{exercise}\normalfont\normalsize
  7742. Create ten new test programs in \LangIf{}. Half the programs should
  7743. have a type error.
  7744. \racket{For those programs, create an empty file with the
  7745. same base name and with file extension \code{.tyerr}. For example, if
  7746. the test \code{cond\_test\_14.rkt}
  7747. is expected to error, then create
  7748. an empty file named \code{cond\_test\_14.tyerr}.
  7749. 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 most of the operators in \LangIf{}, but
  7793. the arguments of operators are restricted to atomic expressions. The
  7794. \LangCIf{} language does not include \code{if} expressions, but it does
  7795. include a restricted form of \code{if} statement. The condition must be
  7796. a comparison, and the two branches may contain only \code{goto}
  7797. statements. These restrictions make it easier to translate \code{if}
  7798. statements to x86. The \LangCIf{} language also adds a \code{return}
  7799. statement to finish the program with a specified value.
  7800. %
  7801. The \key{CProgram} construct contains a dictionary mapping labels to
  7802. lists of statements that end with a \emph{tail} statement, which is
  7803. either a \code{return} statement, a \code{goto}, or an
  7804. \code{if} statement.
  7805. %
  7806. A \code{goto} transfers control to the sequence of statements
  7807. associated with its label.
  7808. %
  7809. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7810. and figure~\ref{fig:c1-syntax} shows its
  7811. abstract syntax.
  7812. %
  7813. \fi}
  7814. %
  7815. \newcommand{\CifGrammarRacket}{
  7816. \begin{array}{lcl}
  7817. \Atm &::=& \itm{bool} \\
  7818. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7819. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7820. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7821. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7822. \end{array}
  7823. }
  7824. \newcommand{\CifASTRacket}{
  7825. \begin{array}{lcl}
  7826. \Atm &::=& \BOOL{\itm{bool}} \\
  7827. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7828. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7829. \Tail &::= & \GOTO{\itm{label}} \\
  7830. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7831. \end{array}
  7832. }
  7833. \newcommand{\CifGrammarPython}{
  7834. \begin{array}{lcl}
  7835. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7836. \Exp &::= & \Atm \MID \CREAD{}
  7837. \MID \CUNIOP{\key{-}}{\Atm}
  7838. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7839. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7840. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7841. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7842. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7843. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7844. \end{array}
  7845. }
  7846. \newcommand{\CifASTPython}{
  7847. \begin{array}{lcl}
  7848. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7849. \Exp &::= & \Atm \MID \READ{}
  7850. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7851. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7852. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7853. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7854. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7855. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7856. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7857. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7858. \end{array}
  7859. }
  7860. \begin{figure}[tbp]
  7861. \begin{tcolorbox}[colback=white]
  7862. \small
  7863. {\if\edition\racketEd
  7864. \[
  7865. \begin{array}{l}
  7866. \gray{\CvarGrammarRacket} \\ \hline
  7867. \CifGrammarRacket \\
  7868. \begin{array}{lcl}
  7869. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7870. \end{array}
  7871. \end{array}
  7872. \]
  7873. \fi}
  7874. {\if\edition\pythonEd\pythonColor
  7875. \[
  7876. \begin{array}{l}
  7877. \CifGrammarPython \\
  7878. \begin{array}{lcl}
  7879. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7880. \end{array}
  7881. \end{array}
  7882. \]
  7883. \fi}
  7884. \end{tcolorbox}
  7885. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7886. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7887. \label{fig:c1-concrete-syntax}
  7888. \end{figure}
  7889. \begin{figure}[tp]
  7890. \begin{tcolorbox}[colback=white]
  7891. \small
  7892. {\if\edition\racketEd
  7893. \[
  7894. \begin{array}{l}
  7895. \gray{\CvarASTRacket} \\ \hline
  7896. \CifASTRacket \\
  7897. \begin{array}{lcl}
  7898. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7899. \end{array}
  7900. \end{array}
  7901. \]
  7902. \fi}
  7903. {\if\edition\pythonEd\pythonColor
  7904. \[
  7905. \begin{array}{l}
  7906. \CifASTPython \\
  7907. \begin{array}{lcl}
  7908. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7909. \end{array}
  7910. \end{array}
  7911. \]
  7912. \fi}
  7913. \end{tcolorbox}
  7914. \racket{
  7915. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7916. }
  7917. \index{subject}{Goto@\texttt{Goto}}
  7918. \index{subject}{Return@\texttt{Return}}
  7919. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7920. (figure~\ref{fig:c0-syntax})}.}
  7921. \label{fig:c1-syntax}
  7922. \end{figure}
  7923. \section{The \LangXIf{} Language}
  7924. \label{sec:x86-if}
  7925. \index{subject}{x86}
  7926. To implement Booleans, the new logical operations, the
  7927. comparison operations, and the \key{if} expression\python{ and
  7928. statement}, we delve further into the x86
  7929. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7930. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7931. subset of x86, which includes instructions for logical operations,
  7932. comparisons, and \racket{conditional} jumps.
  7933. %
  7934. \python{The abstract syntax for an \LangXIf{} program contains a
  7935. dictionary mapping labels to sequences of instructions, each of
  7936. which we refer to as a \emph{basic block}\index{subject}{basic
  7937. block}.}
  7938. As x86 does not provide direct support for Booleans, we take the usual
  7939. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7940. \code{False} as $0$.
  7941. Furthermore, x86 does not provide an instruction that directly
  7942. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7943. However, the \code{xorq} instruction can be used to encode \code{not}.
  7944. The \key{xorq} instruction takes two arguments, performs a pairwise
  7945. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7946. and writes the results into its second argument. Recall the following
  7947. truth table for exclusive-or:
  7948. \begin{center}
  7949. \begin{tabular}{l|cc}
  7950. & 0 & 1 \\ \hline
  7951. 0 & 0 & 1 \\
  7952. 1 & 1 & 0
  7953. \end{tabular}
  7954. \end{center}
  7955. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7956. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7957. for the bit $1$, the result is the opposite of the second bit. Thus,
  7958. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7959. the first argument, as follows, where $\Arg$ is the translation of
  7960. $\Atm$ to x86:
  7961. \[
  7962. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7963. \qquad\Rightarrow\qquad
  7964. \begin{array}{l}
  7965. \key{movq}~ \Arg\key{,} \Var\\
  7966. \key{xorq}~ \key{\$1,} \Var
  7967. \end{array}
  7968. \]
  7969. \newcommand{\GrammarXIf}{
  7970. \begin{array}{lcl}
  7971. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7972. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7973. \Arg &::=& \key{\%}\itm{bytereg}\\
  7974. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7975. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7976. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7977. \MID \key{set}cc~\Arg
  7978. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7979. &\MID& \key{j}cc~\itm{label} \\
  7980. \end{array}
  7981. }
  7982. \begin{figure}[tp]
  7983. \begin{tcolorbox}[colback=white]
  7984. \[
  7985. \begin{array}{l}
  7986. \gray{\GrammarXInt} \\ \hline
  7987. \GrammarXIf \\
  7988. \begin{array}{lcl}
  7989. \LangXIfM{} &::= & \key{.globl main} \\
  7990. & & \key{main:} \; \Instr\ldots
  7991. \end{array}
  7992. \end{array}
  7993. \]
  7994. \end{tcolorbox}
  7995. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7996. \label{fig:x86-1-concrete}
  7997. \end{figure}
  7998. \newcommand{\ASTXIfRacket}{
  7999. \begin{array}{lcl}
  8000. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8001. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8002. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8003. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8004. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8005. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8006. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8007. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8008. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8009. \end{array}
  8010. }
  8011. \newcommand{\ASTXIfPython}{
  8012. \begin{array}{lcl}
  8013. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8014. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8015. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8016. \MID \BYTEREG{\itm{bytereg}} \\
  8017. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8018. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8019. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8020. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8021. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8022. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8023. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8024. \end{array}
  8025. }
  8026. \begin{figure}[tp]
  8027. \begin{tcolorbox}[colback=white]
  8028. \small
  8029. {\if\edition\racketEd
  8030. \[\arraycolsep=3pt
  8031. \begin{array}{l}
  8032. \gray{\ASTXIntRacket} \\ \hline
  8033. \ASTXIfRacket \\
  8034. \begin{array}{lcl}
  8035. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8036. \end{array}
  8037. \end{array}
  8038. \]
  8039. \fi}
  8040. %
  8041. {\if\edition\pythonEd\pythonColor
  8042. \[
  8043. \begin{array}{l}
  8044. \gray{\ASTXIntPython} \\ \hline
  8045. \ASTXIfPython \\
  8046. \begin{array}{lcl}
  8047. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8048. \end{array}
  8049. \end{array}
  8050. \]
  8051. \fi}
  8052. \end{tcolorbox}
  8053. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8054. \label{fig:x86-1}
  8055. \end{figure}
  8056. Next we consider the x86 instructions that are relevant for compiling
  8057. the comparison operations. The \key{cmpq} instruction compares its two
  8058. arguments to determine whether one argument is less than, equal to, or
  8059. greater than the other argument. The \key{cmpq} instruction is unusual
  8060. regarding the order of its arguments and where the result is
  8061. placed. The argument order is backward: if you want to test whether
  8062. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8063. \key{cmpq} is placed in the special EFLAGS register. This register
  8064. cannot be accessed directly, but it can be queried by a number of
  8065. instructions, including the \key{set} instruction. The instruction
  8066. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8067. depending on whether the contents of the EFLAGS register matches the
  8068. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8069. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8070. The \key{set} instruction has a quirk in that its destination argument
  8071. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8072. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8073. register. Thankfully, the \key{movzbq} instruction can be used to
  8074. move from a single-byte register to a normal 64-bit register. The
  8075. abstract syntax for the \code{set} instruction differs from the
  8076. concrete syntax in that it separates the instruction name from the
  8077. condition code.
  8078. \python{The x86 instructions for jumping are relevant to the
  8079. compilation of \key{if} expressions.}
  8080. %
  8081. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8082. counter to the address of the instruction after the specified
  8083. label.}
  8084. %
  8085. \racket{The x86 instruction for conditional jump is relevant to the
  8086. compilation of \key{if} expressions.}
  8087. %
  8088. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8089. counter to point to the instruction after \itm{label}, depending on
  8090. whether the result in the EFLAGS register matches the condition code
  8091. \itm{cc}; otherwise, the jump instruction falls through to the next
  8092. instruction. Like the abstract syntax for \code{set}, the abstract
  8093. syntax for conditional jump separates the instruction name from the
  8094. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8095. corresponds to \code{jle foo}. Because the conditional jump instruction
  8096. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8097. a \key{cmpq} instruction to set the EFLAGS register.
  8098. \section{Shrink the \LangIf{} Language}
  8099. \label{sec:shrink-Lif}
  8100. The \code{shrink} pass translates some of the language features into
  8101. other features, thereby reducing the kinds of expressions in the
  8102. language. For example, the short-circuiting nature of the \code{and}
  8103. and \code{or} logical operators can be expressed using \code{if} as
  8104. follows.
  8105. \begin{align*}
  8106. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8107. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8108. \end{align*}
  8109. By performing these translations in the front end of the compiler,
  8110. subsequent passes of the compiler can be shorter.
  8111. On the other hand, translations sometimes reduce the efficiency of the
  8112. generated code by increasing the number of instructions. For example,
  8113. expressing subtraction in terms of addition and negation
  8114. \[
  8115. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8116. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8117. \]
  8118. produces code with two x86 instructions (\code{negq} and \code{addq})
  8119. instead of just one (\code{subq}). Thus, we do not recommend
  8120. translating subtraction into addition and negation.
  8121. \begin{exercise}\normalfont\normalsize
  8122. %
  8123. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8124. the language by translating them to \code{if} expressions in \LangIf{}.
  8125. %
  8126. Create four test programs that involve these operators.
  8127. %
  8128. {\if\edition\racketEd
  8129. In the \code{run-tests.rkt} script, add the following entry for
  8130. \code{shrink} to the list of passes (it should be the only pass at
  8131. this point).
  8132. \begin{lstlisting}
  8133. (list "shrink" shrink interp_Lif type-check-Lif)
  8134. \end{lstlisting}
  8135. This instructs \code{interp-tests} to run the interpreter
  8136. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8137. output of \code{shrink}.
  8138. \fi}
  8139. %
  8140. Run the script to test your compiler on all the test programs.
  8141. \end{exercise}
  8142. {\if\edition\racketEd
  8143. \section{Uniquify Variables}
  8144. \label{sec:uniquify-Lif}
  8145. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8146. \code{if} expressions.
  8147. \begin{exercise}\normalfont\normalsize
  8148. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8149. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8150. \begin{lstlisting}
  8151. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8152. \end{lstlisting}
  8153. Run the script to test your compiler.
  8154. \end{exercise}
  8155. \fi}
  8156. \section{Remove Complex Operands}
  8157. \label{sec:remove-complex-opera-Lif}
  8158. The output language of \code{remove\_complex\_operands} is
  8159. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8160. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8161. but the \code{if} expression is not. All three subexpressions of an
  8162. \code{if} are allowed to be complex expressions, but the operands of
  8163. the \code{not} operator and comparison operators must be atomic.
  8164. %
  8165. \python{We add a new language form, the \code{Begin} expression, to aid
  8166. in the translation of \code{if} expressions. When we recursively
  8167. process the two branches of the \code{if}, we generate temporary
  8168. variables and their initializing expressions. However, these
  8169. expressions may contain side effects and should be executed only
  8170. when the condition of the \code{if} is true (for the ``then''
  8171. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8172. provides a way to initialize the temporary variables within the two branches
  8173. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8174. form executes the statements $ss$ and then returns the result of
  8175. expression $e$.}
  8176. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8177. the new features in \LangIf{}. In recursively processing
  8178. subexpressions, recall that you should invoke \code{rco\_atom} when
  8179. the output needs to be an \Atm{} (as specified in the grammar for
  8180. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8181. \Exp{}. Regarding \code{if}, it is particularly important
  8182. \emph{not} to replace its condition with a temporary variable, because
  8183. that would interfere with the generation of high-quality output in the
  8184. upcoming \code{explicate\_control} pass.
  8185. \newcommand{\LifMonadASTRacket}{
  8186. \begin{array}{rcl}
  8187. \Atm &::=& \BOOL{\itm{bool}}\\
  8188. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8189. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8190. \MID \IF{\Exp}{\Exp}{\Exp}
  8191. \end{array}
  8192. }
  8193. \newcommand{\LifMonadASTPython}{
  8194. \begin{array}{rcl}
  8195. \Atm &::=& \BOOL{\itm{bool}}\\
  8196. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8197. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8198. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8199. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8200. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8201. \end{array}
  8202. }
  8203. \begin{figure}[tp]
  8204. \centering
  8205. \begin{tcolorbox}[colback=white]
  8206. {\if\edition\racketEd
  8207. \[
  8208. \begin{array}{l}
  8209. \gray{\LvarMonadASTRacket} \\ \hline
  8210. \LifMonadASTRacket \\
  8211. \begin{array}{rcl}
  8212. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8213. \end{array}
  8214. \end{array}
  8215. \]
  8216. \fi}
  8217. {\if\edition\pythonEd\pythonColor
  8218. \[
  8219. \begin{array}{l}
  8220. \gray{\LvarMonadASTPython} \\ \hline
  8221. \LifMonadASTPython \\
  8222. \begin{array}{rcl}
  8223. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8224. \end{array}
  8225. \end{array}
  8226. \]
  8227. \fi}
  8228. \end{tcolorbox}
  8229. \python{\index{subject}{Begin@\texttt{Begin}}}
  8230. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8231. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8232. \label{fig:Lif-anf-syntax}
  8233. \end{figure}
  8234. \begin{exercise}\normalfont\normalsize
  8235. %
  8236. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8237. and \code{rco\_exp} functions.
  8238. %
  8239. Create three new \LangIf{} programs that exercise the interesting
  8240. code in this pass.
  8241. %
  8242. {\if\edition\racketEd
  8243. In the \code{run-tests.rkt} script, add the following entry to the
  8244. list of \code{passes} and then run the script to test your compiler.
  8245. \begin{lstlisting}
  8246. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8247. \end{lstlisting}
  8248. \fi}
  8249. \end{exercise}
  8250. \section{Explicate Control}
  8251. \label{sec:explicate-control-Lif}
  8252. \racket{Recall that the purpose of \code{explicate\_control} is to
  8253. make the order of evaluation explicit in the syntax of the program.
  8254. With the addition of \key{if}, this becomes more interesting.}
  8255. %
  8256. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8257. %
  8258. The main challenge to overcome is that the condition of an \key{if}
  8259. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8260. condition must be a comparison.
  8261. As a motivating example, consider the following program that has an
  8262. \key{if} expression nested in the condition of another \key{if}:%
  8263. \python{\footnote{Programmers rarely write nested \code{if}
  8264. expressions, but they do write nested expressions involving
  8265. logical \code{and}, which, as we have seen, translates to
  8266. \code{if}.}}
  8267. % cond_test_41.rkt, if_lt_eq.py
  8268. \begin{center}
  8269. \begin{minipage}{0.96\textwidth}
  8270. {\if\edition\racketEd
  8271. \begin{lstlisting}
  8272. (let ([x (read)])
  8273. (let ([y (read)])
  8274. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8275. (+ y 2)
  8276. (+ y 10))))
  8277. \end{lstlisting}
  8278. \fi}
  8279. {\if\edition\pythonEd\pythonColor
  8280. \begin{lstlisting}
  8281. x = input_int()
  8282. y = input_int()
  8283. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8284. \end{lstlisting}
  8285. \fi}
  8286. \end{minipage}
  8287. \end{center}
  8288. %
  8289. The naive way to compile \key{if} and the comparison operations would
  8290. be to handle each of them in isolation, regardless of their context.
  8291. Each comparison would be translated into a \key{cmpq} instruction
  8292. followed by several instructions to move the result from the EFLAGS
  8293. register into a general purpose register or stack location. Each
  8294. \key{if} would be translated into a \key{cmpq} instruction followed by
  8295. a conditional jump. The generated code for the inner \key{if} in this
  8296. example would be as follows:
  8297. \begin{center}
  8298. \begin{minipage}{0.96\textwidth}
  8299. \begin{lstlisting}
  8300. cmpq $1, x
  8301. setl %al
  8302. movzbq %al, tmp
  8303. cmpq $1, tmp
  8304. je then_branch_1
  8305. jmp else_branch_1
  8306. \end{lstlisting}
  8307. \end{minipage}
  8308. \end{center}
  8309. Notice that the three instructions starting with \code{setl} are
  8310. redundant; the conditional jump could come immediately after the first
  8311. \code{cmpq}.
  8312. Our goal is to compile \key{if} expressions so that the relevant
  8313. comparison instruction appears directly before the conditional jump.
  8314. For example, we want to generate the following code for the inner
  8315. \code{if}:
  8316. \begin{center}
  8317. \begin{minipage}{0.96\textwidth}
  8318. \begin{lstlisting}
  8319. cmpq $1, x
  8320. jl then_branch_1
  8321. jmp else_branch_1
  8322. \end{lstlisting}
  8323. \end{minipage}
  8324. \end{center}
  8325. One way to achieve this goal is to reorganize the code at the level of
  8326. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8327. the following code:
  8328. \begin{center}
  8329. \begin{minipage}{0.96\textwidth}
  8330. {\if\edition\racketEd
  8331. \begin{lstlisting}
  8332. (let ([x (read)])
  8333. (let ([y (read)])
  8334. (if (< x 1)
  8335. (if (eq? x 0)
  8336. (+ y 2)
  8337. (+ y 10))
  8338. (if (eq? x 2)
  8339. (+ y 2)
  8340. (+ y 10)))))
  8341. \end{lstlisting}
  8342. \fi}
  8343. {\if\edition\pythonEd\pythonColor
  8344. \begin{lstlisting}
  8345. x = input_int()
  8346. y = input_int()
  8347. print(((y + 2) if x == 0 else (y + 10)) \
  8348. if (x < 1) \
  8349. else ((y + 2) if (x == 2) else (y + 10)))
  8350. \end{lstlisting}
  8351. \fi}
  8352. \end{minipage}
  8353. \end{center}
  8354. Unfortunately, this approach duplicates the two branches from the
  8355. outer \code{if}, and a compiler must never duplicate code! After all,
  8356. the two branches could be very large expressions.
  8357. How can we apply this transformation without duplicating code? In
  8358. other words, how can two different parts of a program refer to one
  8359. piece of code?
  8360. %
  8361. The answer is that we must move away from abstract syntax \emph{trees}
  8362. and instead use \emph{graphs}.
  8363. %
  8364. At the level of x86 assembly, this is straightforward because we can
  8365. label the code for each branch and insert jumps in all the places that
  8366. need to execute the branch. In this way, jump instructions are edges
  8367. in the graph and the basic blocks are the nodes.
  8368. %
  8369. Likewise, our language \LangCIf{} provides the ability to label a
  8370. sequence of statements and to jump to a label via \code{goto}.
  8371. As a preview of what \code{explicate\_control} will do,
  8372. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8373. \code{explicate\_control} on this example. Note how the condition of
  8374. every \code{if} is a comparison operation and that we have not
  8375. duplicated any code but instead have used labels and \code{goto} to
  8376. enable sharing of code.
  8377. \begin{figure}[tbp]
  8378. \begin{tcolorbox}[colback=white]
  8379. {\if\edition\racketEd
  8380. \begin{tabular}{lll}
  8381. \begin{minipage}{0.4\textwidth}
  8382. % cond_test_41.rkt
  8383. \begin{lstlisting}
  8384. (let ([x (read)])
  8385. (let ([y (read)])
  8386. (if (if (< x 1)
  8387. (eq? x 0)
  8388. (eq? x 2))
  8389. (+ y 2)
  8390. (+ y 10))))
  8391. \end{lstlisting}
  8392. \end{minipage}
  8393. &
  8394. $\Rightarrow$
  8395. &
  8396. \begin{minipage}{0.55\textwidth}
  8397. \begin{lstlisting}
  8398. start:
  8399. x = (read);
  8400. y = (read);
  8401. if (< x 1)
  8402. goto block_4;
  8403. else
  8404. goto block_5;
  8405. block_4:
  8406. if (eq? x 0)
  8407. goto block_2;
  8408. else
  8409. goto block_3;
  8410. block_5:
  8411. if (eq? x 2)
  8412. goto block_2;
  8413. else
  8414. goto block_3;
  8415. block_2:
  8416. return (+ y 2);
  8417. block_3:
  8418. return (+ y 10);
  8419. \end{lstlisting}
  8420. \end{minipage}
  8421. \end{tabular}
  8422. \fi}
  8423. {\if\edition\pythonEd\pythonColor
  8424. \begin{tabular}{lll}
  8425. \begin{minipage}{0.4\textwidth}
  8426. % tests/if/if_lt_eq.py
  8427. \begin{lstlisting}
  8428. x = input_int()
  8429. y = input_int()
  8430. print(y + 2 \
  8431. if (x == 0 \
  8432. if x < 1 \
  8433. else x == 2) \
  8434. else y + 10)
  8435. \end{lstlisting}
  8436. \end{minipage}
  8437. &
  8438. $\Rightarrow\qquad$
  8439. &
  8440. \begin{minipage}{0.55\textwidth}
  8441. \begin{lstlisting}
  8442. start:
  8443. x = input_int()
  8444. y = input_int()
  8445. if x < 1:
  8446. goto block_6
  8447. else:
  8448. goto block_7
  8449. block_6:
  8450. if x == 0:
  8451. goto block_4
  8452. else:
  8453. goto block_5
  8454. block_7:
  8455. if x == 2:
  8456. goto block_4
  8457. else:
  8458. goto block_5
  8459. block_4:
  8460. tmp.82 = (y + 2)
  8461. goto block_3
  8462. block_5:
  8463. tmp.82 = (y + 10)
  8464. goto block_3
  8465. block_3:
  8466. print(tmp.82)
  8467. return 0
  8468. \end{lstlisting}
  8469. \end{minipage}
  8470. \end{tabular}
  8471. \fi}
  8472. \end{tcolorbox}
  8473. \caption{Translation from \LangIf{} to \LangCIf{}
  8474. via the \code{explicate\_control}.}
  8475. \label{fig:explicate-control-s1-38}
  8476. \end{figure}
  8477. {\if\edition\racketEd
  8478. %
  8479. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8480. \code{explicate\_control} for \LangVar{} using two recursive
  8481. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8482. former function translates expressions in tail position, whereas the
  8483. latter function translates expressions on the right-hand side of a
  8484. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8485. have a new kind of position to deal with: the predicate position of
  8486. the \key{if}. We need another function, \code{explicate\_pred}, that
  8487. decides how to compile an \key{if} by analyzing its condition. So,
  8488. \code{explicate\_pred} takes an \LangIf{} expression and two
  8489. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8490. and outputs a tail. In the following paragraphs we discuss specific
  8491. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8492. \code{explicate\_pred} functions.
  8493. %
  8494. \fi}
  8495. %
  8496. {\if\edition\pythonEd\pythonColor
  8497. %
  8498. We recommend implementing \code{explicate\_control} using the
  8499. following four auxiliary functions.
  8500. \begin{description}
  8501. \item[\code{explicate\_effect}] generates code for expressions as
  8502. statements, so their result is ignored and only their side effects
  8503. matter.
  8504. \item[\code{explicate\_assign}] generates code for expressions
  8505. on the right-hand side of an assignment.
  8506. \item[\code{explicate\_pred}] generates code for an \code{if}
  8507. expression or statement by analyzing the condition expression.
  8508. \item[\code{explicate\_stmt}] generates code for statements.
  8509. \end{description}
  8510. These four functions should build the dictionary of basic blocks. The
  8511. following auxiliary function \code{create\_block} is used to create a
  8512. new basic block from a list of statements. If the list just contains a
  8513. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8514. \code{create\_block} creates a new basic block and returns a
  8515. \code{goto} to its label.
  8516. \begin{center}
  8517. \begin{minipage}{\textwidth}
  8518. \begin{lstlisting}
  8519. def create_block(stmts, basic_blocks):
  8520. match stmts:
  8521. case [Goto(l)]:
  8522. return stmts
  8523. case _:
  8524. label = label_name(generate_name('block'))
  8525. basic_blocks[label] = stmts
  8526. return [Goto(label)]
  8527. \end{lstlisting}
  8528. \end{minipage}
  8529. \end{center}
  8530. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8531. \code{explicate\_control} pass.
  8532. The \code{explicate\_effect} function has three parameters: (1) the
  8533. expression to be compiled; (2) the already-compiled code for this
  8534. expression's \emph{continuation}, that is, the list of statements that
  8535. should execute after this expression; and (3) the dictionary of
  8536. generated basic blocks. The \code{explicate\_effect} function returns
  8537. a list of \LangCIf{} statements and it may add to the dictionary of
  8538. basic blocks.
  8539. %
  8540. Let's consider a few of the cases for the expression to be compiled.
  8541. If the expression to be compiled is a constant, then it can be
  8542. discarded because it has no side effects. If it's a \CREAD{}, then it
  8543. has a side effect and should be preserved. So the expression should be
  8544. translated into a statement using the \code{Expr} AST class. If the
  8545. expression to be compiled is an \code{if} expression, we translate the
  8546. two branches using \code{explicate\_effect} and then translate the
  8547. condition expression using \code{explicate\_pred}, which generates
  8548. code for the entire \code{if}.
  8549. The \code{explicate\_assign} function has four parameters: (1) the
  8550. right-hand side of the assignment, (2) the left-hand side of the
  8551. assignment (the variable), (3) the continuation, and (4) the dictionary
  8552. of basic blocks. The \code{explicate\_assign} function returns a list
  8553. of \LangCIf{} statements, and it may add to the dictionary of basic
  8554. blocks.
  8555. When the right-hand side is an \code{if} expression, there is some
  8556. work to do. In particular, the two branches should be translated using
  8557. \code{explicate\_assign}, and the condition expression should be
  8558. translated using \code{explicate\_pred}. Otherwise we can simply
  8559. generate an assignment statement, with the given left- and right-hand
  8560. sides, concatenated with its continuation.
  8561. \begin{figure}[tbp]
  8562. \begin{tcolorbox}[colback=white]
  8563. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8564. def explicate_effect(e, cont, basic_blocks):
  8565. match e:
  8566. case IfExp(test, body, orelse):
  8567. ...
  8568. case Call(func, args):
  8569. ...
  8570. case Begin(body, result):
  8571. ...
  8572. case _:
  8573. ...
  8574. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8575. match rhs:
  8576. case IfExp(test, body, orelse):
  8577. ...
  8578. case Begin(body, result):
  8579. ...
  8580. case _:
  8581. return [Assign([lhs], rhs)] + cont
  8582. def explicate_pred(cnd, thn, els, basic_blocks):
  8583. match cnd:
  8584. case Compare(left, [op], [right]):
  8585. goto_thn = create_block(thn, basic_blocks)
  8586. goto_els = create_block(els, basic_blocks)
  8587. return [If(cnd, goto_thn, goto_els)]
  8588. case Constant(True):
  8589. return thn;
  8590. case Constant(False):
  8591. return els;
  8592. case UnaryOp(Not(), operand):
  8593. ...
  8594. case IfExp(test, body, orelse):
  8595. ...
  8596. case Begin(body, result):
  8597. ...
  8598. case _:
  8599. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8600. create_block(els, basic_blocks),
  8601. create_block(thn, basic_blocks))]
  8602. def explicate_stmt(s, cont, basic_blocks):
  8603. match s:
  8604. case Assign([lhs], rhs):
  8605. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8606. case Expr(value):
  8607. return explicate_effect(value, cont, basic_blocks)
  8608. case If(test, body, orelse):
  8609. ...
  8610. def explicate_control(p):
  8611. match p:
  8612. case Module(body):
  8613. new_body = [Return(Constant(0))]
  8614. basic_blocks = {}
  8615. for s in reversed(body):
  8616. new_body = explicate_stmt(s, new_body, basic_blocks)
  8617. basic_blocks[label_name('start')] = new_body
  8618. return CProgram(basic_blocks)
  8619. \end{lstlisting}
  8620. \end{tcolorbox}
  8621. \caption{Skeleton for the \code{explicate\_control} pass.}
  8622. \label{fig:explicate-control-Lif}
  8623. \end{figure}
  8624. \fi}
  8625. {\if\edition\racketEd
  8626. \subsection{Explicate Tail and Assign}
  8627. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8628. additional cases for Boolean constants and \key{if}. The cases for
  8629. \code{if} should recursively compile the two branches using either
  8630. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8631. cases should then invoke \code{explicate\_pred} on the condition
  8632. expression, passing in the generated code for the two branches. For
  8633. example, consider the following program with an \code{if} in tail
  8634. position.
  8635. % cond_test_6.rkt
  8636. \begin{lstlisting}
  8637. (let ([x (read)])
  8638. (if (eq? x 0) 42 777))
  8639. \end{lstlisting}
  8640. The two branches are recursively compiled to return statements. We
  8641. then delegate to \code{explicate\_pred}, passing the condition
  8642. \code{(eq? x 0)} and the two return statements. We return to this
  8643. example shortly when we discuss \code{explicate\_pred}.
  8644. Next let us consider a program with an \code{if} on the right-hand
  8645. side of a \code{let}.
  8646. \begin{lstlisting}
  8647. (let ([y (read)])
  8648. (let ([x (if (eq? y 0) 40 777)])
  8649. (+ x 2)))
  8650. \end{lstlisting}
  8651. Note that the body of the inner \code{let} will have already been
  8652. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8653. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8654. to recursively process both branches of the \code{if}, and we do not
  8655. want to duplicate code, so we generate the following block using an
  8656. auxiliary function named \code{create\_block}, discussed in the next
  8657. section.
  8658. \begin{lstlisting}
  8659. block_6:
  8660. return (+ x 2)
  8661. \end{lstlisting}
  8662. We then use \code{goto block\_6;} as the \code{cont} argument for
  8663. compiling the branches. So the two branches compile to
  8664. \begin{center}
  8665. \begin{minipage}{0.2\textwidth}
  8666. \begin{lstlisting}
  8667. x = 40;
  8668. goto block_6;
  8669. \end{lstlisting}
  8670. \end{minipage}
  8671. \hspace{0.5in} and \hspace{0.5in}
  8672. \begin{minipage}{0.2\textwidth}
  8673. \begin{lstlisting}
  8674. x = 777;
  8675. goto block_6;
  8676. \end{lstlisting}
  8677. \end{minipage}
  8678. \end{center}
  8679. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8680. \code{(eq? y 0)} and the previously presented code for the branches.
  8681. \subsection{Create Block}
  8682. We recommend implementing the \code{create\_block} auxiliary function
  8683. as follows, using a global variable \code{basic-blocks} to store a
  8684. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8685. that \code{create\_block} generates a new label and then associates
  8686. the given \code{tail} with the new label in the \code{basic-blocks}
  8687. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8688. new label. However, if the given \code{tail} is already a \code{Goto},
  8689. then there is no need to generate a new label and entry in
  8690. \code{basic-blocks}; we can simply return that \code{Goto}.
  8691. %
  8692. \begin{lstlisting}
  8693. (define (create_block tail)
  8694. (match tail
  8695. [(Goto label) (Goto label)]
  8696. [else
  8697. (let ([label (gensym 'block)])
  8698. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8699. (Goto label))]))
  8700. \end{lstlisting}
  8701. \fi}
  8702. {\if\edition\racketEd
  8703. \subsection{Explicate Predicate}
  8704. The skeleton for the \code{explicate\_pred} function is given in
  8705. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8706. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8707. the code generated by explicate for the \emph{then} branch; and (3)
  8708. \code{els}, the code generated by explicate for the \emph{else}
  8709. branch. The \code{explicate\_pred} function should match on
  8710. \code{cnd} with a case for every kind of expression that can have type
  8711. \BOOLTY{}.
  8712. \begin{figure}[tbp]
  8713. \begin{tcolorbox}[colback=white]
  8714. \begin{lstlisting}
  8715. (define (explicate_pred cnd thn els)
  8716. (match cnd
  8717. [(Var x) ___]
  8718. [(Let x rhs body) ___]
  8719. [(Prim 'not (list e)) ___]
  8720. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8721. (IfStmt (Prim op es) (create_block thn)
  8722. (create_block els))]
  8723. [(Bool b) (if b thn els)]
  8724. [(If cnd^ thn^ els^) ___]
  8725. [else (error "explicate_pred unhandled case" cnd)]))
  8726. \end{lstlisting}
  8727. \end{tcolorbox}
  8728. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8729. \label{fig:explicate-pred}
  8730. \end{figure}
  8731. \fi}
  8732. %
  8733. {\if\edition\pythonEd\pythonColor
  8734. The \code{explicate\_pred} function has four parameters: (1) the
  8735. condition expression, (2) the generated statements for the \emph{then}
  8736. branch, (3) the generated statements for the \emph{else} branch, and
  8737. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8738. function returns a list of statements, and it adds to the dictionary
  8739. of basic blocks.
  8740. \fi}
  8741. Consider the case for comparison operators. We translate the
  8742. comparison to an \code{if} statement whose branches are \code{goto}
  8743. statements created by applying \code{create\_block} to the \code{thn}
  8744. and \code{els} parameters. Let us illustrate this translation by
  8745. returning to the program with an \code{if} expression in tail
  8746. position, shown next. We invoke \code{explicate\_pred} on its
  8747. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8748. %
  8749. {\if\edition\racketEd
  8750. \begin{lstlisting}
  8751. (let ([x (read)])
  8752. (if (eq? x 0) 42 777))
  8753. \end{lstlisting}
  8754. \fi}
  8755. %
  8756. {\if\edition\pythonEd\pythonColor
  8757. \begin{lstlisting}
  8758. x = input_int()
  8759. 42 if x == 0 else 777
  8760. \end{lstlisting}
  8761. \fi}
  8762. %
  8763. \noindent The two branches \code{42} and \code{777} were already
  8764. compiled to \code{return} statements, from which we now create the
  8765. following blocks:
  8766. %
  8767. \begin{center}
  8768. \begin{minipage}{\textwidth}
  8769. \begin{lstlisting}
  8770. block_1:
  8771. return 42;
  8772. block_2:
  8773. return 777;
  8774. \end{lstlisting}
  8775. \end{minipage}
  8776. \end{center}
  8777. %
  8778. After that, \code{explicate\_pred} compiles the comparison
  8779. \racket{\code{(eq? x 0)}}
  8780. \python{\code{x == 0}}
  8781. to the following \code{if} statement:
  8782. %
  8783. {\if\edition\racketEd
  8784. \begin{center}
  8785. \begin{minipage}{\textwidth}
  8786. \begin{lstlisting}
  8787. if (eq? x 0)
  8788. goto block_1;
  8789. else
  8790. goto block_2;
  8791. \end{lstlisting}
  8792. \end{minipage}
  8793. \end{center}
  8794. \fi}
  8795. {\if\edition\pythonEd\pythonColor
  8796. \begin{center}
  8797. \begin{minipage}{\textwidth}
  8798. \begin{lstlisting}
  8799. if x == 0:
  8800. goto block_1;
  8801. else
  8802. goto block_2;
  8803. \end{lstlisting}
  8804. \end{minipage}
  8805. \end{center}
  8806. \fi}
  8807. Next consider the case for Boolean constants. We perform a kind of
  8808. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8809. either the \code{thn} or \code{els} parameter, depending on whether the
  8810. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8811. following program:
  8812. {\if\edition\racketEd
  8813. \begin{lstlisting}
  8814. (if #t 42 777)
  8815. \end{lstlisting}
  8816. \fi}
  8817. {\if\edition\pythonEd\pythonColor
  8818. \begin{lstlisting}
  8819. 42 if True else 777
  8820. \end{lstlisting}
  8821. \fi}
  8822. %
  8823. \noindent Again, the two branches \code{42} and \code{777} were
  8824. compiled to \code{return} statements, so \code{explicate\_pred}
  8825. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8826. code for the \emph{then} branch.
  8827. \begin{lstlisting}
  8828. return 42;
  8829. \end{lstlisting}
  8830. This case demonstrates that we sometimes discard the \code{thn} or
  8831. \code{els} blocks that are input to \code{explicate\_pred}.
  8832. The case for \key{if} expressions in \code{explicate\_pred} is
  8833. particularly illuminating because it deals with the challenges
  8834. discussed previously regarding nested \key{if} expressions
  8835. (figure~\ref{fig:explicate-control-s1-38}). The
  8836. \racket{\lstinline{thn^}}\python{\code{body}} and
  8837. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8838. \key{if} inherit their context from the current one, that is,
  8839. predicate context. So, you should recursively apply
  8840. \code{explicate\_pred} to the
  8841. \racket{\lstinline{thn^}}\python{\code{body}} and
  8842. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8843. those recursive calls, pass \code{thn} and \code{els} as the extra
  8844. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8845. inside each recursive call. As discussed previously, to avoid
  8846. duplicating code, we need to add them to the dictionary of basic
  8847. blocks so that we can instead refer to them by name and execute them
  8848. with a \key{goto}.
  8849. {\if\edition\pythonEd\pythonColor
  8850. %
  8851. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8852. three parameters: (1) the statement to be compiled, (2) the code for its
  8853. continuation, and (3) the dictionary of basic blocks. The
  8854. \code{explicate\_stmt} returns a list of statements, and it may add to
  8855. the dictionary of basic blocks. The cases for assignment and an
  8856. expression-statement are given in full in the skeleton code: they
  8857. simply dispatch to \code{explicate\_assign} and
  8858. \code{explicate\_effect}, respectively. The case for \code{if}
  8859. statements is not given; it is similar to the case for \code{if}
  8860. expressions.
  8861. The \code{explicate\_control} function itself is given in
  8862. figure~\ref{fig:explicate-control-Lif}. It applies
  8863. \code{explicate\_stmt} to each statement in the program, from back to
  8864. front. Thus, the result so far, stored in \code{new\_body}, can be
  8865. used as the continuation parameter in the next call to
  8866. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8867. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8868. the dictionary of basic blocks, labeling it the ``start'' block.
  8869. %
  8870. \fi}
  8871. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8872. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8873. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8874. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8875. %% results from the two recursive calls. We complete the case for
  8876. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8877. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8878. %% the result $B_5$.
  8879. %% \[
  8880. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8881. %% \quad\Rightarrow\quad
  8882. %% B_5
  8883. %% \]
  8884. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8885. %% inherit the current context, so they are in tail position. Thus, the
  8886. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8887. %% \code{explicate\_tail}.
  8888. %% %
  8889. %% We need to pass $B_0$ as the accumulator argument for both of these
  8890. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8891. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8892. %% to the control-flow graph and obtain a promised goto $G_0$.
  8893. %% %
  8894. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8895. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8896. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8897. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8898. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8899. %% \[
  8900. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8901. %% \]
  8902. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8903. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8904. %% should not be confused with the labels for the blocks that appear in
  8905. %% the generated code. We initially construct unlabeled blocks; we only
  8906. %% attach labels to blocks when we add them to the control-flow graph, as
  8907. %% we see in the next case.
  8908. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8909. %% function. The context of the \key{if} is an assignment to some
  8910. %% variable $x$ and then the control continues to some promised block
  8911. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8912. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8913. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8914. %% branches of the \key{if} inherit the current context, so they are in
  8915. %% assignment positions. Let $B_2$ be the result of applying
  8916. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8917. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8918. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8919. %% the result of applying \code{explicate\_pred} to the predicate
  8920. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8921. %% translates to the promise $B_4$.
  8922. %% \[
  8923. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8924. %% \]
  8925. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8926. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8927. \code{remove\_complex\_operands} pass and then the
  8928. \code{explicate\_control} pass on the example program. We walk through
  8929. the output program.
  8930. %
  8931. Following the order of evaluation in the output of
  8932. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8933. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8934. in the predicate of the inner \key{if}. In the output of
  8935. \code{explicate\_control}, in the
  8936. block labeled \code{start}, two assignment statements are followed by an
  8937. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8938. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8939. The blocks associated with those labels contain the
  8940. translations of the code
  8941. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8942. and
  8943. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8944. respectively. In particular, we start
  8945. \racket{\code{block\_4}}\python{\code{block\_6}}
  8946. with the comparison
  8947. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8948. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8949. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8950. which correspond to the two branches of the outer \key{if}, that is,
  8951. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8952. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8953. %
  8954. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8955. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8956. %
  8957. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8958. {\if\edition\racketEd
  8959. \subsection{Interactions between Explicate and Shrink}
  8960. The way in which the \code{shrink} pass transforms logical operations
  8961. such as \code{and} and \code{or} can impact the quality of code
  8962. generated by \code{explicate\_control}. For example, consider the
  8963. following program:
  8964. % cond_test_21.rkt, and_eq_input.py
  8965. \begin{lstlisting}
  8966. (if (and (eq? (read) 0) (eq? (read) 1))
  8967. 0
  8968. 42)
  8969. \end{lstlisting}
  8970. The \code{and} operation should transform into something that the
  8971. \code{explicate\_pred} function can analyze and descend through to
  8972. reach the underlying \code{eq?} conditions. Ideally, for this program
  8973. your \code{explicate\_control} pass should generate code similar to
  8974. the following:
  8975. \begin{center}
  8976. \begin{minipage}{\textwidth}
  8977. \begin{lstlisting}
  8978. start:
  8979. tmp1 = (read);
  8980. if (eq? tmp1 0) goto block40;
  8981. else goto block39;
  8982. block40:
  8983. tmp2 = (read);
  8984. if (eq? tmp2 1) goto block38;
  8985. else goto block39;
  8986. block38:
  8987. return 0;
  8988. block39:
  8989. return 42;
  8990. \end{lstlisting}
  8991. \end{minipage}
  8992. \end{center}
  8993. \fi}
  8994. \begin{exercise}\normalfont\normalsize
  8995. \racket{
  8996. Implement the pass \code{explicate\_control} by adding the cases for
  8997. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8998. \code{explicate\_assign} functions. Implement the auxiliary function
  8999. \code{explicate\_pred} for predicate contexts.}
  9000. \python{Implement \code{explicate\_control} pass with its
  9001. four auxiliary functions.}
  9002. %
  9003. Create test cases that exercise all the new cases in the code for
  9004. this pass.
  9005. %
  9006. {\if\edition\racketEd
  9007. Add the following entry to the list of \code{passes} in
  9008. \code{run-tests.rkt}:
  9009. \begin{lstlisting}
  9010. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9011. \end{lstlisting}
  9012. and then run \code{run-tests.rkt} to test your compiler.
  9013. \fi}
  9014. \end{exercise}
  9015. \section{Select Instructions}
  9016. \label{sec:select-Lif}
  9017. \index{subject}{select instructions}
  9018. The \code{select\_instructions} pass translates \LangCIf{} to
  9019. \LangXIfVar{}.
  9020. %
  9021. \racket{Recall that we implement this pass using three auxiliary
  9022. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9023. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9024. %
  9025. \racket{For $\Atm$, we have new cases for the Booleans.}
  9026. %
  9027. \python{We begin with the Boolean constants.}
  9028. As previously discussed, we encode them as integers.
  9029. \[
  9030. \TRUE{} \quad\Rightarrow\quad \key{1}
  9031. \qquad\qquad
  9032. \FALSE{} \quad\Rightarrow\quad \key{0}
  9033. \]
  9034. For translating statements, we discuss some of the cases. The
  9035. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9036. discussed at the beginning of this section. Given an assignment, if
  9037. the left-hand-side variable is the same as the argument of \code{not},
  9038. then just the \code{xorq} instruction suffices.
  9039. \[
  9040. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9041. \quad\Rightarrow\quad
  9042. \key{xorq}~\key{\$}1\key{,}~\Var
  9043. \]
  9044. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9045. semantics of x86. In the following translation, let $\Arg$ be the
  9046. result of translating $\Atm$ to x86.
  9047. \[
  9048. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9049. \quad\Rightarrow\quad
  9050. \begin{array}{l}
  9051. \key{movq}~\Arg\key{,}~\Var\\
  9052. \key{xorq}~\key{\$}1\key{,}~\Var
  9053. \end{array}
  9054. \]
  9055. Next consider the cases for equality comparisons. Translating this
  9056. operation to x86 is slightly involved due to the unusual nature of the
  9057. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9058. We recommend translating an assignment with an equality on the
  9059. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9060. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9061. \begin{tabular}{lll}
  9062. \begin{minipage}{0.4\textwidth}
  9063. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9064. \end{minipage}
  9065. &
  9066. $\Rightarrow$
  9067. &
  9068. \begin{minipage}{0.4\textwidth}
  9069. \begin{lstlisting}
  9070. cmpq |$\Arg_2$|, |$\Arg_1$|
  9071. sete %al
  9072. movzbq %al, |$\Var$|
  9073. \end{lstlisting}
  9074. \end{minipage}
  9075. \end{tabular} \\
  9076. The translations for the other comparison operators are similar to
  9077. this but use different condition codes for the \code{set} instruction.
  9078. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9079. \key{goto} and \key{if} statements. Both are straightforward to
  9080. translate to x86.}
  9081. %
  9082. A \key{goto} statement becomes a jump instruction.
  9083. \[
  9084. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9085. \]
  9086. %
  9087. An \key{if} statement becomes a compare instruction followed by a
  9088. conditional jump (for the \emph{then} branch), and the fall-through is to
  9089. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9090. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9091. \begin{tabular}{lll}
  9092. \begin{minipage}{0.4\textwidth}
  9093. \begin{lstlisting}
  9094. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9095. goto |$\ell_1$||$\racket{\key{;}}$|
  9096. else|$\python{\key{:}}$|
  9097. goto |$\ell_2$||$\racket{\key{;}}$|
  9098. \end{lstlisting}
  9099. \end{minipage}
  9100. &
  9101. $\Rightarrow$
  9102. &
  9103. \begin{minipage}{0.4\textwidth}
  9104. \begin{lstlisting}
  9105. cmpq |$\Arg_2$|, |$\Arg_1$|
  9106. je |$\ell_1$|
  9107. jmp |$\ell_2$|
  9108. \end{lstlisting}
  9109. \end{minipage}
  9110. \end{tabular} \\
  9111. Again, the translations for the other comparison operators are similar to this
  9112. but use different condition codes for the conditional jump instruction.
  9113. \python{Regarding the \key{return} statement, we recommend treating it
  9114. as an assignment to the \key{rax} register followed by a jump to the
  9115. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9116. \begin{exercise}\normalfont\normalsize
  9117. Expand your \code{select\_instructions} pass to handle the new
  9118. features of the \LangCIf{} language.
  9119. %
  9120. {\if\edition\racketEd
  9121. Add the following entry to the list of \code{passes} in
  9122. \code{run-tests.rkt}
  9123. \begin{lstlisting}
  9124. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9125. \end{lstlisting}
  9126. \fi}
  9127. %
  9128. Run the script to test your compiler on all the test programs.
  9129. \end{exercise}
  9130. \section{Register Allocation}
  9131. \label{sec:register-allocation-Lif}
  9132. \index{subject}{register allocation}
  9133. The changes required for compiling \LangIf{} affect liveness analysis,
  9134. building the interference graph, and assigning homes, but the graph
  9135. coloring algorithm itself does not change.
  9136. \subsection{Liveness Analysis}
  9137. \label{sec:liveness-analysis-Lif}
  9138. \index{subject}{liveness analysis}
  9139. Recall that for \LangVar{} we implemented liveness analysis for a
  9140. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9141. the addition of \key{if} expressions to \LangIf{},
  9142. \code{explicate\_control} produces many basic blocks.
  9143. %% We recommend that you create a new auxiliary function named
  9144. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9145. %% control-flow graph.
  9146. The first question is, in what order should we process the basic blocks?
  9147. Recall that to perform liveness analysis on a basic block we need to
  9148. know the live-after set for the last instruction in the block. If a
  9149. basic block has no successors (i.e., contains no jumps to other
  9150. blocks), then it has an empty live-after set and we can immediately
  9151. apply liveness analysis to it. If a basic block has some successors,
  9152. then we need to complete liveness analysis on those blocks
  9153. first. These ordering constraints are the reverse of a
  9154. \emph{topological order}\index{subject}{topological order} on a graph
  9155. representation of the program. In particular, the \emph{control flow
  9156. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9157. of a program has a node for each basic block and an edge for each jump
  9158. from one block to another. It is straightforward to generate a CFG
  9159. from the dictionary of basic blocks. One then transposes the CFG and
  9160. applies the topological sort algorithm.
  9161. %
  9162. %
  9163. \racket{We recommend using the \code{tsort} and \code{transpose}
  9164. functions of the Racket \code{graph} package to accomplish this.}
  9165. %
  9166. \python{We provide implementations of \code{topological\_sort} and
  9167. \code{transpose} in the file \code{graph.py} of the support code.}
  9168. %
  9169. As an aside, a topological ordering is only guaranteed to exist if the
  9170. graph does not contain any cycles. This is the case for the
  9171. control-flow graphs that we generate from \LangIf{} programs.
  9172. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9173. and learn how to handle cycles in the control-flow graph.
  9174. \racket{You need to construct a directed graph to represent the
  9175. control-flow graph. Do not use the \code{directed-graph} of the
  9176. \code{graph} package because that allows at most one edge
  9177. between each pair of vertices, whereas a control-flow graph may have
  9178. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9179. file in the support code implements a graph representation that
  9180. allows multiple edges between a pair of vertices.}
  9181. {\if\edition\racketEd
  9182. The next question is how to analyze jump instructions. Recall that in
  9183. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9184. \code{label->live} that maps each label to the set of live locations
  9185. at the beginning of its block. We use \code{label->live} to determine
  9186. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9187. that we have many basic blocks, \code{label->live} needs to be updated
  9188. as we process the blocks. In particular, after performing liveness
  9189. analysis on a block, we take the live-before set of its first
  9190. instruction and associate that with the block's label in the
  9191. \code{label->live} alist.
  9192. \fi}
  9193. %
  9194. {\if\edition\pythonEd\pythonColor
  9195. %
  9196. The next question is how to analyze jump instructions. The locations
  9197. that are live before a \code{jmp} should be the locations in
  9198. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9199. maintaining a dictionary named \code{live\_before\_block} that maps each
  9200. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9201. block. After performing liveness analysis on each block, we take the
  9202. live-before set of its first instruction and associate that with the
  9203. block's label in the \code{live\_before\_block} dictionary.
  9204. %
  9205. \fi}
  9206. In \LangXIfVar{} we also have the conditional jump
  9207. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9208. this instruction is particularly interesting because during
  9209. compilation, we do not know which way a conditional jump will go. Thus
  9210. we do not know whether to use the live-before set for the block
  9211. associated with the $\itm{label}$ or the live-before set for the
  9212. following instruction. So we use both, by taking the union of the
  9213. live-before sets from the following instruction and from the mapping
  9214. for $\itm{label}$ in
  9215. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9216. The auxiliary functions for computing the variables in an
  9217. instruction's argument and for computing the variables read-from ($R$)
  9218. or written-to ($W$) by an instruction need to be updated to handle the
  9219. new kinds of arguments and instructions in \LangXIfVar{}.
  9220. \begin{exercise}\normalfont\normalsize
  9221. {\if\edition\racketEd
  9222. %
  9223. Update the \code{uncover\_live} pass to apply liveness analysis to
  9224. every basic block in the program.
  9225. %
  9226. Add the following entry to the list of \code{passes} in the
  9227. \code{run-tests.rkt} script:
  9228. \begin{lstlisting}
  9229. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9230. \end{lstlisting}
  9231. \fi}
  9232. {\if\edition\pythonEd\pythonColor
  9233. %
  9234. Update the \code{uncover\_live} function to perform liveness analysis,
  9235. in reverse topological order, on all the basic blocks in the
  9236. program.
  9237. %
  9238. \fi}
  9239. % Check that the live-after sets that you generate for
  9240. % example X matches the following... -Jeremy
  9241. \end{exercise}
  9242. \subsection{Build the Interference Graph}
  9243. \label{sec:build-interference-Lif}
  9244. Many of the new instructions in \LangXIfVar{} can be handled in the
  9245. same way as the instructions in \LangXVar{}.
  9246. % Thus, if your code was
  9247. % already quite general, it will not need to be changed to handle the
  9248. % new instructions. If your code is not general enough, we recommend that
  9249. % you change your code to be more general. For example, you can factor
  9250. % out the computing of the the read and write sets for each kind of
  9251. % instruction into auxiliary functions.
  9252. %
  9253. Some instructions, such as the \key{movzbq} instruction, require special care,
  9254. similar to the \key{movq} instruction. Refer to rule number 1 in
  9255. section~\ref{sec:build-interference}.
  9256. \begin{exercise}\normalfont\normalsize
  9257. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9258. {\if\edition\racketEd
  9259. Add the following entries to the list of \code{passes} in the
  9260. \code{run-tests.rkt} script:
  9261. \begin{lstlisting}
  9262. (list "build_interference" build_interference interp-pseudo-x86-1)
  9263. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9264. \end{lstlisting}
  9265. \fi}
  9266. % Check that the interference graph that you generate for
  9267. % example X matches the following graph G... -Jeremy
  9268. \end{exercise}
  9269. \section{Patch Instructions}
  9270. The new instructions \key{cmpq} and \key{movzbq} have some special
  9271. restrictions that need to be handled in the \code{patch\_instructions}
  9272. pass.
  9273. %
  9274. The second argument of the \key{cmpq} instruction must not be an
  9275. immediate value (such as an integer). So, if you are comparing two
  9276. immediates, we recommend inserting a \key{movq} instruction to put the
  9277. second argument in \key{rax}. On the other hand, if you implemented
  9278. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9279. update it for \LangIf{} and then this situation would not arise.
  9280. %
  9281. As usual, \key{cmpq} may have at most one memory reference.
  9282. %
  9283. The second argument of the \key{movzbq} must be a register.
  9284. \begin{exercise}\normalfont\normalsize
  9285. %
  9286. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9287. %
  9288. {\if\edition\racketEd
  9289. Add the following entry to the list of \code{passes} in
  9290. \code{run-tests.rkt}, and then run this script to test your compiler.
  9291. \begin{lstlisting}
  9292. (list "patch_instructions" patch_instructions interp-x86-1)
  9293. \end{lstlisting}
  9294. \fi}
  9295. \end{exercise}
  9296. {\if\edition\pythonEd\pythonColor
  9297. \section{Generate Prelude and Conclusion}
  9298. \label{sec:prelude-conclusion-cond}
  9299. The generation of the \code{main} function with its prelude and
  9300. conclusion must change to accommodate how the program now consists of
  9301. one or more basic blocks. After the prelude in \code{main}, jump to
  9302. the \code{start} block. Place the conclusion in a basic block labeled
  9303. with \code{conclusion}.
  9304. \fi}
  9305. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9306. \LangIf{} translated to x86, showing the results of
  9307. \code{explicate\_control}, \code{select\_instructions}, and the final
  9308. x86 assembly.
  9309. \begin{figure}[tbp]
  9310. \begin{tcolorbox}[colback=white]
  9311. {\if\edition\racketEd
  9312. \begin{tabular}{lll}
  9313. \begin{minipage}{0.4\textwidth}
  9314. % cond_test_20.rkt, eq_input.py
  9315. \begin{lstlisting}
  9316. (if (eq? (read) 1) 42 0)
  9317. \end{lstlisting}
  9318. $\Downarrow$
  9319. \begin{lstlisting}
  9320. start:
  9321. tmp7951 = (read);
  9322. if (eq? tmp7951 1)
  9323. goto block7952;
  9324. else
  9325. goto block7953;
  9326. block7952:
  9327. return 42;
  9328. block7953:
  9329. return 0;
  9330. \end{lstlisting}
  9331. $\Downarrow$
  9332. \begin{lstlisting}
  9333. start:
  9334. callq read_int
  9335. movq %rax, tmp7951
  9336. cmpq $1, tmp7951
  9337. je block7952
  9338. jmp block7953
  9339. block7953:
  9340. movq $0, %rax
  9341. jmp conclusion
  9342. block7952:
  9343. movq $42, %rax
  9344. jmp conclusion
  9345. \end{lstlisting}
  9346. \end{minipage}
  9347. &
  9348. $\Rightarrow\qquad$
  9349. \begin{minipage}{0.4\textwidth}
  9350. \begin{lstlisting}
  9351. start:
  9352. callq read_int
  9353. movq %rax, %rcx
  9354. cmpq $1, %rcx
  9355. je block7952
  9356. jmp block7953
  9357. block7953:
  9358. movq $0, %rax
  9359. jmp conclusion
  9360. block7952:
  9361. movq $42, %rax
  9362. jmp conclusion
  9363. .globl main
  9364. main:
  9365. pushq %rbp
  9366. movq %rsp, %rbp
  9367. pushq %r13
  9368. pushq %r12
  9369. pushq %rbx
  9370. pushq %r14
  9371. subq $0, %rsp
  9372. jmp start
  9373. conclusion:
  9374. addq $0, %rsp
  9375. popq %r14
  9376. popq %rbx
  9377. popq %r12
  9378. popq %r13
  9379. popq %rbp
  9380. retq
  9381. \end{lstlisting}
  9382. \end{minipage}
  9383. \end{tabular}
  9384. \fi}
  9385. {\if\edition\pythonEd\pythonColor
  9386. \begin{tabular}{lll}
  9387. \begin{minipage}{0.4\textwidth}
  9388. % cond_test_20.rkt, eq_input.py
  9389. \begin{lstlisting}
  9390. print(42 if input_int() == 1 else 0)
  9391. \end{lstlisting}
  9392. $\Downarrow$
  9393. \begin{lstlisting}
  9394. start:
  9395. tmp_0 = input_int()
  9396. if tmp_0 == 1:
  9397. goto block_3
  9398. else:
  9399. goto block_4
  9400. block_3:
  9401. tmp_1 = 42
  9402. goto block_2
  9403. block_4:
  9404. tmp_1 = 0
  9405. goto block_2
  9406. block_2:
  9407. print(tmp_1)
  9408. return 0
  9409. \end{lstlisting}
  9410. $\Downarrow$
  9411. \begin{lstlisting}
  9412. start:
  9413. callq read_int
  9414. movq %rax, tmp_0
  9415. cmpq 1, tmp_0
  9416. je block_3
  9417. jmp block_4
  9418. block_3:
  9419. movq 42, tmp_1
  9420. jmp block_2
  9421. block_4:
  9422. movq 0, tmp_1
  9423. jmp block_2
  9424. block_2:
  9425. movq tmp_1, %rdi
  9426. callq print_int
  9427. movq 0, %rax
  9428. jmp conclusion
  9429. \end{lstlisting}
  9430. \end{minipage}
  9431. &
  9432. $\Rightarrow\qquad$
  9433. \begin{minipage}{0.4\textwidth}
  9434. \begin{lstlisting}
  9435. .globl main
  9436. main:
  9437. pushq %rbp
  9438. movq %rsp, %rbp
  9439. subq $0, %rsp
  9440. jmp start
  9441. start:
  9442. callq read_int
  9443. movq %rax, %rcx
  9444. cmpq $1, %rcx
  9445. je block_3
  9446. jmp block_4
  9447. block_3:
  9448. movq $42, %rcx
  9449. jmp block_2
  9450. block_4:
  9451. movq $0, %rcx
  9452. jmp block_2
  9453. block_2:
  9454. movq %rcx, %rdi
  9455. callq print_int
  9456. movq $0, %rax
  9457. jmp conclusion
  9458. conclusion:
  9459. addq $0, %rsp
  9460. popq %rbp
  9461. retq
  9462. \end{lstlisting}
  9463. \end{minipage}
  9464. \end{tabular}
  9465. \fi}
  9466. \end{tcolorbox}
  9467. \caption{Example compilation of an \key{if} expression to x86, showing
  9468. the results of \code{explicate\_control},
  9469. \code{select\_instructions}, and the final x86 assembly code. }
  9470. \label{fig:if-example-x86}
  9471. \end{figure}
  9472. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9473. compilation of \LangIf{}.
  9474. \begin{figure}[htbp]
  9475. \begin{tcolorbox}[colback=white]
  9476. {\if\edition\racketEd
  9477. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9478. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9479. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9480. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9481. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9482. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9483. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9484. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9485. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9486. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9487. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9488. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9489. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9490. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9491. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9492. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9493. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9494. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9495. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9496. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9497. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9498. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9499. \end{tikzpicture}
  9500. \fi}
  9501. {\if\edition\pythonEd\pythonColor
  9502. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9503. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9504. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9505. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9506. \node (C-1) at (0,0) {\large \LangCIf{}};
  9507. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9508. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9509. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9510. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9511. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9512. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9513. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9514. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9515. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9516. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9517. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9518. \end{tikzpicture}
  9519. \fi}
  9520. \end{tcolorbox}
  9521. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9522. \label{fig:Lif-passes}
  9523. \end{figure}
  9524. \section{Challenge: Optimize Blocks and Remove Jumps}
  9525. \label{sec:opt-jumps}
  9526. We discuss two challenges that involve optimizing the control-flow of
  9527. the program.
  9528. \subsection{Optimize Blocks}
  9529. The algorithm for \code{explicate\_control} that we discussed in
  9530. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9531. blocks. It creates a block whenever a continuation \emph{might} get
  9532. used more than once (for example, whenever the \code{cont} parameter
  9533. is passed into two or more recursive calls). However, some
  9534. continuation arguments may not be used at all. Consider the case for
  9535. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9536. the \code{els} continuation.
  9537. %
  9538. {\if\edition\racketEd
  9539. The following example program falls into this
  9540. case, and it creates two unused blocks.
  9541. \begin{center}
  9542. \begin{tabular}{lll}
  9543. \begin{minipage}{0.4\textwidth}
  9544. % cond_test_82.rkt
  9545. \begin{lstlisting}
  9546. (let ([y (if #t
  9547. (read)
  9548. (if (eq? (read) 0)
  9549. 777
  9550. (let ([x (read)])
  9551. (+ 1 x))))])
  9552. (+ y 2))
  9553. \end{lstlisting}
  9554. \end{minipage}
  9555. &
  9556. $\Rightarrow$
  9557. &
  9558. \begin{minipage}{0.4\textwidth}
  9559. \begin{lstlisting}
  9560. start:
  9561. y = (read);
  9562. goto block_5;
  9563. block_5:
  9564. return (+ y 2);
  9565. block_6:
  9566. y = 777;
  9567. goto block_5;
  9568. block_7:
  9569. x = (read);
  9570. y = (+ 1 x2);
  9571. goto block_5;
  9572. \end{lstlisting}
  9573. \end{minipage}
  9574. \end{tabular}
  9575. \end{center}
  9576. \fi}
  9577. {\if\edition\pythonEd
  9578. The following example program falls into this
  9579. case, and it creates the unused \code{block\_9}.
  9580. \begin{center}
  9581. \begin{minipage}{0.4\textwidth}
  9582. % if/if_true.py
  9583. \begin{lstlisting}
  9584. if True:
  9585. print(0)
  9586. else:
  9587. x = 1 if False else 2
  9588. print(x)
  9589. \end{lstlisting}
  9590. \end{minipage}
  9591. $\Rightarrow\qquad\qquad$
  9592. \begin{minipage}{0.4\textwidth}
  9593. \begin{lstlisting}
  9594. start:
  9595. print(0)
  9596. goto block_8
  9597. block_9:
  9598. print(x)
  9599. goto block_8
  9600. block_8:
  9601. return 0
  9602. \end{lstlisting}
  9603. \end{minipage}
  9604. \end{center}
  9605. \fi}
  9606. The question is, how can we decide whether to create a basic block?
  9607. \emph{Lazy evaluation}\index{subject}{lazy
  9608. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9609. delaying the creation of a basic block until the point in time at which
  9610. we know that it will be used.
  9611. %
  9612. {\if\edition\racketEd
  9613. %
  9614. Racket provides support for
  9615. lazy evaluation with the
  9616. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9617. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9618. \index{subject}{delay} creates a
  9619. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9620. expressions is postponed. When \key{(force}
  9621. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9622. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9623. result of $e_n$ is cached in the promise and returned. If \code{force}
  9624. is applied again to the same promise, then the cached result is
  9625. returned. If \code{force} is applied to an argument that is not a
  9626. promise, \code{force} simply returns the argument.
  9627. %
  9628. \fi}
  9629. %
  9630. {\if\edition\pythonEd\pythonColor
  9631. %
  9632. Although Python does not provide direct support for lazy evaluation,
  9633. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9634. by wrapping it inside a function with no parameters. We \emph{force}
  9635. its evaluation by calling the function. However, we might need to
  9636. force multiple times, so we store the result of calling the
  9637. function instead of recomputing it each time. The following
  9638. \code{Promise} class handles this memoization process.
  9639. \begin{minipage}{0.8\textwidth}
  9640. \begin{lstlisting}
  9641. @dataclass
  9642. class Promise:
  9643. fun : typing.Any
  9644. cache : list[stmt] = None
  9645. def force(self):
  9646. if self.cache is None:
  9647. self.cache = self.fun(); return self.cache
  9648. else:
  9649. return self.cache
  9650. \end{lstlisting}
  9651. \end{minipage}
  9652. \noindent However, in some cases of \code{explicate\_pred}, we return
  9653. a list of statements, and in other cases we return a function that
  9654. computes a list of statements. To uniformly deal with both regular
  9655. data and promises, we define the following \code{force} function that
  9656. checks whether its input is delayed (i.e., whether it is a
  9657. \code{Promise}) and then either (1) forces the promise or (2) returns
  9658. the input.
  9659. %
  9660. \begin{lstlisting}
  9661. def force(promise):
  9662. if isinstance(promise, Promise):
  9663. return promise.force()
  9664. else:
  9665. return promise
  9666. \end{lstlisting}
  9667. %
  9668. \fi}
  9669. We use promises for the input and output of the functions
  9670. \code{explicate\_pred}, \code{explicate\_assign},
  9671. %
  9672. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9673. %
  9674. So, instead of taking and returning \racket{$\Tail$
  9675. expressions}\python{lists of statements}, they take and return
  9676. promises. Furthermore, when we come to a situation in which a
  9677. continuation might be used more than once, as in the case for
  9678. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9679. that creates a basic block for each continuation (if there is not
  9680. already one) and then returns a \code{goto} statement to that basic
  9681. block. When we come to a situation in which we have a promise but need an
  9682. actual piece of code, for example, to create a larger piece of code with a
  9683. constructor such as \code{Seq}, then insert a call to \code{force}.
  9684. %
  9685. {\if\edition\racketEd
  9686. %
  9687. Also, we must modify the \code{create\_block} function to begin with
  9688. \code{delay} to create a promise. When forced, this promise forces the
  9689. original promise. If that returns a \code{Goto} (because the block was
  9690. already added to \code{basic-blocks}), then we return the
  9691. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9692. return a \code{Goto} to the new label.
  9693. \begin{center}
  9694. \begin{minipage}{\textwidth}
  9695. \begin{lstlisting}
  9696. (define (create_block tail)
  9697. (delay
  9698. (define t (force tail))
  9699. (match t
  9700. [(Goto label) (Goto label)]
  9701. [else
  9702. (let ([label (gensym 'block)])
  9703. (set! basic-blocks (cons (cons label t) basic-blocks))
  9704. (Goto label))])))
  9705. \end{lstlisting}
  9706. \end{minipage}
  9707. \end{center}
  9708. \fi}
  9709. {\if\edition\pythonEd\pythonColor
  9710. %
  9711. Here is the new version of the \code{create\_block} auxiliary function
  9712. that delays the creation of the new basic block.\\
  9713. \begin{minipage}{\textwidth}
  9714. \begin{lstlisting}
  9715. def create_block(promise, basic_blocks):
  9716. def delay():
  9717. stmts = force(promise)
  9718. match stmts:
  9719. case [Goto(l)]:
  9720. return [Goto(l)]
  9721. case _:
  9722. label = label_name(generate_name('block'))
  9723. basic_blocks[label] = stmts
  9724. return [Goto(label)]
  9725. return Promise(delay)
  9726. \end{lstlisting}
  9727. \end{minipage}
  9728. \fi}
  9729. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9730. improved \code{explicate\_control} on this example.
  9731. \racket{As you can see, the number of basic blocks has been reduced
  9732. from four blocks to two blocks.}%
  9733. \python{As you can see, the number of basic blocks has been reduced
  9734. from three blocks to two blocks.}
  9735. \begin{figure}[tbp]
  9736. \begin{tcolorbox}[colback=white]
  9737. {\if\edition\racketEd
  9738. \begin{tabular}{lll}
  9739. \begin{minipage}{0.45\textwidth}
  9740. % cond_test_82.rkt
  9741. \begin{lstlisting}
  9742. (let ([y (if #t
  9743. (read)
  9744. (if (eq? (read) 0)
  9745. 777
  9746. (let ([x (read)])
  9747. (+ 1 x))))])
  9748. (+ y 2))
  9749. \end{lstlisting}
  9750. \end{minipage}
  9751. &
  9752. $\quad\Rightarrow\quad$
  9753. &
  9754. \begin{minipage}{0.4\textwidth}
  9755. \begin{lstlisting}
  9756. start:
  9757. y = (read);
  9758. goto block_5;
  9759. block_5:
  9760. return (+ y 2);
  9761. \end{lstlisting}
  9762. \end{minipage}
  9763. \end{tabular}
  9764. \fi}
  9765. {\if\edition\pythonEd\pythonColor
  9766. \begin{tabular}{lll}
  9767. \begin{minipage}{0.4\textwidth}
  9768. % if/if_true.py
  9769. \begin{lstlisting}
  9770. if True:
  9771. print(0)
  9772. else:
  9773. x = 1 if False else 2
  9774. print(x)
  9775. \end{lstlisting}
  9776. \end{minipage}
  9777. &
  9778. $\Rightarrow$
  9779. &
  9780. \begin{minipage}{0.55\textwidth}
  9781. \begin{lstlisting}
  9782. start:
  9783. print(0)
  9784. goto block_4
  9785. block_4:
  9786. return 0
  9787. \end{lstlisting}
  9788. \end{minipage}
  9789. \end{tabular}
  9790. \fi}
  9791. \end{tcolorbox}
  9792. \caption{Translation from \LangIf{} to \LangCIf{}
  9793. via the improved \code{explicate\_control}.}
  9794. \label{fig:explicate-control-challenge}
  9795. \end{figure}
  9796. %% Recall that in the example output of \code{explicate\_control} in
  9797. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9798. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9799. %% block. The first goal of this challenge assignment is to remove those
  9800. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9801. %% \code{explicate\_control} on the left and shows the result of bypassing
  9802. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9803. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9804. %% \code{block55}. The optimized code on the right of
  9805. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9806. %% \code{then} branch jumping directly to \code{block55}. The story is
  9807. %% similar for the \code{else} branch, as well as for the two branches in
  9808. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9809. %% have been optimized in this way, there are no longer any jumps to
  9810. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9811. %% \begin{figure}[tbp]
  9812. %% \begin{tabular}{lll}
  9813. %% \begin{minipage}{0.4\textwidth}
  9814. %% \begin{lstlisting}
  9815. %% block62:
  9816. %% tmp54 = (read);
  9817. %% if (eq? tmp54 2) then
  9818. %% goto block59;
  9819. %% else
  9820. %% goto block60;
  9821. %% block61:
  9822. %% tmp53 = (read);
  9823. %% if (eq? tmp53 0) then
  9824. %% goto block57;
  9825. %% else
  9826. %% goto block58;
  9827. %% block60:
  9828. %% goto block56;
  9829. %% block59:
  9830. %% goto block55;
  9831. %% block58:
  9832. %% goto block56;
  9833. %% block57:
  9834. %% goto block55;
  9835. %% block56:
  9836. %% return (+ 700 77);
  9837. %% block55:
  9838. %% return (+ 10 32);
  9839. %% start:
  9840. %% tmp52 = (read);
  9841. %% if (eq? tmp52 1) then
  9842. %% goto block61;
  9843. %% else
  9844. %% goto block62;
  9845. %% \end{lstlisting}
  9846. %% \end{minipage}
  9847. %% &
  9848. %% $\Rightarrow$
  9849. %% &
  9850. %% \begin{minipage}{0.55\textwidth}
  9851. %% \begin{lstlisting}
  9852. %% block62:
  9853. %% tmp54 = (read);
  9854. %% if (eq? tmp54 2) then
  9855. %% goto block55;
  9856. %% else
  9857. %% goto block56;
  9858. %% block61:
  9859. %% tmp53 = (read);
  9860. %% if (eq? tmp53 0) then
  9861. %% goto block55;
  9862. %% else
  9863. %% goto block56;
  9864. %% block56:
  9865. %% return (+ 700 77);
  9866. %% block55:
  9867. %% return (+ 10 32);
  9868. %% start:
  9869. %% tmp52 = (read);
  9870. %% if (eq? tmp52 1) then
  9871. %% goto block61;
  9872. %% else
  9873. %% goto block62;
  9874. %% \end{lstlisting}
  9875. %% \end{minipage}
  9876. %% \end{tabular}
  9877. %% \caption{Optimize jumps by removing trivial blocks.}
  9878. %% \label{fig:optimize-jumps}
  9879. %% \end{figure}
  9880. %% The name of this pass is \code{optimize-jumps}. We recommend
  9881. %% implementing this pass in two phases. The first phrase builds a hash
  9882. %% table that maps labels to possibly improved labels. The second phase
  9883. %% changes the target of each \code{goto} to use the improved label. If
  9884. %% the label is for a trivial block, then the hash table should map the
  9885. %% label to the first non-trivial block that can be reached from this
  9886. %% label by jumping through trivial blocks. If the label is for a
  9887. %% non-trivial block, then the hash table should map the label to itself;
  9888. %% we do not want to change jumps to non-trivial blocks.
  9889. %% The first phase can be accomplished by constructing an empty hash
  9890. %% table, call it \code{short-cut}, and then iterating over the control
  9891. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9892. %% then update the hash table, mapping the block's source to the target
  9893. %% of the \code{goto}. Also, the hash table may already have mapped some
  9894. %% labels to the block's source, to you must iterate through the hash
  9895. %% table and update all of those so that they instead map to the target
  9896. %% of the \code{goto}.
  9897. %% For the second phase, we recommend iterating through the $\Tail$ of
  9898. %% each block in the program, updating the target of every \code{goto}
  9899. %% according to the mapping in \code{short-cut}.
  9900. \begin{exercise}\normalfont\normalsize
  9901. Implement the improvements to the \code{explicate\_control} pass.
  9902. Check that it removes trivial blocks in a few example programs. Then
  9903. check that your compiler still passes all your tests.
  9904. \end{exercise}
  9905. \subsection{Remove Jumps}
  9906. There is an opportunity for removing jumps that is apparent in the
  9907. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9908. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9909. and there are no other jumps to
  9910. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9911. In this situation we can avoid the runtime overhead of this jump by merging
  9912. \racket{\code{block\_5}}\python{\code{block\_4}}
  9913. into the preceding block, which in this case is the \code{start} block.
  9914. Figure~\ref{fig:remove-jumps} shows the output of
  9915. \code{allocate\_registers} on the left and the result of this
  9916. optimization on the right.
  9917. \begin{figure}[tbp]
  9918. \begin{tcolorbox}[colback=white]
  9919. {\if\edition\racketEd
  9920. \begin{tabular}{lll}
  9921. \begin{minipage}{0.5\textwidth}
  9922. % cond_test_82.rkt
  9923. \begin{lstlisting}
  9924. start:
  9925. callq read_int
  9926. movq %rax, %rcx
  9927. jmp block_5
  9928. block_5:
  9929. movq %rcx, %rax
  9930. addq $2, %rax
  9931. jmp conclusion
  9932. \end{lstlisting}
  9933. \end{minipage}
  9934. &
  9935. $\Rightarrow\qquad$
  9936. \begin{minipage}{0.4\textwidth}
  9937. \begin{lstlisting}
  9938. start:
  9939. callq read_int
  9940. movq %rax, %rcx
  9941. movq %rcx, %rax
  9942. addq $2, %rax
  9943. jmp conclusion
  9944. \end{lstlisting}
  9945. \end{minipage}
  9946. \end{tabular}
  9947. \fi}
  9948. {\if\edition\pythonEd\pythonColor
  9949. \begin{tabular}{lll}
  9950. \begin{minipage}{0.5\textwidth}
  9951. % cond_test_20.rkt
  9952. \begin{lstlisting}
  9953. start:
  9954. callq read_int
  9955. movq %rax, tmp_0
  9956. cmpq 1, tmp_0
  9957. je block_3
  9958. jmp block_4
  9959. block_3:
  9960. movq 42, tmp_1
  9961. jmp block_2
  9962. block_4:
  9963. movq 0, tmp_1
  9964. jmp block_2
  9965. block_2:
  9966. movq tmp_1, %rdi
  9967. callq print_int
  9968. movq 0, %rax
  9969. jmp conclusion
  9970. \end{lstlisting}
  9971. \end{minipage}
  9972. &
  9973. $\Rightarrow\qquad$
  9974. \begin{minipage}{0.4\textwidth}
  9975. \begin{lstlisting}
  9976. start:
  9977. callq read_int
  9978. movq %rax, tmp_0
  9979. cmpq 1, tmp_0
  9980. je block_3
  9981. movq 0, tmp_1
  9982. jmp block_2
  9983. block_3:
  9984. movq 42, tmp_1
  9985. jmp block_2
  9986. block_2:
  9987. movq tmp_1, %rdi
  9988. callq print_int
  9989. movq 0, %rax
  9990. jmp conclusion
  9991. \end{lstlisting}
  9992. \end{minipage}
  9993. \end{tabular}
  9994. \fi}
  9995. \end{tcolorbox}
  9996. \caption{Merging basic blocks by removing unnecessary jumps.}
  9997. \label{fig:remove-jumps}
  9998. \end{figure}
  9999. \begin{exercise}\normalfont\normalsize
  10000. %
  10001. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10002. into their preceding basic block, when there is only one preceding
  10003. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10004. %
  10005. {\if\edition\racketEd
  10006. In the \code{run-tests.rkt} script, add the following entry to the
  10007. list of \code{passes} between \code{allocate\_registers}
  10008. and \code{patch\_instructions}:
  10009. \begin{lstlisting}
  10010. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10011. \end{lstlisting}
  10012. \fi}
  10013. %
  10014. Run the script to test your compiler.
  10015. %
  10016. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10017. blocks on several test programs.
  10018. \end{exercise}
  10019. \section{Further Reading}
  10020. \label{sec:cond-further-reading}
  10021. The algorithm for the \code{explicate\_control} pass is based on the
  10022. \code{expose-basic-blocks} pass in the course notes of
  10023. \citet{Dybvig:2010aa}.
  10024. %
  10025. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10026. \citet{Appel:2003fk}, and is related to translations into continuation
  10027. passing
  10028. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10029. %
  10030. The treatment of conditionals in the \code{explicate\_control} pass is
  10031. similar to short-cut Boolean
  10032. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10033. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10034. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10035. \chapter{Loops and Dataflow Analysis}
  10036. \label{ch:Lwhile}
  10037. \setcounter{footnote}{0}
  10038. % TODO: define R'_8
  10039. % TODO: multi-graph
  10040. {\if\edition\racketEd
  10041. %
  10042. In this chapter we study two features that are the hallmarks of
  10043. imperative programming languages: loops and assignments to local
  10044. variables. The following example demonstrates these new features by
  10045. computing the sum of the first five positive integers:
  10046. % similar to loop_test_1.rkt
  10047. \begin{lstlisting}
  10048. (let ([sum 0])
  10049. (let ([i 5])
  10050. (begin
  10051. (while (> i 0)
  10052. (begin
  10053. (set! sum (+ sum i))
  10054. (set! i (- i 1))))
  10055. sum)))
  10056. \end{lstlisting}
  10057. The \code{while} loop consists of a condition and a
  10058. body.\footnote{The \code{while} loop is not a built-in
  10059. feature of the Racket language, but Racket includes many looping
  10060. constructs and it is straightforward to define \code{while} as a
  10061. macro.} The body is evaluated repeatedly so long as the condition
  10062. remains true.
  10063. %
  10064. The \code{set!} consists of a variable and a right-hand side
  10065. expression. The \code{set!} updates value of the variable to the
  10066. value of the right-hand side.
  10067. %
  10068. The primary purpose of both the \code{while} loop and \code{set!} is
  10069. to cause side effects, so they do not give a meaningful result
  10070. value. Instead, their result is the \code{\#<void>} value. The
  10071. expression \code{(void)} is an explicit way to create the
  10072. \code{\#<void>} value, and it has type \code{Void}. The
  10073. \code{\#<void>} value can be passed around just like other values
  10074. inside an \LangLoop{} program, and it can be compared for equality with
  10075. another \code{\#<void>} value. However, there are no other operations
  10076. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10077. Racket defines the \code{void?} predicate that returns \code{\#t}
  10078. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10079. %
  10080. \footnote{Racket's \code{Void} type corresponds to what is often
  10081. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10082. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10083. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10084. %
  10085. With the addition of side effect-producing features such as
  10086. \code{while} loop and \code{set!}, it is helpful to include a language
  10087. feature for sequencing side effects: the \code{begin} expression. It
  10088. consists of one or more subexpressions that are evaluated
  10089. left to right.
  10090. %
  10091. \fi}
  10092. {\if\edition\pythonEd\pythonColor
  10093. %
  10094. In this chapter we study loops, one of the hallmarks of imperative
  10095. programming languages. The following example demonstrates the
  10096. \code{while} loop by computing the sum of the first five positive
  10097. integers.
  10098. \begin{lstlisting}
  10099. sum = 0
  10100. i = 5
  10101. while i > 0:
  10102. sum = sum + i
  10103. i = i - 1
  10104. print(sum)
  10105. \end{lstlisting}
  10106. The \code{while} loop consists of a condition and a body (a sequence
  10107. of statements). The body is evaluated repeatedly so long as the
  10108. condition remains true.
  10109. %
  10110. \fi}
  10111. \section{The \LangLoop{} Language}
  10112. \newcommand{\LwhileGrammarRacket}{
  10113. \begin{array}{lcl}
  10114. \Type &::=& \key{Void}\\
  10115. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10116. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10117. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10118. \end{array}
  10119. }
  10120. \newcommand{\LwhileASTRacket}{
  10121. \begin{array}{lcl}
  10122. \Type &::=& \key{Void}\\
  10123. \Exp &::=& \SETBANG{\Var}{\Exp}
  10124. \MID \BEGIN{\Exp^{*}}{\Exp}
  10125. \MID \WHILE{\Exp}{\Exp}
  10126. \MID \VOID{}
  10127. \end{array}
  10128. }
  10129. \newcommand{\LwhileGrammarPython}{
  10130. \begin{array}{rcl}
  10131. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10132. \end{array}
  10133. }
  10134. \newcommand{\LwhileASTPython}{
  10135. \begin{array}{lcl}
  10136. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10137. \end{array}
  10138. }
  10139. \begin{figure}[tp]
  10140. \centering
  10141. \begin{tcolorbox}[colback=white]
  10142. \small
  10143. {\if\edition\racketEd
  10144. \[
  10145. \begin{array}{l}
  10146. \gray{\LintGrammarRacket{}} \\ \hline
  10147. \gray{\LvarGrammarRacket{}} \\ \hline
  10148. \gray{\LifGrammarRacket{}} \\ \hline
  10149. \LwhileGrammarRacket \\
  10150. \begin{array}{lcl}
  10151. \LangLoopM{} &::=& \Exp
  10152. \end{array}
  10153. \end{array}
  10154. \]
  10155. \fi}
  10156. {\if\edition\pythonEd\pythonColor
  10157. \[
  10158. \begin{array}{l}
  10159. \gray{\LintGrammarPython} \\ \hline
  10160. \gray{\LvarGrammarPython} \\ \hline
  10161. \gray{\LifGrammarPython} \\ \hline
  10162. \LwhileGrammarPython \\
  10163. \begin{array}{rcl}
  10164. \LangLoopM{} &::=& \Stmt^{*}
  10165. \end{array}
  10166. \end{array}
  10167. \]
  10168. \fi}
  10169. \end{tcolorbox}
  10170. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10171. \label{fig:Lwhile-concrete-syntax}
  10172. \end{figure}
  10173. \begin{figure}[tp]
  10174. \centering
  10175. \begin{tcolorbox}[colback=white]
  10176. \small
  10177. {\if\edition\racketEd
  10178. \[
  10179. \begin{array}{l}
  10180. \gray{\LintOpAST} \\ \hline
  10181. \gray{\LvarASTRacket{}} \\ \hline
  10182. \gray{\LifASTRacket{}} \\ \hline
  10183. \LwhileASTRacket{} \\
  10184. \begin{array}{lcl}
  10185. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10186. \end{array}
  10187. \end{array}
  10188. \]
  10189. \fi}
  10190. {\if\edition\pythonEd\pythonColor
  10191. \[
  10192. \begin{array}{l}
  10193. \gray{\LintASTPython} \\ \hline
  10194. \gray{\LvarASTPython} \\ \hline
  10195. \gray{\LifASTPython} \\ \hline
  10196. \LwhileASTPython \\
  10197. \begin{array}{lcl}
  10198. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10199. \end{array}
  10200. \end{array}
  10201. \]
  10202. \fi}
  10203. \end{tcolorbox}
  10204. \python{
  10205. \index{subject}{While@\texttt{While}}
  10206. }
  10207. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10208. \label{fig:Lwhile-syntax}
  10209. \end{figure}
  10210. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10211. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10212. shows the definition of its abstract syntax.
  10213. %
  10214. The definitional interpreter for \LangLoop{} is shown in
  10215. figure~\ref{fig:interp-Lwhile}.
  10216. %
  10217. {\if\edition\racketEd
  10218. %
  10219. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10220. and \code{Void}, and we make changes to the cases for \code{Var} and
  10221. \code{Let} regarding variables. To support assignment to variables and
  10222. to make their lifetimes indefinite (see the second example in
  10223. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10224. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10225. value.
  10226. %
  10227. Now we discuss the new cases. For \code{SetBang}, we find the
  10228. variable in the environment to obtain a boxed value, and then we change
  10229. it using \code{set-box!} to the result of evaluating the right-hand
  10230. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10231. %
  10232. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10233. if the result is true, (2) evaluate the body.
  10234. The result value of a \code{while} loop is also \code{\#<void>}.
  10235. %
  10236. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10237. subexpressions \itm{es} for their effects and then evaluates
  10238. and returns the result from \itm{body}.
  10239. %
  10240. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10241. %
  10242. \fi}
  10243. {\if\edition\pythonEd\pythonColor
  10244. %
  10245. We add a new case for \code{While} in the \code{interp\_stmts}
  10246. function, in which we repeatedly interpret the \code{body} so long as the
  10247. \code{test} expression remains true.
  10248. %
  10249. \fi}
  10250. \begin{figure}[tbp]
  10251. \begin{tcolorbox}[colback=white]
  10252. {\if\edition\racketEd
  10253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10254. (define interp-Lwhile-class
  10255. (class interp-Lif-class
  10256. (super-new)
  10257. (define/override ((interp-exp env) e)
  10258. (define recur (interp-exp env))
  10259. (match e
  10260. [(Let x e body)
  10261. (define new-env (dict-set env x (box (recur e))))
  10262. ((interp-exp new-env) body)]
  10263. [(Var x) (unbox (dict-ref env x))]
  10264. [(SetBang x rhs)
  10265. (set-box! (dict-ref env x) (recur rhs))]
  10266. [(WhileLoop cnd body)
  10267. (define (loop)
  10268. (cond [(recur cnd) (recur body) (loop)]
  10269. [else (void)]))
  10270. (loop)]
  10271. [(Begin es body)
  10272. (for ([e es]) (recur e))
  10273. (recur body)]
  10274. [(Void) (void)]
  10275. [else ((super interp-exp env) e)]))
  10276. ))
  10277. (define (interp-Lwhile p)
  10278. (send (new interp-Lwhile-class) interp-program p))
  10279. \end{lstlisting}
  10280. \fi}
  10281. {\if\edition\pythonEd\pythonColor
  10282. \begin{lstlisting}
  10283. class InterpLwhile(InterpLif):
  10284. def interp_stmt(self, s, env, cont):
  10285. match s:
  10286. case While(test, body, []):
  10287. if self.interp_exp(test, env):
  10288. self.interp_stmts(body + [s] + cont, env)
  10289. else:
  10290. return self.interp_stmts(cont, env)
  10291. case _:
  10292. return super().interp_stmt(s, env, cont)
  10293. \end{lstlisting}
  10294. \fi}
  10295. \end{tcolorbox}
  10296. \caption{Interpreter for \LangLoop{}.}
  10297. \label{fig:interp-Lwhile}
  10298. \end{figure}
  10299. The definition of the type checker for \LangLoop{} is shown in
  10300. figure~\ref{fig:type-check-Lwhile}.
  10301. %
  10302. {\if\edition\racketEd
  10303. %
  10304. The type checking of the \code{SetBang} expression requires the type
  10305. of the variable and the right-hand side to agree. The result type is
  10306. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10307. and the result type is \code{Void}. For \code{Begin}, the result type
  10308. is the type of its last subexpression.
  10309. %
  10310. \fi}
  10311. %
  10312. {\if\edition\pythonEd\pythonColor
  10313. %
  10314. A \code{while} loop is well typed if the type of the \code{test}
  10315. expression is \code{bool} and the statements in the \code{body} are
  10316. well typed.
  10317. %
  10318. \fi}
  10319. \begin{figure}[tbp]
  10320. \begin{tcolorbox}[colback=white]
  10321. {\if\edition\racketEd
  10322. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10323. (define type-check-Lwhile-class
  10324. (class type-check-Lif-class
  10325. (super-new)
  10326. (inherit check-type-equal?)
  10327. (define/override (type-check-exp env)
  10328. (lambda (e)
  10329. (define recur (type-check-exp env))
  10330. (match e
  10331. [(SetBang x rhs)
  10332. (define-values (rhs^ rhsT) (recur rhs))
  10333. (define varT (dict-ref env x))
  10334. (check-type-equal? rhsT varT e)
  10335. (values (SetBang x rhs^) 'Void)]
  10336. [(WhileLoop cnd body)
  10337. (define-values (cnd^ Tc) (recur cnd))
  10338. (check-type-equal? Tc 'Boolean e)
  10339. (define-values (body^ Tbody) ((type-check-exp env) body))
  10340. (values (WhileLoop cnd^ body^) 'Void)]
  10341. [(Begin es body)
  10342. (define-values (es^ ts)
  10343. (for/lists (l1 l2) ([e es]) (recur e)))
  10344. (define-values (body^ Tbody) (recur body))
  10345. (values (Begin es^ body^) Tbody)]
  10346. [else ((super type-check-exp env) e)])))
  10347. ))
  10348. (define (type-check-Lwhile p)
  10349. (send (new type-check-Lwhile-class) type-check-program p))
  10350. \end{lstlisting}
  10351. \fi}
  10352. {\if\edition\pythonEd\pythonColor
  10353. \begin{lstlisting}
  10354. class TypeCheckLwhile(TypeCheckLif):
  10355. def type_check_stmts(self, ss, env):
  10356. if len(ss) == 0:
  10357. return
  10358. match ss[0]:
  10359. case While(test, body, []):
  10360. test_t = self.type_check_exp(test, env)
  10361. check_type_equal(bool, test_t, test)
  10362. body_t = self.type_check_stmts(body, env)
  10363. return self.type_check_stmts(ss[1:], env)
  10364. case _:
  10365. return super().type_check_stmts(ss, env)
  10366. \end{lstlisting}
  10367. \fi}
  10368. \end{tcolorbox}
  10369. \caption{Type checker for the \LangLoop{} language.}
  10370. \label{fig:type-check-Lwhile}
  10371. \end{figure}
  10372. {\if\edition\racketEd
  10373. %
  10374. At first glance, the translation of these language features to x86
  10375. seems straightforward because the \LangCIf{} intermediate language
  10376. already supports all the ingredients that we need: assignment,
  10377. \code{goto}, conditional branching, and sequencing. However,
  10378. complications arise, which we discuss in the next section. After
  10379. that we introduce the changes necessary to the existing passes.
  10380. %
  10381. \fi}
  10382. {\if\edition\pythonEd\pythonColor
  10383. %
  10384. At first glance, the translation of \code{while} loops to x86 seems
  10385. straightforward because the \LangCIf{} intermediate language already
  10386. supports \code{goto} and conditional branching. However, there are
  10387. complications that arise, which we discuss in the next section. After
  10388. that we introduce the changes necessary to the existing passes.
  10389. %
  10390. \fi}
  10391. \section{Cyclic Control Flow and Dataflow Analysis}
  10392. \label{sec:dataflow-analysis}
  10393. Up until this point, the programs generated in
  10394. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10395. \code{while} loop introduces a cycle. Does that matter?
  10396. %
  10397. Indeed, it does. Recall that for register allocation, the compiler
  10398. performs liveness analysis to determine which variables can share the
  10399. same register. To accomplish this, we analyzed the control-flow graph
  10400. in reverse topological order
  10401. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10402. well defined only for acyclic graphs.
  10403. Let us return to the example of computing the sum of the first five
  10404. positive integers. Here is the program after instruction
  10405. selection\index{subject}{instruction selection} but before register
  10406. allocation.
  10407. \begin{center}
  10408. {\if\edition\racketEd
  10409. \begin{minipage}{0.45\textwidth}
  10410. \begin{lstlisting}
  10411. (define (main) : Integer
  10412. mainstart:
  10413. movq $0, sum
  10414. movq $5, i
  10415. jmp block5
  10416. block5:
  10417. movq i, tmp3
  10418. cmpq tmp3, $0
  10419. jl block7
  10420. jmp block8
  10421. \end{lstlisting}
  10422. \end{minipage}
  10423. \begin{minipage}{0.45\textwidth}
  10424. \begin{lstlisting}
  10425. block7:
  10426. addq i, sum
  10427. movq $1, tmp4
  10428. negq tmp4
  10429. addq tmp4, i
  10430. jmp block5
  10431. block8:
  10432. movq $27, %rax
  10433. addq sum, %rax
  10434. jmp mainconclusion)
  10435. \end{lstlisting}
  10436. \end{minipage}
  10437. \fi}
  10438. {\if\edition\pythonEd\pythonColor
  10439. \begin{minipage}{0.45\textwidth}
  10440. \begin{lstlisting}
  10441. mainstart:
  10442. movq $0, sum
  10443. movq $5, i
  10444. jmp block5
  10445. block5:
  10446. cmpq $0, i
  10447. jg block7
  10448. jmp block8
  10449. \end{lstlisting}
  10450. \end{minipage}
  10451. \begin{minipage}{0.45\textwidth}
  10452. \begin{lstlisting}
  10453. block7:
  10454. addq i, sum
  10455. subq $1, i
  10456. jmp block5
  10457. block8:
  10458. movq sum, %rdi
  10459. callq print_int
  10460. movq $0, %rax
  10461. jmp mainconclusion
  10462. \end{lstlisting}
  10463. \end{minipage}
  10464. \fi}
  10465. \end{center}
  10466. Recall that liveness analysis works backward, starting at the end
  10467. of each function. For this example we could start with \code{block8}
  10468. because we know what is live at the beginning of the conclusion:
  10469. only \code{rax} and \code{rsp}. So the live-before set
  10470. for \code{block8} is \code{\{rsp,sum\}}.
  10471. %
  10472. Next we might try to analyze \code{block5} or \code{block7}, but
  10473. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10474. we are stuck.
  10475. The way out of this impasse is to realize that we can compute an
  10476. underapproximation of each live-before set by starting with empty
  10477. live-after sets. By \emph{underapproximation}, we mean that the set
  10478. contains only variables that are live for some execution of the
  10479. program, but the set may be missing some variables that are live.
  10480. Next, the underapproximations for each block can be improved by (1)
  10481. updating the live-after set for each block using the approximate
  10482. live-before sets from the other blocks, and (2) performing liveness
  10483. analysis again on each block. In fact, by iterating this process, the
  10484. underapproximations eventually become the correct solutions!
  10485. %
  10486. This approach of iteratively analyzing a control-flow graph is
  10487. applicable to many static analysis problems and goes by the name
  10488. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10489. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10490. Washington.
  10491. Let us apply this approach to the previously presented example. We use
  10492. the empty set for the initial live-before set for each block. Let
  10493. $m_0$ be the following mapping from label names to sets of locations
  10494. (variables and registers):
  10495. \begin{center}
  10496. \begin{lstlisting}
  10497. mainstart: {}, block5: {}, block7: {}, block8: {}
  10498. \end{lstlisting}
  10499. \end{center}
  10500. Using the above live-before approximations, we determine the
  10501. live-after for each block and then apply liveness analysis to each
  10502. block. This produces our next approximation $m_1$ of the live-before
  10503. sets.
  10504. \begin{center}
  10505. \begin{lstlisting}
  10506. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10507. \end{lstlisting}
  10508. \end{center}
  10509. For the second round, the live-after for \code{mainstart} is the
  10510. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10511. the liveness analysis for \code{mainstart} computes the empty set. The
  10512. live-after for \code{block5} is the union of the live-before sets for
  10513. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10514. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10515. sum\}}. The live-after for \code{block7} is the live-before for
  10516. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10517. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10518. Together these yield the following approximation $m_2$ of
  10519. the live-before sets:
  10520. \begin{center}
  10521. \begin{lstlisting}
  10522. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10523. \end{lstlisting}
  10524. \end{center}
  10525. In the preceding iteration, only \code{block5} changed, so we can
  10526. limit our attention to \code{mainstart} and \code{block7}, the two
  10527. blocks that jump to \code{block5}. As a result, the live-before sets
  10528. for \code{mainstart} and \code{block7} are updated to include
  10529. \code{rsp}, yielding the following approximation $m_3$:
  10530. \begin{center}
  10531. \begin{lstlisting}
  10532. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10533. \end{lstlisting}
  10534. \end{center}
  10535. Because \code{block7} changed, we analyze \code{block5} once more, but
  10536. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10537. our approximations have converged, so $m_3$ is the solution.
  10538. This iteration process is guaranteed to converge to a solution by the
  10539. Kleene fixed-point theorem, a general theorem about functions on
  10540. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10541. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10542. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10543. join operator
  10544. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10545. will be working with join semilattices.} When two elements are
  10546. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10547. as much information as $m_i$, so we can think of $m_j$ as a
  10548. better-than-or-equal-to approximation in relation to $m_i$. The
  10549. bottom element $\bot$ represents the complete lack of information,
  10550. that is, the worst approximation. The join operator takes two lattice
  10551. elements and combines their information; that is, it produces the
  10552. least upper bound of the two.\index{subject}{least upper bound}
  10553. A dataflow analysis typically involves two lattices: one lattice to
  10554. represent abstract states and another lattice that aggregates the
  10555. abstract states of all the blocks in the control-flow graph. For
  10556. liveness analysis, an abstract state is a set of locations. We form
  10557. the lattice $L$ by taking its elements to be sets of locations, the
  10558. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10559. set, and the join operator to be set union.
  10560. %
  10561. We form a second lattice $M$ by taking its elements to be mappings
  10562. from the block labels to sets of locations (elements of $L$). We
  10563. order the mappings point-wise, using the ordering of $L$. So, given any
  10564. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10565. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10566. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10567. to the empty set, $\bot_M(\ell) = \emptyset$.
  10568. We can think of one iteration of liveness analysis applied to the
  10569. whole program as being a function $f$ on the lattice $M$. It takes a
  10570. mapping as input and computes a new mapping.
  10571. \[
  10572. f(m_i) = m_{i+1}
  10573. \]
  10574. Next let us think for a moment about what a final solution $m_s$
  10575. should look like. If we perform liveness analysis using the solution
  10576. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10577. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10578. \[
  10579. f(m_s) = m_s
  10580. \]
  10581. Furthermore, the solution should include only locations that are
  10582. forced to be there by performing liveness analysis on the program, so
  10583. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10584. The Kleene fixed-point theorem states that if a function $f$ is
  10585. monotone (better inputs produce better outputs), then the least fixed
  10586. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10587. chain} that starts at $\bot$ and iterates $f$ as
  10588. follows:\index{subject}{Kleene fixed-point theorem}
  10589. \[
  10590. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10591. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10592. \]
  10593. When a lattice contains only finitely long ascending chains, then
  10594. every Kleene chain tops out at some fixed point after some number of
  10595. iterations of $f$.
  10596. \[
  10597. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10598. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10599. \]
  10600. The liveness analysis is indeed a monotone function and the lattice
  10601. $M$ has finitely long ascending chains because there are only a
  10602. finite number of variables and blocks in the program. Thus we are
  10603. guaranteed that iteratively applying liveness analysis to all blocks
  10604. in the program will eventually produce the least fixed point solution.
  10605. Next let us consider dataflow analysis in general and discuss the
  10606. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10607. %
  10608. The algorithm has four parameters: the control-flow graph \code{G}, a
  10609. function \code{transfer} that applies the analysis to one block, and the
  10610. \code{bottom} and \code{join} operators for the lattice of abstract
  10611. states. The \code{analyze\_dataflow} function is formulated as a
  10612. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10613. function come from the predecessor nodes in the control-flow
  10614. graph. However, liveness analysis is a \emph{backward} dataflow
  10615. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10616. function with the transpose of the control-flow graph.
  10617. The algorithm begins by creating the bottom mapping, represented by a
  10618. hash table. It then pushes all the nodes in the control-flow graph
  10619. onto the work list (a queue). The algorithm repeats the \code{while}
  10620. loop as long as there are items in the work list. In each iteration, a
  10621. node is popped from the work list and processed. The \code{input} for
  10622. the node is computed by taking the join of the abstract states of all
  10623. the predecessor nodes. The \code{transfer} function is then applied to
  10624. obtain the \code{output} abstract state. If the output differs from
  10625. the previous state for this block, the mapping for this block is
  10626. updated and its successor nodes are pushed onto the work list.
  10627. \begin{figure}[tb]
  10628. \begin{tcolorbox}[colback=white]
  10629. {\if\edition\racketEd
  10630. \begin{lstlisting}
  10631. (define (analyze_dataflow G transfer bottom join)
  10632. (define mapping (make-hash))
  10633. (for ([v (in-vertices G)])
  10634. (dict-set! mapping v bottom))
  10635. (define worklist (make-queue))
  10636. (for ([v (in-vertices G)])
  10637. (enqueue! worklist v))
  10638. (define trans-G (transpose G))
  10639. (while (not (queue-empty? worklist))
  10640. (define node (dequeue! worklist))
  10641. (define input (for/fold ([state bottom])
  10642. ([pred (in-neighbors trans-G node)])
  10643. (join state (dict-ref mapping pred))))
  10644. (define output (transfer node input))
  10645. (cond [(not (equal? output (dict-ref mapping node)))
  10646. (dict-set! mapping node output)
  10647. (for ([v (in-neighbors G node)])
  10648. (enqueue! worklist v))]))
  10649. mapping)
  10650. \end{lstlisting}
  10651. \fi}
  10652. {\if\edition\pythonEd\pythonColor
  10653. \begin{lstlisting}
  10654. def analyze_dataflow(G, transfer, bottom, join):
  10655. trans_G = transpose(G)
  10656. mapping = dict((v, bottom) for v in G.vertices())
  10657. worklist = deque(G.vertices)
  10658. while worklist:
  10659. node = worklist.pop()
  10660. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10661. input = reduce(join, inputs, bottom)
  10662. output = transfer(node, input)
  10663. if output != mapping[node]:
  10664. mapping[node] = output
  10665. worklist.extend(G.adjacent(node))
  10666. \end{lstlisting}
  10667. \fi}
  10668. \end{tcolorbox}
  10669. \caption{Generic work list algorithm for dataflow analysis.}
  10670. \label{fig:generic-dataflow}
  10671. \end{figure}
  10672. {\if\edition\racketEd
  10673. \section{Mutable Variables and Remove Complex Operands}
  10674. There is a subtle interaction between the
  10675. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10676. and the left-to-right order of evaluation of Racket. Consider the
  10677. following example:
  10678. \begin{lstlisting}
  10679. (let ([x 2])
  10680. (+ x (begin (set! x 40) x)))
  10681. \end{lstlisting}
  10682. The result of this program is \code{42} because the first read from
  10683. \code{x} produces \code{2} and the second produces \code{40}. However,
  10684. if we naively apply the \code{remove\_complex\_operands} pass to this
  10685. example we obtain the following program whose result is \code{80}!
  10686. \begin{lstlisting}
  10687. (let ([x 2])
  10688. (let ([tmp (begin (set! x 40) x)])
  10689. (+ x tmp)))
  10690. \end{lstlisting}
  10691. The problem is that with mutable variables, the ordering between
  10692. reads and writes is important, and the
  10693. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10694. before the first read of \code{x}.
  10695. We recommend solving this problem by giving special treatment to reads
  10696. from mutable variables, that is, variables that occur on the left-hand
  10697. side of a \code{set!}. We mark each read from a mutable variable with
  10698. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10699. that the read operation is effectful in that it can produce different
  10700. results at different points in time. Let's apply this idea to the
  10701. following variation that also involves a variable that is not mutated:
  10702. % loop_test_24.rkt
  10703. \begin{lstlisting}
  10704. (let ([x 2])
  10705. (let ([y 0])
  10706. (+ y (+ x (begin (set! x 40) x)))))
  10707. \end{lstlisting}
  10708. We first analyze this program to discover that variable \code{x}
  10709. is mutable but \code{y} is not. We then transform the program as
  10710. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10711. \begin{lstlisting}
  10712. (let ([x 2])
  10713. (let ([y 0])
  10714. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10715. \end{lstlisting}
  10716. Now that we have a clear distinction between reads from mutable and
  10717. immutable variables, we can apply the \code{remove\_complex\_operands}
  10718. pass, where reads from immutable variables are still classified as
  10719. atomic expressions but reads from mutable variables are classified as
  10720. complex. Thus, \code{remove\_complex\_operands} yields the following
  10721. program:\\
  10722. \begin{minipage}{\textwidth}
  10723. \begin{lstlisting}
  10724. (let ([x 2])
  10725. (let ([y 0])
  10726. (let ([t1 x])
  10727. (let ([t2 (begin (set! x 40) x)])
  10728. (let ([t3 (+ t1 t2)])
  10729. (+ y t3))))))
  10730. \end{lstlisting}
  10731. \end{minipage}
  10732. The temporary variable \code{t1} gets the value of \code{x} before the
  10733. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10734. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10735. do not generate a temporary variable for the occurrence of \code{y}
  10736. because it's an immutable variable. We want to avoid such unnecessary
  10737. extra temporaries because they would needlessly increase the number of
  10738. variables, making it more likely for some of them to be spilled. The
  10739. result of this program is \code{42}, the same as the result prior to
  10740. \code{remove\_complex\_operands}.
  10741. The approach that we've sketched requires only a small
  10742. modification to \code{remove\_complex\_operands} to handle
  10743. \code{get!}. However, it requires a new pass, called
  10744. \code{uncover-get!}, that we discuss in
  10745. section~\ref{sec:uncover-get-bang}.
  10746. As an aside, this problematic interaction between \code{set!} and the
  10747. pass \code{remove\_complex\_operands} is particular to Racket and not
  10748. its predecessor, the Scheme language. The key difference is that
  10749. Scheme does not specify an order of evaluation for the arguments of an
  10750. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10751. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10752. would be correct results for the example program. Interestingly,
  10753. Racket is implemented on top of the Chez Scheme
  10754. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10755. presented in this section (using extra \code{let} bindings to control
  10756. the order of evaluation) is used in the translation from Racket to
  10757. Scheme~\citep{Flatt:2019tb}.
  10758. \fi} % racket
  10759. Having discussed the complications that arise from adding support for
  10760. assignment and loops, we turn to discussing the individual compilation
  10761. passes.
  10762. {\if\edition\racketEd
  10763. \section{Uncover \texttt{get!}}
  10764. \label{sec:uncover-get-bang}
  10765. The goal of this pass is to mark uses of mutable variables so that
  10766. \code{remove\_complex\_operands} can treat them as complex expressions
  10767. and thereby preserve their ordering relative to the side effects in
  10768. other operands. So, the first step is to collect all the mutable
  10769. variables. We recommend creating an auxiliary function for this,
  10770. named \code{collect-set!}, that recursively traverses expressions,
  10771. returning the set of all variables that occur on the left-hand side of a
  10772. \code{set!}. Here's an excerpt of its implementation.
  10773. \begin{center}
  10774. \begin{minipage}{\textwidth}
  10775. \begin{lstlisting}
  10776. (define (collect-set! e)
  10777. (match e
  10778. [(Var x) (set)]
  10779. [(Int n) (set)]
  10780. [(Let x rhs body)
  10781. (set-union (collect-set! rhs) (collect-set! body))]
  10782. [(SetBang var rhs)
  10783. (set-union (set var) (collect-set! rhs))]
  10784. ...))
  10785. \end{lstlisting}
  10786. \end{minipage}
  10787. \end{center}
  10788. By placing this pass after \code{uniquify}, we need not worry about
  10789. variable shadowing, and our logic for \code{Let} can remain simple, as
  10790. in this excerpt.
  10791. The second step is to mark the occurrences of the mutable variables
  10792. with the new \code{GetBang} AST node (\code{get!} in concrete
  10793. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10794. function, which takes two parameters: the set of mutable variables
  10795. \code{set!-vars} and the expression \code{e} to be processed. The
  10796. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10797. mutable variable or leaves it alone if not.
  10798. \begin{center}
  10799. \begin{minipage}{\textwidth}
  10800. \begin{lstlisting}
  10801. (define ((uncover-get!-exp set!-vars) e)
  10802. (match e
  10803. [(Var x)
  10804. (if (set-member? set!-vars x)
  10805. (GetBang x)
  10806. (Var x))]
  10807. ...))
  10808. \end{lstlisting}
  10809. \end{minipage}
  10810. \end{center}
  10811. To wrap things up, define the \code{uncover-get!} function for
  10812. processing a whole program, using \code{collect-set!} to obtain the
  10813. set of mutable variables and then \code{uncover-get!-exp} to replace
  10814. their occurrences with \code{GetBang}.
  10815. \fi}
  10816. \section{Remove Complex Operands}
  10817. \label{sec:rco-loop}
  10818. {\if\edition\racketEd
  10819. %
  10820. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10821. \code{while} are all complex expressions. The subexpressions of
  10822. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10823. %
  10824. \fi}
  10825. {\if\edition\pythonEd\pythonColor
  10826. %
  10827. The change needed for this pass is to add a case for the \code{while}
  10828. statement. The condition of a loop is allowed to be a complex
  10829. expression, just like the condition of the \code{if} statement.
  10830. %
  10831. \fi}
  10832. %
  10833. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10834. \LangLoopANF{} of this pass.
  10835. \newcommand{\LwhileMonadASTRacket}{
  10836. \begin{array}{rcl}
  10837. \Atm &::=& \VOID{} \\
  10838. \Exp &::=& \GETBANG{\Var}
  10839. \MID \SETBANG{\Var}{\Exp}
  10840. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10841. &\MID& \WHILE{\Exp}{\Exp}
  10842. \end{array}
  10843. }
  10844. \newcommand{\LwhileMonadASTPython}{
  10845. \begin{array}{rcl}
  10846. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10847. \end{array}
  10848. }
  10849. \begin{figure}[tp]
  10850. \centering
  10851. \begin{tcolorbox}[colback=white]
  10852. \small
  10853. {\if\edition\racketEd
  10854. \[
  10855. \begin{array}{l}
  10856. \gray{\LvarMonadASTRacket} \\ \hline
  10857. \gray{\LifMonadASTRacket} \\ \hline
  10858. \LwhileMonadASTRacket \\
  10859. \begin{array}{rcl}
  10860. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10861. \end{array}
  10862. \end{array}
  10863. \]
  10864. \fi}
  10865. {\if\edition\pythonEd\pythonColor
  10866. \[
  10867. \begin{array}{l}
  10868. \gray{\LvarMonadASTPython} \\ \hline
  10869. \gray{\LifMonadASTPython} \\ \hline
  10870. \LwhileMonadASTPython \\
  10871. \begin{array}{rcl}
  10872. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10873. \end{array}
  10874. \end{array}
  10875. \]
  10876. \fi}
  10877. \end{tcolorbox}
  10878. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10879. \label{fig:Lwhile-anf-syntax}
  10880. \end{figure}
  10881. {\if\edition\racketEd
  10882. %
  10883. As usual, when a complex expression appears in a grammar position that
  10884. needs to be atomic, such as the argument of a primitive operator, we
  10885. must introduce a temporary variable and bind it to the complex
  10886. expression. This approach applies, unchanged, to handle the new
  10887. language forms. For example, in the following code there are two
  10888. \code{begin} expressions appearing as arguments to the \code{+}
  10889. operator. The output of \code{rco\_exp} is then shown, in which the
  10890. \code{begin} expressions have been bound to temporary
  10891. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10892. allowed to have arbitrary expressions in their right-hand side
  10893. expression, so it is fine to place \code{begin} there.
  10894. %
  10895. \begin{center}
  10896. \begin{tabular}{lcl}
  10897. \begin{minipage}{0.4\textwidth}
  10898. \begin{lstlisting}
  10899. (let ([x2 10])
  10900. (let ([y3 0])
  10901. (+ (+ (begin
  10902. (set! y3 (read))
  10903. (get! x2))
  10904. (begin
  10905. (set! x2 (read))
  10906. (get! y3)))
  10907. (get! x2))))
  10908. \end{lstlisting}
  10909. \end{minipage}
  10910. &
  10911. $\Rightarrow$
  10912. &
  10913. \begin{minipage}{0.4\textwidth}
  10914. \begin{lstlisting}
  10915. (let ([x2 10])
  10916. (let ([y3 0])
  10917. (let ([tmp4 (begin
  10918. (set! y3 (read))
  10919. x2)])
  10920. (let ([tmp5 (begin
  10921. (set! x2 (read))
  10922. y3)])
  10923. (let ([tmp6 (+ tmp4 tmp5)])
  10924. (let ([tmp7 x2])
  10925. (+ tmp6 tmp7)))))))
  10926. \end{lstlisting}
  10927. \end{minipage}
  10928. \end{tabular}
  10929. \end{center}
  10930. \fi}
  10931. \section{Explicate Control \racket{and \LangCLoop{}}}
  10932. \label{sec:explicate-loop}
  10933. \newcommand{\CloopASTRacket}{
  10934. \begin{array}{lcl}
  10935. \Atm &::=& \VOID \\
  10936. \Stmt &::=& \READ{}
  10937. \end{array}
  10938. }
  10939. {\if\edition\racketEd
  10940. Recall that in the \code{explicate\_control} pass we define one helper
  10941. function for each kind of position in the program. For the \LangVar{}
  10942. language of integers and variables, we needed assignment and tail
  10943. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10944. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10945. another kind of position: effect position. Except for the last
  10946. subexpression, the subexpressions inside a \code{begin} are evaluated
  10947. only for their effect. Their result values are discarded. We can
  10948. generate better code by taking this fact into account.
  10949. The output language of \code{explicate\_control} is \LangCLoop{}
  10950. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10951. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10952. and that \code{read} may appear as a statement. The most significant
  10953. difference between the programs generated by \code{explicate\_control}
  10954. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10955. chapter is that the control-flow graphs of the latter may contain
  10956. cycles.
  10957. \begin{figure}[tp]
  10958. \begin{tcolorbox}[colback=white]
  10959. \small
  10960. \[
  10961. \begin{array}{l}
  10962. \gray{\CvarASTRacket} \\ \hline
  10963. \gray{\CifASTRacket} \\ \hline
  10964. \CloopASTRacket \\
  10965. \begin{array}{lcl}
  10966. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10967. \end{array}
  10968. \end{array}
  10969. \]
  10970. \end{tcolorbox}
  10971. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10972. \label{fig:c7-syntax}
  10973. \end{figure}
  10974. The new auxiliary function \code{explicate\_effect} takes an
  10975. expression (in an effect position) and the code for its
  10976. continuation. The function returns a $\Tail$ that includes the
  10977. generated code for the input expression followed by the
  10978. continuation. If the expression is obviously pure, that is, never
  10979. causes side effects, then the expression can be removed, so the result
  10980. is just the continuation.
  10981. %
  10982. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10983. interesting; the generated code is depicted in the following diagram:
  10984. \begin{center}
  10985. \begin{minipage}{0.3\textwidth}
  10986. \xymatrix{
  10987. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10988. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10989. & *+[F]{\txt{\itm{cont}}} \\
  10990. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10991. }
  10992. \end{minipage}
  10993. \end{center}
  10994. We start by creating a fresh label $\itm{loop}$ for the top of the
  10995. loop. Next, recursively process the \itm{body} (in effect position)
  10996. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10997. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10998. \itm{body'} as the \emph{then} branch and the continuation block as the
  10999. \emph{else} branch. The result should be added to the dictionary of
  11000. \code{basic-blocks} with the label \itm{loop}. The result for the
  11001. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11002. The auxiliary functions for tail, assignment, and predicate positions
  11003. need to be updated. The three new language forms, \code{while},
  11004. \code{set!}, and \code{begin}, can appear in assignment and tail
  11005. positions. Only \code{begin} may appear in predicate positions; the
  11006. other two have result type \code{Void}.
  11007. \fi}
  11008. %
  11009. {\if\edition\pythonEd\pythonColor
  11010. %
  11011. The output of this pass is the language \LangCIf{}. No new language
  11012. features are needed in the output, because a \code{while} loop can be
  11013. expressed in terms of \code{goto} and \code{if} statements, which are
  11014. already in \LangCIf{}.
  11015. %
  11016. Add a case for the \code{while} statement to the
  11017. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11018. the condition expression.
  11019. %
  11020. \fi}
  11021. {\if\edition\racketEd
  11022. \section{Select Instructions}
  11023. \label{sec:select-instructions-loop}
  11024. \index{subject}{select instructions}
  11025. Only two small additions are needed in the \code{select\_instructions}
  11026. pass to handle the changes to \LangCLoop{}. First, to handle the
  11027. addition of \VOID{} we simply translate it to \code{0}. Second,
  11028. \code{read} may appear as a stand-alone statement instead of
  11029. appearing only on the right-hand side of an assignment statement. The code
  11030. generation is nearly identical to the one for assignment; just leave
  11031. off the instruction for moving the result into the left-hand side.
  11032. \fi}
  11033. \section{Register Allocation}
  11034. \label{sec:register-allocation-loop}
  11035. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11036. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11037. which complicates the liveness analysis needed for register
  11038. allocation.
  11039. %
  11040. We recommend using the generic \code{analyze\_dataflow} function that
  11041. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11042. perform liveness analysis, replacing the code in
  11043. \code{uncover\_live} that processed the basic blocks in topological
  11044. order (section~\ref{sec:liveness-analysis-Lif}).
  11045. The \code{analyze\_dataflow} function has the following four parameters.
  11046. \begin{enumerate}
  11047. \item The first parameter \code{G} should be passed the transpose
  11048. of the control-flow graph.
  11049. \item The second parameter \code{transfer} should be passed a function
  11050. that applies liveness analysis to a basic block. It takes two
  11051. parameters: the label for the block to analyze and the live-after
  11052. set for that block. The transfer function should return the
  11053. live-before set for the block.
  11054. %
  11055. \racket{Also, as a side effect, it should update the block's
  11056. $\itm{info}$ with the liveness information for each instruction.}
  11057. %
  11058. \python{Also, as a side effect, it should update the live-before and
  11059. live-after sets for each instruction.}
  11060. %
  11061. To implement the \code{transfer} function, you should be able to
  11062. reuse the code you already have for analyzing basic blocks.
  11063. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11064. \code{bottom} and \code{join} for the lattice of abstract states,
  11065. that is, sets of locations. For liveness analysis, the bottom of the
  11066. lattice is the empty set, and the join operator is set union.
  11067. \end{enumerate}
  11068. \begin{figure}[tp]
  11069. \begin{tcolorbox}[colback=white]
  11070. {\if\edition\racketEd
  11071. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11072. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11073. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11074. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11075. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11076. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11077. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11078. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11079. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11080. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11081. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11082. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11083. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11084. \path[->,bend left=15] (Lfun) edge [above] node
  11085. {\ttfamily\footnotesize shrink} (Lfun-2);
  11086. \path[->,bend left=15] (Lfun-2) edge [above] node
  11087. {\ttfamily\footnotesize uniquify} (F1-4);
  11088. \path[->,bend left=15] (F1-4) edge [above] node
  11089. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11090. \path[->,bend left=15] (F1-5) edge [left] node
  11091. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11092. \path[->,bend left=10] (F1-6) edge [above] node
  11093. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11094. \path[->,bend left=15] (C3-2) edge [right] node
  11095. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11096. \path[->,bend right=15] (x86-2) edge [right] node
  11097. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11098. \path[->,bend right=15] (x86-2-1) edge [below] node
  11099. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11100. \path[->,bend right=15] (x86-2-2) edge [right] node
  11101. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11102. \path[->,bend left=15] (x86-3) edge [above] node
  11103. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11104. \path[->,bend left=15] (x86-4) edge [right] node
  11105. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11106. \end{tikzpicture}
  11107. \fi}
  11108. {\if\edition\pythonEd\pythonColor
  11109. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11110. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11111. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11112. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11113. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11114. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11115. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11116. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11117. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11118. \path[->,bend left=15] (Lfun) edge [above] node
  11119. {\ttfamily\footnotesize shrink} (Lfun-2);
  11120. \path[->,bend left=15] (Lfun-2) edge [above] node
  11121. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11122. \path[->,bend left=10] (F1-6) edge [right] node
  11123. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11124. \path[->,bend right=15] (C3-2) edge [right] node
  11125. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11126. \path[->,bend right=15] (x86-2) edge [below] node
  11127. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11128. \path[->,bend left=15] (x86-3) edge [above] node
  11129. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11130. \path[->,bend right=15] (x86-4) edge [below] node
  11131. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11132. \end{tikzpicture}
  11133. \fi}
  11134. \end{tcolorbox}
  11135. \caption{Diagram of the passes for \LangLoop{}.}
  11136. \label{fig:Lwhile-passes}
  11137. \end{figure}
  11138. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11139. for the compilation of \LangLoop{}.
  11140. % Further Reading: dataflow analysis
  11141. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11142. \chapter{Tuples and Garbage Collection}
  11143. \label{ch:Lvec}
  11144. \index{subject}{tuple}
  11145. \index{subject}{vector}
  11146. \setcounter{footnote}{0}
  11147. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11148. %% all the IR grammars are spelled out! \\ --Jeremy}
  11149. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11150. %% the root stack. \\ --Jeremy}
  11151. In this chapter we study the implementation of tuples\racket{, called
  11152. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11153. in which each element may have a different type.
  11154. %
  11155. This language feature is the first to use the computer's
  11156. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11157. indefinite; that is, a tuple lives forever from the programmer's
  11158. viewpoint. Of course, from an implementer's viewpoint, it is important
  11159. to reclaim the space associated with a tuple when it is no longer
  11160. needed, which is why we also study \emph{garbage collection}
  11161. \index{subject}{garbage collection} techniques in this chapter.
  11162. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11163. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11164. language (chapter~\ref{ch:Lwhile}) with tuples.
  11165. %
  11166. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11167. copying live tuples back and forth between two halves of the heap. The
  11168. garbage collector requires coordination with the compiler so that it
  11169. can find all the live tuples.
  11170. %
  11171. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11172. discuss the necessary changes and additions to the compiler passes,
  11173. including a new compiler pass named \code{expose\_allocation}.
  11174. \section{The \LangVec{} Language}
  11175. \label{sec:r3}
  11176. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11177. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11178. the definition of the abstract syntax.
  11179. %
  11180. \racket{The \LangVec{} language includes the forms \code{vector} for
  11181. creating a tuple, \code{vector-ref} for reading an element of a
  11182. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11183. \code{vector-length} for obtaining the number of elements of a
  11184. tuple.}
  11185. %
  11186. \python{The \LangVec{} language adds (1) tuple creation via a
  11187. comma-separated list of expressions; (2) accessing an element of a
  11188. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11189. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11190. comparison operator; and (4) obtaining the number of elements (the
  11191. length) of a tuple. In this chapter, we restrict access indices to
  11192. constant integers.}
  11193. %
  11194. The following program shows an example of the use of tuples. It creates a tuple
  11195. \code{t} containing the elements \code{40},
  11196. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11197. contains just \code{2}. The element at index $1$ of \code{t} is
  11198. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11199. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11200. to which we add \code{2}, the element at index $0$ of the tuple.
  11201. The result of the program is \code{42}.
  11202. %
  11203. {\if\edition\racketEd
  11204. \begin{lstlisting}
  11205. (let ([t (vector 40 #t (vector 2))])
  11206. (if (vector-ref t 1)
  11207. (+ (vector-ref t 0)
  11208. (vector-ref (vector-ref t 2) 0))
  11209. 44))
  11210. \end{lstlisting}
  11211. \fi}
  11212. {\if\edition\pythonEd\pythonColor
  11213. \begin{lstlisting}
  11214. t = 40, True, (2,)
  11215. print(t[0] + t[2][0] if t[1] else 44)
  11216. \end{lstlisting}
  11217. \fi}
  11218. \newcommand{\LtupGrammarRacket}{
  11219. \begin{array}{lcl}
  11220. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11221. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11222. \MID \LP\key{vector-length}\;\Exp\RP \\
  11223. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11224. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11225. \end{array}
  11226. }
  11227. \newcommand{\LtupASTRacket}{
  11228. \begin{array}{lcl}
  11229. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11230. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11231. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11232. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11233. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11234. \end{array}
  11235. }
  11236. \newcommand{\LtupGrammarPython}{
  11237. \begin{array}{rcl}
  11238. \itm{cmp} &::= & \key{is} \\
  11239. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11240. \end{array}
  11241. }
  11242. \newcommand{\LtupASTPython}{
  11243. \begin{array}{lcl}
  11244. \itm{cmp} &::= & \code{Is()} \\
  11245. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11246. &\MID& \LEN{\Exp}
  11247. \end{array}
  11248. }
  11249. \begin{figure}[tbp]
  11250. \centering
  11251. \begin{tcolorbox}[colback=white]
  11252. \small
  11253. {\if\edition\racketEd
  11254. \[
  11255. \begin{array}{l}
  11256. \gray{\LintGrammarRacket{}} \\ \hline
  11257. \gray{\LvarGrammarRacket{}} \\ \hline
  11258. \gray{\LifGrammarRacket{}} \\ \hline
  11259. \gray{\LwhileGrammarRacket} \\ \hline
  11260. \LtupGrammarRacket \\
  11261. \begin{array}{lcl}
  11262. \LangVecM{} &::=& \Exp
  11263. \end{array}
  11264. \end{array}
  11265. \]
  11266. \fi}
  11267. {\if\edition\pythonEd\pythonColor
  11268. \[
  11269. \begin{array}{l}
  11270. \gray{\LintGrammarPython{}} \\ \hline
  11271. \gray{\LvarGrammarPython{}} \\ \hline
  11272. \gray{\LifGrammarPython{}} \\ \hline
  11273. \gray{\LwhileGrammarPython} \\ \hline
  11274. \LtupGrammarPython \\
  11275. \begin{array}{rcl}
  11276. \LangVecM{} &::=& \Stmt^{*}
  11277. \end{array}
  11278. \end{array}
  11279. \]
  11280. \fi}
  11281. \end{tcolorbox}
  11282. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11283. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11284. \label{fig:Lvec-concrete-syntax}
  11285. \end{figure}
  11286. \begin{figure}[tp]
  11287. \centering
  11288. \begin{tcolorbox}[colback=white]
  11289. \small
  11290. {\if\edition\racketEd
  11291. \[
  11292. \begin{array}{l}
  11293. \gray{\LintOpAST} \\ \hline
  11294. \gray{\LvarASTRacket{}} \\ \hline
  11295. \gray{\LifASTRacket{}} \\ \hline
  11296. \gray{\LwhileASTRacket{}} \\ \hline
  11297. \LtupASTRacket{} \\
  11298. \begin{array}{lcl}
  11299. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11300. \end{array}
  11301. \end{array}
  11302. \]
  11303. \fi}
  11304. {\if\edition\pythonEd\pythonColor
  11305. \[
  11306. \begin{array}{l}
  11307. \gray{\LintASTPython} \\ \hline
  11308. \gray{\LvarASTPython} \\ \hline
  11309. \gray{\LifASTPython} \\ \hline
  11310. \gray{\LwhileASTPython} \\ \hline
  11311. \LtupASTPython \\
  11312. \begin{array}{lcl}
  11313. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11314. \end{array}
  11315. \end{array}
  11316. \]
  11317. \fi}
  11318. \end{tcolorbox}
  11319. \caption{The abstract syntax of \LangVec{}.}
  11320. \label{fig:Lvec-syntax}
  11321. \end{figure}
  11322. Tuples raise several interesting new issues. First, variable binding
  11323. performs a shallow copy in dealing with tuples, which means that
  11324. different variables can refer to the same tuple; that is, two
  11325. variables can be \emph{aliases}\index{subject}{alias} for the same
  11326. entity. Consider the following example, in which \code{t1} and
  11327. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11328. different tuple value with equal elements. The result of the
  11329. program is \code{42}.
  11330. \begin{center}
  11331. \begin{minipage}{0.96\textwidth}
  11332. {\if\edition\racketEd
  11333. \begin{lstlisting}
  11334. (let ([t1 (vector 3 7)])
  11335. (let ([t2 t1])
  11336. (let ([t3 (vector 3 7)])
  11337. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11338. 42
  11339. 0))))
  11340. \end{lstlisting}
  11341. \fi}
  11342. {\if\edition\pythonEd\pythonColor
  11343. \begin{lstlisting}
  11344. t1 = 3, 7
  11345. t2 = t1
  11346. t3 = 3, 7
  11347. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11348. \end{lstlisting}
  11349. \fi}
  11350. \end{minipage}
  11351. \end{center}
  11352. {\if\edition\racketEd
  11353. Whether two variables are aliased or not affects what happens
  11354. when the underlying tuple is mutated\index{subject}{mutation}.
  11355. Consider the following example in which \code{t1} and \code{t2}
  11356. again refer to the same tuple value.
  11357. \begin{center}
  11358. \begin{minipage}{0.96\textwidth}
  11359. \begin{lstlisting}
  11360. (let ([t1 (vector 3 7)])
  11361. (let ([t2 t1])
  11362. (let ([_ (vector-set! t2 0 42)])
  11363. (vector-ref t1 0))))
  11364. \end{lstlisting}
  11365. \end{minipage}
  11366. \end{center}
  11367. The mutation through \code{t2} is visible in referencing the tuple
  11368. from \code{t1}, so the result of this program is \code{42}.
  11369. \fi}
  11370. The next issue concerns the lifetime of tuples. When does a tuple's
  11371. lifetime end? Notice that \LangVec{} does not include an operation
  11372. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11373. to any notion of static scoping.
  11374. %
  11375. {\if\edition\racketEd
  11376. %
  11377. For example, the following program returns \code{42} even though the
  11378. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11379. that reads from the vector to which it was bound.
  11380. \begin{center}
  11381. \begin{minipage}{0.96\textwidth}
  11382. \begin{lstlisting}
  11383. (let ([v (vector (vector 44))])
  11384. (let ([x (let ([w (vector 42)])
  11385. (let ([_ (vector-set! v 0 w)])
  11386. 0))])
  11387. (+ x (vector-ref (vector-ref v 0) 0))))
  11388. \end{lstlisting}
  11389. \end{minipage}
  11390. \end{center}
  11391. \fi}
  11392. %
  11393. {\if\edition\pythonEd\pythonColor
  11394. %
  11395. For example, the following program returns \code{42} even though the
  11396. variable \code{x} goes out of scope when the function returns, prior
  11397. to reading the tuple element at index $0$. (We study the compilation
  11398. of functions in chapter~\ref{ch:Lfun}.)
  11399. %
  11400. \begin{center}
  11401. \begin{minipage}{0.96\textwidth}
  11402. \begin{lstlisting}
  11403. def f():
  11404. x = 42, 43
  11405. return x
  11406. t = f()
  11407. print(t[0])
  11408. \end{lstlisting}
  11409. \end{minipage}
  11410. \end{center}
  11411. \fi}
  11412. %
  11413. From the perspective of programmer-observable behavior, tuples live
  11414. forever. However, if they really lived forever then many long-running
  11415. programs would run out of memory. To solve this problem, the
  11416. language's runtime system performs automatic garbage collection.
  11417. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11418. \LangVec{} language.
  11419. %
  11420. \racket{We define the \code{vector}, \code{vector-ref},
  11421. \code{vector-set!}, and \code{vector-length} operations for
  11422. \LangVec{} in terms of the corresponding operations in Racket. One
  11423. subtle point is that the \code{vector-set!} operation returns the
  11424. \code{\#<void>} value.}
  11425. %
  11426. \python{We represent tuples with Python lists in the interpreter
  11427. because we need to write to them
  11428. (section~\ref{sec:expose-allocation}). (Python tuples are
  11429. immutable.) We define element access, the \code{is} operator, and
  11430. the \code{len} operator for \LangVec{} in terms of the corresponding
  11431. operations in Python.}
  11432. \begin{figure}[tbp]
  11433. \begin{tcolorbox}[colback=white]
  11434. {\if\edition\racketEd
  11435. \begin{lstlisting}
  11436. (define interp-Lvec-class
  11437. (class interp-Lwhile-class
  11438. (super-new)
  11439. (define/override (interp-op op)
  11440. (match op
  11441. ['eq? (lambda (v1 v2)
  11442. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11443. (and (boolean? v1) (boolean? v2))
  11444. (and (vector? v1) (vector? v2))
  11445. (and (void? v1) (void? v2)))
  11446. (eq? v1 v2)]))]
  11447. ['vector vector]
  11448. ['vector-length vector-length]
  11449. ['vector-ref vector-ref]
  11450. ['vector-set! vector-set!]
  11451. [else (super interp-op op)]
  11452. ))
  11453. (define/override ((interp-exp env) e)
  11454. (match e
  11455. [(HasType e t) ((interp-exp env) e)]
  11456. [else ((super interp-exp env) e)]
  11457. ))
  11458. ))
  11459. (define (interp-Lvec p)
  11460. (send (new interp-Lvec-class) interp-program p))
  11461. \end{lstlisting}
  11462. \fi}
  11463. %
  11464. {\if\edition\pythonEd\pythonColor
  11465. \begin{lstlisting}
  11466. class InterpLtup(InterpLwhile):
  11467. def interp_cmp(self, cmp):
  11468. match cmp:
  11469. case Is():
  11470. return lambda x, y: x is y
  11471. case _:
  11472. return super().interp_cmp(cmp)
  11473. def interp_exp(self, e, env):
  11474. match e:
  11475. case Tuple(es, Load()):
  11476. return tuple([self.interp_exp(e, env) for e in es])
  11477. case Subscript(tup, index, Load()):
  11478. t = self.interp_exp(tup, env)
  11479. n = self.interp_exp(index, env)
  11480. return t[n]
  11481. case _:
  11482. return super().interp_exp(e, env)
  11483. \end{lstlisting}
  11484. \fi}
  11485. \end{tcolorbox}
  11486. \caption{Interpreter for the \LangVec{} language.}
  11487. \label{fig:interp-Lvec}
  11488. \end{figure}
  11489. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11490. \LangVec{}.
  11491. %
  11492. The type of a tuple is a
  11493. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11494. type for each of its elements.
  11495. %
  11496. \racket{To create the s-expression for the \code{Vector} type, we use the
  11497. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11498. operator} \code{,@} to insert the list \code{t*} without its usual
  11499. start and end parentheses. \index{subject}{unquote-splicing}}
  11500. %
  11501. The type of accessing the ith element of a tuple is the ith element
  11502. type of the tuple's type, if there is one. If not, an error is
  11503. signaled. Note that the index \code{i} is required to be a constant
  11504. integer (and not, for example, a call to
  11505. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11506. can determine the element's type given the tuple type.
  11507. %
  11508. \racket{
  11509. Regarding writing an element to a tuple, the element's type must
  11510. be equal to the ith element type of the tuple's type.
  11511. The result type is \code{Void}.}
  11512. %% When allocating a tuple,
  11513. %% we need to know which elements of the tuple are themselves tuples for
  11514. %% the purposes of garbage collection. We can obtain this information
  11515. %% during type checking. The type checker shown in
  11516. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11517. %% expression; it also
  11518. %% %
  11519. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11520. %% where $T$ is the tuple's type.
  11521. %
  11522. %records the type of each tuple expression in a new field named \code{has\_type}.
  11523. \begin{figure}[tp]
  11524. \begin{tcolorbox}[colback=white]
  11525. {\if\edition\racketEd
  11526. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11527. (define type-check-Lvec-class
  11528. (class type-check-Lif-class
  11529. (super-new)
  11530. (inherit check-type-equal?)
  11531. (define/override (type-check-exp env)
  11532. (lambda (e)
  11533. (define recur (type-check-exp env))
  11534. (match e
  11535. [(Prim 'vector es)
  11536. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11537. (define t `(Vector ,@t*))
  11538. (values (Prim 'vector e*) t)]
  11539. [(Prim 'vector-ref (list e1 (Int i)))
  11540. (define-values (e1^ t) (recur e1))
  11541. (match t
  11542. [`(Vector ,ts ...)
  11543. (unless (and (0 . <= . i) (i . < . (length ts)))
  11544. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11545. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11546. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11547. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11548. (define-values (e-vec t-vec) (recur e1))
  11549. (define-values (e-elt^ t-elt) (recur elt))
  11550. (match t-vec
  11551. [`(Vector ,ts ...)
  11552. (unless (and (0 . <= . i) (i . < . (length ts)))
  11553. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11554. (check-type-equal? (list-ref ts i) t-elt e)
  11555. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11556. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11557. [(Prim 'vector-length (list e))
  11558. (define-values (e^ t) (recur e))
  11559. (match t
  11560. [`(Vector ,ts ...)
  11561. (values (Prim 'vector-length (list e^)) 'Integer)]
  11562. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11563. [(Prim 'eq? (list arg1 arg2))
  11564. (define-values (e1 t1) (recur arg1))
  11565. (define-values (e2 t2) (recur arg2))
  11566. (match* (t1 t2)
  11567. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11568. [(other wise) (check-type-equal? t1 t2 e)])
  11569. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11570. [else ((super type-check-exp env) e)]
  11571. )))
  11572. ))
  11573. (define (type-check-Lvec p)
  11574. (send (new type-check-Lvec-class) type-check-program p))
  11575. \end{lstlisting}
  11576. \fi}
  11577. {\if\edition\pythonEd\pythonColor
  11578. \begin{lstlisting}
  11579. class TypeCheckLtup(TypeCheckLwhile):
  11580. def type_check_exp(self, e, env):
  11581. match e:
  11582. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11583. l = self.type_check_exp(left, env)
  11584. r = self.type_check_exp(right, env)
  11585. check_type_equal(l, r, e)
  11586. return bool
  11587. case Tuple(es, Load()):
  11588. ts = [self.type_check_exp(e, env) for e in es]
  11589. e.has_type = TupleType(ts)
  11590. return e.has_type
  11591. case Subscript(tup, Constant(i), Load()):
  11592. tup_ty = self.type_check_exp(tup, env)
  11593. i_ty = self.type_check_exp(Constant(i), env)
  11594. check_type_equal(i_ty, int, i)
  11595. match tup_ty:
  11596. case TupleType(ts):
  11597. return ts[i]
  11598. case _:
  11599. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11600. case _:
  11601. return super().type_check_exp(e, env)
  11602. \end{lstlisting}
  11603. \fi}
  11604. \end{tcolorbox}
  11605. \caption{Type checker for the \LangVec{} language.}
  11606. \label{fig:type-check-Lvec}
  11607. \end{figure}
  11608. \section{Garbage Collection}
  11609. \label{sec:GC}
  11610. Garbage collection is a runtime technique for reclaiming space on the
  11611. heap that will not be used in the future of the running program. We
  11612. use the term \emph{object}\index{subject}{object} to refer to any
  11613. value that is stored in the heap, which for now includes only
  11614. tuples.%
  11615. %
  11616. \footnote{The term \emph{object} as it is used in the context of
  11617. object-oriented programming has a more specific meaning than the
  11618. way in which we use the term here.}
  11619. %
  11620. Unfortunately, it is impossible to know precisely which objects will
  11621. be accessed in the future and which will not. Instead, garbage
  11622. collectors overapproximate the set of objects that will be accessed by
  11623. identifying which objects can possibly be accessed. The running
  11624. program can directly access objects that are in registers and on the
  11625. procedure call stack. It can also transitively access the elements of
  11626. tuples, starting with a tuple whose address is in a register or on the
  11627. procedure call stack. We define the \emph{root
  11628. set}\index{subject}{root set} to be all the tuple addresses that are
  11629. in registers or on the procedure call stack. We define the \emph{live
  11630. objects}\index{subject}{live objects} to be the objects that are
  11631. reachable from the root set. Garbage collectors reclaim the space that
  11632. is allocated to objects that are no longer live. \index{subject}{allocate}
  11633. That means that some objects may not get reclaimed as soon as they could be,
  11634. but at least
  11635. garbage collectors do not reclaim the space dedicated to objects that
  11636. will be accessed in the future! The programmer can influence which
  11637. objects get reclaimed by causing them to become unreachable.
  11638. So the goal of the garbage collector is twofold:
  11639. \begin{enumerate}
  11640. \item to preserve all the live objects, and
  11641. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11642. \end{enumerate}
  11643. \subsection{Two-Space Copying Collector}
  11644. Here we study a relatively simple algorithm for garbage collection
  11645. that is the basis of many state-of-the-art garbage
  11646. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11647. particular, we describe a two-space copying
  11648. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11649. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11650. collector} \index{subject}{two-space copying collector}
  11651. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11652. what happens in a two-space collector, showing two time steps, prior
  11653. to garbage collection (on the top) and after garbage collection (on
  11654. the bottom). In a two-space collector, the heap is divided into two
  11655. parts named the FromSpace\index{subject}{FromSpace} and the
  11656. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11657. FromSpace until there is not enough room for the next allocation
  11658. request. At that point, the garbage collector goes to work to make
  11659. room for the next allocation.
  11660. A copying collector makes more room by copying all the live objects
  11661. from the FromSpace into the ToSpace and then performs a sleight of
  11662. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11663. as the new ToSpace. In the example shown in
  11664. figure~\ref{fig:copying-collector}, the root set consists of three
  11665. pointers, one in a register and two on the stack. All the live
  11666. objects have been copied to the ToSpace (the right-hand side of
  11667. figure~\ref{fig:copying-collector}) in a way that preserves the
  11668. pointer relationships. For example, the pointer in the register still
  11669. points to a tuple that in turn points to two other tuples. There are
  11670. four tuples that are not reachable from the root set and therefore do
  11671. not get copied into the ToSpace.
  11672. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11673. created by a well-typed program in \LangVec{} because it contains a
  11674. cycle. However, creating cycles will be possible once we get to
  11675. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11676. to deal with cycles to begin with, so we will not need to revisit this
  11677. issue.
  11678. \begin{figure}[tbp]
  11679. \centering
  11680. \begin{tcolorbox}[colback=white]
  11681. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11682. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11683. \\[5ex]
  11684. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11685. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11686. \end{tcolorbox}
  11687. \caption{A copying collector in action.}
  11688. \label{fig:copying-collector}
  11689. \end{figure}
  11690. \subsection{Graph Copying via Cheney's Algorithm}
  11691. \label{sec:cheney}
  11692. \index{subject}{Cheney's algorithm}
  11693. Let us take a closer look at the copying of the live objects. The
  11694. allocated\index{subject}{allocate} objects and pointers can be viewed
  11695. as a graph, and we need to copy the part of the graph that is
  11696. reachable from the root set. To make sure that we copy all the
  11697. reachable vertices in the graph, we need an exhaustive graph traversal
  11698. algorithm, such as depth-first search or breadth-first
  11699. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11700. take into account the possibility of cycles by marking which vertices
  11701. have already been visited, so to ensure termination of the
  11702. algorithm. These search algorithms also use a data structure such as a
  11703. stack or queue as a to-do list to keep track of the vertices that need
  11704. to be visited. We use breadth-first search and a trick due to
  11705. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11706. copying tuples into the ToSpace.
  11707. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11708. copy progresses. The queue is represented by a chunk of contiguous
  11709. memory at the beginning of the ToSpace, using two pointers to track
  11710. the front and the back of the queue, called the \emph{free pointer}
  11711. and the \emph{scan pointer}, respectively. The algorithm starts by
  11712. copying all tuples that are immediately reachable from the root set
  11713. into the ToSpace to form the initial queue. When we copy a tuple, we
  11714. mark the old tuple to indicate that it has been visited. We discuss
  11715. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11716. that any pointers inside the copied tuples in the queue still point
  11717. back to the FromSpace. Once the initial queue has been created, the
  11718. algorithm enters a loop in which it repeatedly processes the tuple at
  11719. the front of the queue and pops it off the queue. To process a tuple,
  11720. the algorithm copies all the objects that are directly reachable from it
  11721. to the ToSpace, placing them at the back of the queue. The algorithm
  11722. then updates the pointers in the popped tuple so that they point to the
  11723. newly copied objects.
  11724. \begin{figure}[tbp]
  11725. \centering
  11726. \begin{tcolorbox}[colback=white]
  11727. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11728. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11729. \end{tcolorbox}
  11730. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11731. \label{fig:cheney}
  11732. \end{figure}
  11733. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11734. tuple whose second element is $42$ to the back of the queue. The other
  11735. pointer goes to a tuple that has already been copied, so we do not
  11736. need to copy it again, but we do need to update the pointer to the new
  11737. location. This can be accomplished by storing a \emph{forwarding
  11738. pointer}\index{subject}{forwarding pointer} to the new location in the
  11739. old tuple, when we initially copied the tuple into the
  11740. ToSpace. This completes one step of the algorithm. The algorithm
  11741. continues in this way until the queue is empty; that is, when the scan
  11742. pointer catches up with the free pointer.
  11743. \subsection{Data Representation}
  11744. \label{sec:data-rep-gc}
  11745. The garbage collector places some requirements on the data
  11746. representations used by our compiler. First, the garbage collector
  11747. needs to distinguish between pointers and other kinds of data such as
  11748. integers. The following are three ways to accomplish this:
  11749. \begin{enumerate}
  11750. \item Attach a tag to each object that identifies what type of
  11751. object it is~\citep{McCarthy:1960dz}.
  11752. \item Store different types of objects in different
  11753. regions~\citep{Steele:1977ab}.
  11754. \item Use type information from the program to either (a) generate
  11755. type-specific code for collecting, or (b) generate tables that
  11756. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11757. \end{enumerate}
  11758. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11759. need to tag objects in any case, so option 1 is a natural choice for those
  11760. languages. However, \LangVec{} is a statically typed language, so it
  11761. would be unfortunate to require tags on every object, especially small
  11762. and pervasive objects like integers and Booleans. Option 3 is the
  11763. best-performing choice for statically typed languages, but it comes with
  11764. a relatively high implementation complexity. To keep this chapter
  11765. within a reasonable scope of complexity, we recommend a combination of options
  11766. 1 and 2, using separate strategies for the stack and the heap.
  11767. Regarding the stack, we recommend using a separate stack for pointers,
  11768. which we call the \emph{root stack}\index{subject}{root stack}
  11769. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11770. That is, when a local variable needs to be spilled and is of type
  11771. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11772. root stack instead of putting it on the procedure call
  11773. stack. Furthermore, we always spill tuple-typed variables if they are
  11774. live during a call to the collector, thereby ensuring that no pointers
  11775. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11776. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11777. contrasts it with the data layout using a root stack. The root stack
  11778. contains the two pointers from the regular stack and also the pointer
  11779. in the second register.
  11780. \begin{figure}[tbp]
  11781. \centering
  11782. \begin{tcolorbox}[colback=white]
  11783. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11784. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11785. \end{tcolorbox}
  11786. \caption{Maintaining a root stack to facilitate garbage collection.}
  11787. \label{fig:shadow-stack}
  11788. \end{figure}
  11789. The problem of distinguishing between pointers and other kinds of data
  11790. also arises inside each tuple on the heap. We solve this problem by
  11791. attaching a tag, an extra 64 bits, to each
  11792. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11793. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11794. Note that we have drawn the bits in a big-endian way, from right to left,
  11795. with bit location 0 (the least significant bit) on the far right,
  11796. which corresponds to the direction of the x86 shifting instructions
  11797. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11798. is dedicated to specifying which elements of the tuple are pointers,
  11799. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11800. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11801. data. The pointer mask starts at bit location 7. We limit tuples to a
  11802. maximum size of fifty elements, so we need 50 bits for the pointer
  11803. mask.%
  11804. %
  11805. \footnote{A production-quality compiler would handle
  11806. arbitrarily sized tuples and use a more complex approach.}
  11807. %
  11808. The tag also contains two other pieces of information. The length of
  11809. the tuple (number of elements) is stored in bits at locations 1 through
  11810. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11811. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11812. has not yet been copied. If the bit has value 0, then the entire tag
  11813. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11814. zero in any case, because our tuples are 8-byte aligned.)
  11815. \begin{figure}[tbp]
  11816. \centering
  11817. \begin{tcolorbox}[colback=white]
  11818. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11819. \end{tcolorbox}
  11820. \caption{Representation of tuples in the heap.}
  11821. \label{fig:tuple-rep}
  11822. \end{figure}
  11823. \subsection{Implementation of the Garbage Collector}
  11824. \label{sec:organize-gz}
  11825. \index{subject}{prelude}
  11826. An implementation of the copying collector is provided in the
  11827. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11828. interface to the garbage collector that is used by the compiler. The
  11829. \code{initialize} function creates the FromSpace, ToSpace, and root
  11830. stack and should be called in the prelude of the \code{main}
  11831. function. The arguments of \code{initialize} are the root stack size
  11832. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11833. good choice for both. The \code{initialize} function puts the address
  11834. of the beginning of the FromSpace into the global variable
  11835. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11836. the address that is one past the last element of the FromSpace. We use
  11837. half-open intervals to represent chunks of
  11838. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11839. points to the first element of the root stack.
  11840. As long as there is room left in the FromSpace, your generated code
  11841. can allocate\index{subject}{allocate} tuples simply by moving the
  11842. \code{free\_ptr} forward.
  11843. %
  11844. The amount of room left in the FromSpace is the difference between the
  11845. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11846. function should be called when there is not enough room left in the
  11847. FromSpace for the next allocation. The \code{collect} function takes
  11848. a pointer to the current top of the root stack (one past the last item
  11849. that was pushed) and the number of bytes that need to be
  11850. allocated. The \code{collect} function performs the copying collection
  11851. and leaves the heap in a state such that there is enough room for the
  11852. next allocation.
  11853. \begin{figure}[tbp]
  11854. \begin{tcolorbox}[colback=white]
  11855. \begin{lstlisting}
  11856. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11857. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11858. int64_t* free_ptr;
  11859. int64_t* fromspace_begin;
  11860. int64_t* fromspace_end;
  11861. int64_t** rootstack_begin;
  11862. \end{lstlisting}
  11863. \end{tcolorbox}
  11864. \caption{The compiler's interface to the garbage collector.}
  11865. \label{fig:gc-header}
  11866. \end{figure}
  11867. %% \begin{exercise}
  11868. %% In the file \code{runtime.c} you will find the implementation of
  11869. %% \code{initialize} and a partial implementation of \code{collect}.
  11870. %% The \code{collect} function calls another function, \code{cheney},
  11871. %% to perform the actual copy, and that function is left to the reader
  11872. %% to implement. The following is the prototype for \code{cheney}.
  11873. %% \begin{lstlisting}
  11874. %% static void cheney(int64_t** rootstack_ptr);
  11875. %% \end{lstlisting}
  11876. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11877. %% rootstack (which is an array of pointers). The \code{cheney} function
  11878. %% also communicates with \code{collect} through the global
  11879. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11880. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11881. %% the ToSpace:
  11882. %% \begin{lstlisting}
  11883. %% static int64_t* tospace_begin;
  11884. %% static int64_t* tospace_end;
  11885. %% \end{lstlisting}
  11886. %% The job of the \code{cheney} function is to copy all the live
  11887. %% objects (reachable from the root stack) into the ToSpace, update
  11888. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11889. %% update the root stack so that it points to the objects in the
  11890. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11891. %% and ToSpace.
  11892. %% \end{exercise}
  11893. The introduction of garbage collection has a nontrivial impact on our
  11894. compiler passes. We introduce a new compiler pass named
  11895. \code{expose\_allocation} that elaborates the code for allocating
  11896. tuples. We also make significant changes to
  11897. \code{select\_instructions}, \code{build\_interference},
  11898. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11899. make minor changes in several more passes.
  11900. The following program serves as our running example. It creates
  11901. two tuples, one nested inside the other. Both tuples have length
  11902. one. The program accesses the element in the inner tuple.
  11903. % tests/vectors_test_17.rkt
  11904. {\if\edition\racketEd
  11905. \begin{lstlisting}
  11906. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11907. \end{lstlisting}
  11908. \fi}
  11909. % tests/tuple/get_get.py
  11910. {\if\edition\pythonEd\pythonColor
  11911. \begin{lstlisting}
  11912. v1 = (42,)
  11913. v2 = (v1,)
  11914. print(v2[0][0])
  11915. \end{lstlisting}
  11916. \fi}
  11917. %% {\if\edition\racketEd
  11918. %% \section{Shrink}
  11919. %% \label{sec:shrink-Lvec}
  11920. %% Recall that the \code{shrink} pass translates the primitives operators
  11921. %% into a smaller set of primitives.
  11922. %% %
  11923. %% This pass comes after type checking, and the type checker adds a
  11924. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11925. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11926. %% \fi}
  11927. \section{Expose Allocation}
  11928. \label{sec:expose-allocation}
  11929. The pass \code{expose\_allocation} lowers tuple creation into making a
  11930. conditional call to the collector followed by allocating the
  11931. appropriate amount of memory and initializing it. We choose to place
  11932. the \code{expose\_allocation} pass before
  11933. \code{remove\_complex\_operands} because it generates code that
  11934. contains complex operands. However, with some care it can also be
  11935. placed before \code{remove\_complex\_operands} which would simplify
  11936. tuple creation by removing the need to assign the initializing
  11937. expressions to temporary variables (see below).
  11938. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11939. that replaces tuple creation with new lower-level forms that we use in the
  11940. translation of tuple creation.
  11941. %
  11942. {\if\edition\racketEd
  11943. \[
  11944. \begin{array}{lcl}
  11945. \Exp &::=& (\key{collect} \,\itm{int})
  11946. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11947. \MID (\key{global-value} \,\itm{name})
  11948. \end{array}
  11949. \]
  11950. \fi}
  11951. {\if\edition\pythonEd\pythonColor
  11952. \[
  11953. \begin{array}{lcl}
  11954. \Exp &::=& \key{collect}(\itm{int})
  11955. \MID \key{allocate}(\itm{int},\itm{type})
  11956. \MID \key{global\_value}(\itm{name}) \\
  11957. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11958. \end{array}
  11959. \]
  11960. \fi}
  11961. %
  11962. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  11963. there be $n$ bytes ready to be allocated. During instruction
  11964. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  11965. form will become a call to the \code{collect} function in
  11966. \code{runtime.c}.
  11967. %
  11968. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11969. space at the front for the 64-bit tag), but the elements are not
  11970. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11971. of the tuple:
  11972. %
  11973. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11974. %
  11975. where $\Type_i$ is the type of the $i$th element.
  11976. %
  11977. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11978. variable, such as \code{free\_ptr}.
  11979. \racket{
  11980. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11981. can be obtained by running the
  11982. \code{type-check-Lvec-has-type} type checker immediately before the
  11983. \code{expose\_allocation} pass. This version of the type checker
  11984. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11985. around each tuple creation. The concrete syntax
  11986. for \code{HasType} is \code{has-type}.}
  11987. The following shows the transformation of tuple creation into (1) a
  11988. sequence of temporary variable bindings for the initializing
  11989. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11990. \code{allocate}, and (4) the initialization of the tuple. The
  11991. \itm{len} placeholder refers to the length of the tuple, and
  11992. \itm{bytes} is the total number of bytes that need to be allocated for
  11993. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11994. %
  11995. \python{The \itm{type} needed for the second argument of the
  11996. \code{allocate} form can be obtained from the \code{has\_type} field
  11997. of the tuple AST node, which is stored there by running the type
  11998. checker for \LangVec{} immediately before this pass.}
  11999. %
  12000. \begin{center}
  12001. \begin{minipage}{\textwidth}
  12002. {\if\edition\racketEd
  12003. \begin{lstlisting}
  12004. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12005. |$\Longrightarrow$|
  12006. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12007. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12008. (global-value fromspace_end))
  12009. (void)
  12010. (collect |\itm{bytes}|))])
  12011. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12012. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12013. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12014. |$v$|) ... )))) ...)
  12015. \end{lstlisting}
  12016. \fi}
  12017. {\if\edition\pythonEd\pythonColor
  12018. \begin{lstlisting}
  12019. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12020. |$\Longrightarrow$|
  12021. begin:
  12022. |$x_0$| = |$e_0$|
  12023. |$\vdots$|
  12024. |$x_{n-1}$| = |$e_{n-1}$|
  12025. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12026. 0
  12027. else:
  12028. collect(|\itm{bytes}|)
  12029. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12030. |$v$|[0] = |$x_0$|
  12031. |$\vdots$|
  12032. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12033. |$v$|
  12034. \end{lstlisting}
  12035. \fi}
  12036. \end{minipage}
  12037. \end{center}
  12038. %
  12039. \noindent The sequencing of the initializing expressions
  12040. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12041. they may trigger garbage collection and we cannot have an allocated
  12042. but uninitialized tuple on the heap during a collection.
  12043. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12044. \code{expose\_allocation} pass on our running example.
  12045. \begin{figure}[tbp]
  12046. \begin{tcolorbox}[colback=white]
  12047. % tests/s2_17.rkt
  12048. {\if\edition\racketEd
  12049. \begin{lstlisting}
  12050. (vector-ref
  12051. (vector-ref
  12052. (let ([vecinit6
  12053. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12054. (global-value fromspace_end))
  12055. (void)
  12056. (collect 16))])
  12057. (let ([alloc2 (allocate 1 (Vector Integer))])
  12058. (let ([_3 (vector-set! alloc2 0 42)])
  12059. alloc2)))])
  12060. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12061. (global-value fromspace_end))
  12062. (void)
  12063. (collect 16))])
  12064. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12065. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12066. alloc5))))
  12067. 0)
  12068. 0)
  12069. \end{lstlisting}
  12070. \fi}
  12071. {\if\edition\pythonEd\pythonColor
  12072. \begin{lstlisting}
  12073. v1 = begin:
  12074. init.514 = 42
  12075. if (free_ptr + 16) < fromspace_end:
  12076. else:
  12077. collect(16)
  12078. alloc.513 = allocate(1,tuple[int])
  12079. alloc.513[0] = init.514
  12080. alloc.513
  12081. v2 = begin:
  12082. init.516 = v1
  12083. if (free_ptr + 16) < fromspace_end:
  12084. else:
  12085. collect(16)
  12086. alloc.515 = allocate(1,tuple[tuple[int]])
  12087. alloc.515[0] = init.516
  12088. alloc.515
  12089. print(v2[0][0])
  12090. \end{lstlisting}
  12091. \fi}
  12092. \end{tcolorbox}
  12093. \caption{Output of the \code{expose\_allocation} pass.}
  12094. \label{fig:expose-alloc-output}
  12095. \end{figure}
  12096. \section{Remove Complex Operands}
  12097. \label{sec:remove-complex-opera-Lvec}
  12098. {\if\edition\racketEd
  12099. %
  12100. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12101. should be treated as complex operands.
  12102. %
  12103. \fi}
  12104. %
  12105. {\if\edition\pythonEd\pythonColor
  12106. %
  12107. The expressions \code{allocate}, \code{begin},
  12108. and tuple access should be treated as complex operands. The
  12109. subexpressions of tuple access must be atomic.
  12110. The \code{global\_value} AST node is atomic.
  12111. %
  12112. \fi}
  12113. %% A new case for
  12114. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12115. %% handled carefully to prevent the \code{Prim} node from being separated
  12116. %% from its enclosing \code{HasType}.
  12117. Figure~\ref{fig:Lvec-anf-syntax}
  12118. shows the grammar for the output language \LangAllocANF{} of this
  12119. pass, which is \LangAlloc{} in monadic normal form.
  12120. \newcommand{\LtupMonadASTRacket}{
  12121. \begin{array}{rcl}
  12122. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12123. \MID \GLOBALVALUE{\Var}
  12124. \end{array}
  12125. }
  12126. \newcommand{\LtupMonadASTPython}{
  12127. \begin{array}{rcl}
  12128. \Atm &::=& \GLOBALVALUE{\Var} \\
  12129. \Exp &::=& \GET{\Atm}{\Atm}
  12130. \MID \LEN{\Atm}\\
  12131. &\MID& \ALLOCATE{\Int}{\Type}\\
  12132. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12133. &\MID& \COLLECT{\Int}
  12134. \end{array}
  12135. }
  12136. \begin{figure}[tp]
  12137. \centering
  12138. \begin{tcolorbox}[colback=white]
  12139. \small
  12140. {\if\edition\racketEd
  12141. \[
  12142. \begin{array}{l}
  12143. \gray{\LvarMonadASTRacket} \\ \hline
  12144. \gray{\LifMonadASTRacket} \\ \hline
  12145. \gray{\LwhileMonadASTRacket} \\ \hline
  12146. \LtupMonadASTRacket \\
  12147. \begin{array}{rcl}
  12148. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12149. \end{array}
  12150. \end{array}
  12151. \]
  12152. \fi}
  12153. {\if\edition\pythonEd\pythonColor
  12154. \[
  12155. \begin{array}{l}
  12156. \gray{\LvarMonadASTPython} \\ \hline
  12157. \gray{\LifMonadASTPython} \\ \hline
  12158. \gray{\LwhileMonadASTPython} \\ \hline
  12159. \LtupMonadASTPython \\
  12160. \begin{array}{rcl}
  12161. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12162. \end{array}
  12163. \end{array}
  12164. \]
  12165. \fi}
  12166. \end{tcolorbox}
  12167. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12168. \label{fig:Lvec-anf-syntax}
  12169. \end{figure}
  12170. \section{Explicate Control and the \LangCVec{} Language}
  12171. \label{sec:explicate-control-r3}
  12172. \newcommand{\CtupASTRacket}{
  12173. \begin{array}{lcl}
  12174. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12175. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12176. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12177. &\MID& \VECLEN{\Atm} \\
  12178. &\MID& \GLOBALVALUE{\Var} \\
  12179. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12180. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12181. \end{array}
  12182. }
  12183. \newcommand{\CtupASTPython}{
  12184. \begin{array}{lcl}
  12185. \Atm &::=& \GLOBALVALUE{\Var} \\
  12186. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12187. &\MID& \LEN{\Atm} \\
  12188. \Stmt &::=& \COLLECT{\Int}
  12189. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12190. \end{array}
  12191. }
  12192. \begin{figure}[tp]
  12193. \begin{tcolorbox}[colback=white]
  12194. \small
  12195. {\if\edition\racketEd
  12196. \[
  12197. \begin{array}{l}
  12198. \gray{\CvarASTRacket} \\ \hline
  12199. \gray{\CifASTRacket} \\ \hline
  12200. \gray{\CloopASTRacket} \\ \hline
  12201. \CtupASTRacket \\
  12202. \begin{array}{lcl}
  12203. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12204. \end{array}
  12205. \end{array}
  12206. \]
  12207. \fi}
  12208. {\if\edition\pythonEd\pythonColor
  12209. \[
  12210. \begin{array}{l}
  12211. \gray{\CifASTPython} \\ \hline
  12212. \CtupASTPython \\
  12213. \begin{array}{lcl}
  12214. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12215. \end{array}
  12216. \end{array}
  12217. \]
  12218. \fi}
  12219. \end{tcolorbox}
  12220. \caption{The abstract syntax of \LangCVec{}, extending
  12221. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12222. (figure~\ref{fig:c1-syntax})}.}
  12223. \label{fig:c2-syntax}
  12224. \end{figure}
  12225. The output of \code{explicate\_control} is a program in the
  12226. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12227. shows the definition of the abstract syntax.
  12228. %
  12229. %% \racket{(The concrete syntax is defined in
  12230. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12231. %
  12232. The new expressions of \LangCVec{} include \key{allocate},
  12233. %
  12234. \racket{\key{vector-ref}, and \key{vector-set!},}
  12235. %
  12236. \python{accessing tuple elements,}
  12237. %
  12238. and \key{global\_value}.
  12239. %
  12240. \python{\LangCVec{} also includes the \code{collect} statement and
  12241. assignment to a tuple element.}
  12242. %
  12243. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12244. %
  12245. The \code{explicate\_control} pass can treat these new forms much like
  12246. the other forms that we've already encountered. The output of the
  12247. \code{explicate\_control} pass on the running example is shown on the
  12248. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12249. section.
  12250. \section{Select Instructions and the \LangXGlobal{} Language}
  12251. \label{sec:select-instructions-gc}
  12252. \index{subject}{select instructions}
  12253. %% void (rep as zero)
  12254. %% allocate
  12255. %% collect (callq collect)
  12256. %% vector-ref
  12257. %% vector-set!
  12258. %% vector-length
  12259. %% global (postpone)
  12260. In this pass we generate x86 code for most of the new operations that
  12261. are needed to compile tuples, including \code{Allocate},
  12262. \code{Collect}, accessing tuple elements, and the \code{Is}
  12263. comparison.
  12264. %
  12265. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12266. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12267. \ref{fig:x86-2}). \index{subject}{x86}
  12268. The tuple read and write forms translate into \code{movq}
  12269. instructions. (The $+1$ in the offset serves to move past the tag at the
  12270. beginning of the tuple representation.)
  12271. %
  12272. \begin{center}
  12273. \begin{minipage}{\textwidth}
  12274. {\if\edition\racketEd
  12275. \begin{lstlisting}
  12276. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12277. |$\Longrightarrow$|
  12278. movq |$\itm{tup}'$|, %r11
  12279. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12280. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12281. |$\Longrightarrow$|
  12282. movq |$\itm{tup}'$|, %r11
  12283. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12284. movq $0, |$\itm{lhs'}$|
  12285. \end{lstlisting}
  12286. \fi}
  12287. {\if\edition\pythonEd\pythonColor
  12288. \begin{lstlisting}
  12289. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12290. |$\Longrightarrow$|
  12291. movq |$\itm{tup}'$|, %r11
  12292. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12293. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12294. |$\Longrightarrow$|
  12295. movq |$\itm{tup}'$|, %r11
  12296. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12297. \end{lstlisting}
  12298. \fi}
  12299. \end{minipage}
  12300. \end{center}
  12301. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12302. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12303. are obtained by translating from \LangCVec{} to x86.
  12304. %
  12305. The move of $\itm{tup}'$ to
  12306. register \code{r11} ensures that the offset expression
  12307. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12308. removing \code{r11} from consideration by the register allocator.
  12309. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12310. \code{rax}. Then the generated code for tuple assignment would be
  12311. \begin{lstlisting}
  12312. movq |$\itm{tup}'$|, %rax
  12313. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12314. \end{lstlisting}
  12315. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12316. \code{patch\_instructions} would insert a move through \code{rax}
  12317. as follows:
  12318. \begin{lstlisting}
  12319. movq |$\itm{tup}'$|, %rax
  12320. movq |$\itm{rhs}'$|, %rax
  12321. movq %rax, |$8(n+1)$|(%rax)
  12322. \end{lstlisting}
  12323. However, this sequence of instructions does not work because we're
  12324. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12325. $\itm{rhs}'$) at the same time!
  12326. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12327. be translated into a sequence of instructions that read the tag of the
  12328. tuple and extract the 6 bits that represent the tuple length, which
  12329. are the bits starting at index 1 and going up to and including bit 6.
  12330. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12331. (shift right) can be used to accomplish this.
  12332. We compile the \code{allocate} form to operations on the
  12333. \code{free\_ptr}, as shown next. This approach is called
  12334. \emph{inline allocation} because it implements allocation without a
  12335. function call by simply incrementing the allocation pointer. It is much
  12336. more efficient than calling a function for each allocation. The
  12337. address in the \code{free\_ptr} is the next free address in the
  12338. FromSpace, so we copy it into \code{r11} and then move it forward by
  12339. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12340. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12341. the tag. We then initialize the \itm{tag} and finally copy the
  12342. address in \code{r11} to the left-hand side. Refer to
  12343. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12344. %
  12345. \racket{We recommend using the Racket operations
  12346. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12347. during compilation.}
  12348. %
  12349. \python{We recommend using the bitwise-or operator \code{|} and the
  12350. shift-left operator \code{<<} to compute the tag during
  12351. compilation.}
  12352. %
  12353. The type annotation in the \code{allocate} form is used to determine
  12354. the pointer mask region of the tag.
  12355. %
  12356. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12357. address of the \code{free\_ptr} global variable using a special
  12358. instruction-pointer-relative addressing mode of the x86-64 processor.
  12359. In particular, the assembler computes the distance $d$ between the
  12360. address of \code{free\_ptr} and where the \code{rip} would be at that
  12361. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12362. \code{$d$(\%rip)}, which at runtime will compute the address of
  12363. \code{free\_ptr}.
  12364. %
  12365. {\if\edition\racketEd
  12366. \begin{lstlisting}
  12367. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12368. |$\Longrightarrow$|
  12369. movq free_ptr(%rip), %r11
  12370. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12371. movq $|$\itm{tag}$|, 0(%r11)
  12372. movq %r11, |$\itm{lhs}'$|
  12373. \end{lstlisting}
  12374. \fi}
  12375. {\if\edition\pythonEd\pythonColor
  12376. \begin{lstlisting}
  12377. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12378. |$\Longrightarrow$|
  12379. movq free_ptr(%rip), %r11
  12380. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12381. movq $|$\itm{tag}$|, 0(%r11)
  12382. movq %r11, |$\itm{lhs}'$|
  12383. \end{lstlisting}
  12384. \fi}
  12385. %
  12386. The \code{collect} form is compiled to a call to the \code{collect}
  12387. function in the runtime. The arguments to \code{collect} are (1) the
  12388. top of the root stack, and (2) the number of bytes that need to be
  12389. allocated. We use another dedicated register, \code{r15}, to store
  12390. the pointer to the top of the root stack. Therefore \code{r15} is not
  12391. available for use by the register allocator.
  12392. %
  12393. {\if\edition\racketEd
  12394. \begin{lstlisting}
  12395. (collect |$\itm{bytes}$|)
  12396. |$\Longrightarrow$|
  12397. movq %r15, %rdi
  12398. movq $|\itm{bytes}|, %rsi
  12399. callq collect
  12400. \end{lstlisting}
  12401. \fi}
  12402. {\if\edition\pythonEd\pythonColor
  12403. \begin{lstlisting}
  12404. collect(|$\itm{bytes}$|)
  12405. |$\Longrightarrow$|
  12406. movq %r15, %rdi
  12407. movq $|\itm{bytes}|, %rsi
  12408. callq collect
  12409. \end{lstlisting}
  12410. \fi}
  12411. {\if\edition\pythonEd\pythonColor
  12412. The \code{is} comparison is compiled similarly to the other comparison
  12413. operators, using the \code{cmpq} instruction. Because the value of a
  12414. tuple is its address, we can translate \code{is} into a simple check
  12415. for equality using the \code{e} condition code. \\
  12416. \begin{tabular}{lll}
  12417. \begin{minipage}{0.4\textwidth}
  12418. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12419. \end{minipage}
  12420. &
  12421. $\Rightarrow$
  12422. &
  12423. \begin{minipage}{0.4\textwidth}
  12424. \begin{lstlisting}
  12425. cmpq |$\Arg_2$|, |$\Arg_1$|
  12426. sete %al
  12427. movzbq %al, |$\Var$|
  12428. \end{lstlisting}
  12429. \end{minipage}
  12430. \end{tabular}
  12431. \fi}
  12432. \newcommand{\GrammarXGlobal}{
  12433. \begin{array}{lcl}
  12434. \Arg &::=& \itm{label} \key{(\%rip)}
  12435. \end{array}
  12436. }
  12437. \newcommand{\ASTXGlobalRacket}{
  12438. \begin{array}{lcl}
  12439. \Arg &::=& \GLOBAL{\itm{label}}
  12440. \end{array}
  12441. }
  12442. \begin{figure}[tp]
  12443. \begin{tcolorbox}[colback=white]
  12444. \[
  12445. \begin{array}{l}
  12446. \gray{\GrammarXInt} \\ \hline
  12447. \gray{\GrammarXIf} \\ \hline
  12448. \GrammarXGlobal \\
  12449. \begin{array}{lcl}
  12450. \LangXGlobalM{} &::= & \key{.globl main} \\
  12451. & & \key{main:} \; \Instr^{*}
  12452. \end{array}
  12453. \end{array}
  12454. \]
  12455. \end{tcolorbox}
  12456. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12457. \label{fig:x86-2-concrete}
  12458. \end{figure}
  12459. \begin{figure}[tp]
  12460. \begin{tcolorbox}[colback=white]
  12461. \small
  12462. {\if\edition\racketEd
  12463. \[
  12464. \begin{array}{l}
  12465. \gray{\ASTXIntRacket} \\ \hline
  12466. \gray{\ASTXIfRacket} \\ \hline
  12467. \ASTXGlobalRacket \\
  12468. \begin{array}{lcl}
  12469. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12470. \end{array}
  12471. \end{array}
  12472. \]
  12473. \fi}
  12474. {\if\edition\pythonEd\pythonColor
  12475. \[
  12476. \begin{array}{l}
  12477. \gray{\ASTXIntPython} \\ \hline
  12478. \gray{\ASTXIfPython} \\ \hline
  12479. \ASTXGlobalRacket \\
  12480. \begin{array}{lcl}
  12481. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12482. \end{array}
  12483. \end{array}
  12484. \]
  12485. \fi}
  12486. \end{tcolorbox}
  12487. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12488. \label{fig:x86-2}
  12489. \end{figure}
  12490. The definitions of the concrete and abstract syntax of the
  12491. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12492. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12493. of global variables.
  12494. %
  12495. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12496. \code{select\_instructions} pass on the running example.
  12497. \begin{figure}[tbp]
  12498. \centering
  12499. \begin{tcolorbox}[colback=white]
  12500. {\if\edition\racketEd
  12501. % tests/s2_17.rkt
  12502. \begin{tabular}{lll}
  12503. \begin{minipage}{0.5\textwidth}
  12504. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12505. start:
  12506. tmp9 = (global-value free_ptr);
  12507. tmp0 = (+ tmp9 16);
  12508. tmp1 = (global-value fromspace_end);
  12509. if (< tmp0 tmp1)
  12510. goto block0;
  12511. else
  12512. goto block1;
  12513. block0:
  12514. _4 = (void);
  12515. goto block9;
  12516. block1:
  12517. (collect 16)
  12518. goto block9;
  12519. block9:
  12520. alloc2 = (allocate 1 (Vector Integer));
  12521. _3 = (vector-set! alloc2 0 42);
  12522. vecinit6 = alloc2;
  12523. tmp2 = (global-value free_ptr);
  12524. tmp3 = (+ tmp2 16);
  12525. tmp4 = (global-value fromspace_end);
  12526. if (< tmp3 tmp4)
  12527. goto block7;
  12528. else
  12529. goto block8;
  12530. block7:
  12531. _8 = (void);
  12532. goto block6;
  12533. block8:
  12534. (collect 16)
  12535. goto block6;
  12536. block6:
  12537. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12538. _7 = (vector-set! alloc5 0 vecinit6);
  12539. tmp5 = (vector-ref alloc5 0);
  12540. return (vector-ref tmp5 0);
  12541. \end{lstlisting}
  12542. \end{minipage}
  12543. &$\Rightarrow$&
  12544. \begin{minipage}{0.4\textwidth}
  12545. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12546. start:
  12547. movq free_ptr(%rip), tmp9
  12548. movq tmp9, tmp0
  12549. addq $16, tmp0
  12550. movq fromspace_end(%rip), tmp1
  12551. cmpq tmp1, tmp0
  12552. jl block0
  12553. jmp block1
  12554. block0:
  12555. movq $0, _4
  12556. jmp block9
  12557. block1:
  12558. movq %r15, %rdi
  12559. movq $16, %rsi
  12560. callq collect
  12561. jmp block9
  12562. block9:
  12563. movq free_ptr(%rip), %r11
  12564. addq $16, free_ptr(%rip)
  12565. movq $3, 0(%r11)
  12566. movq %r11, alloc2
  12567. movq alloc2, %r11
  12568. movq $42, 8(%r11)
  12569. movq $0, _3
  12570. movq alloc2, vecinit6
  12571. movq free_ptr(%rip), tmp2
  12572. movq tmp2, tmp3
  12573. addq $16, tmp3
  12574. movq fromspace_end(%rip), tmp4
  12575. cmpq tmp4, tmp3
  12576. jl block7
  12577. jmp block8
  12578. block7:
  12579. movq $0, _8
  12580. jmp block6
  12581. block8:
  12582. movq %r15, %rdi
  12583. movq $16, %rsi
  12584. callq collect
  12585. jmp block6
  12586. block6:
  12587. movq free_ptr(%rip), %r11
  12588. addq $16, free_ptr(%rip)
  12589. movq $131, 0(%r11)
  12590. movq %r11, alloc5
  12591. movq alloc5, %r11
  12592. movq vecinit6, 8(%r11)
  12593. movq $0, _7
  12594. movq alloc5, %r11
  12595. movq 8(%r11), tmp5
  12596. movq tmp5, %r11
  12597. movq 8(%r11), %rax
  12598. jmp conclusion
  12599. \end{lstlisting}
  12600. \end{minipage}
  12601. \end{tabular}
  12602. \fi}
  12603. {\if\edition\pythonEd
  12604. % tests/tuple/get_get.py
  12605. \begin{tabular}{lll}
  12606. \begin{minipage}{0.5\textwidth}
  12607. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12608. start:
  12609. init.514 = 42
  12610. tmp.517 = free_ptr
  12611. tmp.518 = (tmp.517 + 16)
  12612. tmp.519 = fromspace_end
  12613. if tmp.518 < tmp.519:
  12614. goto block.529
  12615. else:
  12616. goto block.530
  12617. block.529:
  12618. goto block.528
  12619. block.530:
  12620. collect(16)
  12621. goto block.528
  12622. block.528:
  12623. alloc.513 = allocate(1,tuple[int])
  12624. alloc.513:tuple[int][0] = init.514
  12625. v1 = alloc.513
  12626. init.516 = v1
  12627. tmp.520 = free_ptr
  12628. tmp.521 = (tmp.520 + 16)
  12629. tmp.522 = fromspace_end
  12630. if tmp.521 < tmp.522:
  12631. goto block.526
  12632. else:
  12633. goto block.527
  12634. block.526:
  12635. goto block.525
  12636. block.527:
  12637. collect(16)
  12638. goto block.525
  12639. block.525:
  12640. alloc.515 = allocate(1,tuple[tuple[int]])
  12641. alloc.515:tuple[tuple[int]][0] = init.516
  12642. v2 = alloc.515
  12643. tmp.523 = v2[0]
  12644. tmp.524 = tmp.523[0]
  12645. print(tmp.524)
  12646. return 0
  12647. \end{lstlisting}
  12648. \end{minipage}
  12649. &$\Rightarrow$&
  12650. \begin{minipage}{0.4\textwidth}
  12651. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12652. start:
  12653. movq $42, init.514
  12654. movq free_ptr(%rip), tmp.517
  12655. movq tmp.517, tmp.518
  12656. addq $16, tmp.518
  12657. movq fromspace_end(%rip), tmp.519
  12658. cmpq tmp.519, tmp.518
  12659. jl block.529
  12660. jmp block.530
  12661. block.529:
  12662. jmp block.528
  12663. block.530:
  12664. movq %r15, %rdi
  12665. movq $16, %rsi
  12666. callq collect
  12667. jmp block.528
  12668. block.528:
  12669. movq free_ptr(%rip), %r11
  12670. addq $16, free_ptr(%rip)
  12671. movq $3, 0(%r11)
  12672. movq %r11, alloc.513
  12673. movq alloc.513, %r11
  12674. movq init.514, 8(%r11)
  12675. movq alloc.513, v1
  12676. movq v1, init.516
  12677. movq free_ptr(%rip), tmp.520
  12678. movq tmp.520, tmp.521
  12679. addq $16, tmp.521
  12680. movq fromspace_end(%rip), tmp.522
  12681. cmpq tmp.522, tmp.521
  12682. jl block.526
  12683. jmp block.527
  12684. block.526:
  12685. jmp block.525
  12686. block.527:
  12687. movq %r15, %rdi
  12688. movq $16, %rsi
  12689. callq collect
  12690. jmp block.525
  12691. block.525:
  12692. movq free_ptr(%rip), %r11
  12693. addq $16, free_ptr(%rip)
  12694. movq $131, 0(%r11)
  12695. movq %r11, alloc.515
  12696. movq alloc.515, %r11
  12697. movq init.516, 8(%r11)
  12698. movq alloc.515, v2
  12699. movq v2, %r11
  12700. movq 8(%r11), %r11
  12701. movq %r11, tmp.523
  12702. movq tmp.523, %r11
  12703. movq 8(%r11), %r11
  12704. movq %r11, tmp.524
  12705. movq tmp.524, %rdi
  12706. callq print_int
  12707. movq $0, %rax
  12708. jmp conclusion
  12709. \end{lstlisting}
  12710. \end{minipage}
  12711. \end{tabular}
  12712. \fi}
  12713. \end{tcolorbox}
  12714. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12715. \code{select\_instructions} (\emph{right}) on the running example.}
  12716. \label{fig:select-instr-output-gc}
  12717. \end{figure}
  12718. \clearpage
  12719. \section{Register Allocation}
  12720. \label{sec:reg-alloc-gc}
  12721. \index{subject}{register allocation}
  12722. As discussed previously in this chapter, the garbage collector needs to
  12723. access all the pointers in the root set, that is, all variables that
  12724. are tuples. It will be the responsibility of the register allocator
  12725. to make sure that
  12726. \begin{enumerate}
  12727. \item the root stack is used for spilling tuple-typed variables, and
  12728. \item if a tuple-typed variable is live during a call to the
  12729. collector, it must be spilled to ensure that it is visible to the
  12730. collector.
  12731. \end{enumerate}
  12732. The latter responsibility can be handled during construction of the
  12733. interference graph, by adding interference edges between the call-live
  12734. tuple-typed variables and all the callee-saved registers. (They
  12735. already interfere with the caller-saved registers.)
  12736. %
  12737. \racket{The type information for variables is in the \code{Program}
  12738. form, so we recommend adding another parameter to the
  12739. \code{build\_interference} function to communicate this alist.}
  12740. %
  12741. \python{The type information for variables is generated by the type
  12742. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12743. the \code{CProgram} AST mode. You'll need to propagate that
  12744. information so that it is available in this pass.}
  12745. The spilling of tuple-typed variables to the root stack can be handled
  12746. after graph coloring, in choosing how to assign the colors
  12747. (integers) to registers and stack locations. The
  12748. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12749. changes to also record the number of spills to the root stack.
  12750. % build-interference
  12751. %
  12752. % callq
  12753. % extra parameter for var->type assoc. list
  12754. % update 'program' and 'if'
  12755. % allocate-registers
  12756. % allocate spilled vectors to the rootstack
  12757. % don't change color-graph
  12758. % TODO:
  12759. %\section{Patch Instructions}
  12760. %[mention that global variables are memory references]
  12761. \section{Generate Prelude and Conclusion}
  12762. \label{sec:print-x86-gc}
  12763. \label{sec:prelude-conclusion-x86-gc}
  12764. \index{subject}{prelude}\index{subject}{conclusion}
  12765. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12766. \code{prelude\_and\_conclusion} pass on the running example. In the
  12767. prelude of the \code{main} function, we allocate space
  12768. on the root stack to make room for the spills of tuple-typed
  12769. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12770. taking care that the root stack grows up instead of down. For the
  12771. running example, there was just one spill, so we increment \code{r15}
  12772. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12773. One issue that deserves special care is that there may be a call to
  12774. \code{collect} prior to the initializing assignments for all the
  12775. variables in the root stack. We do not want the garbage collector to
  12776. mistakenly determine that some uninitialized variable is a pointer that
  12777. needs to be followed. Thus, we zero out all locations on the root
  12778. stack in the prelude of \code{main}. In
  12779. figure~\ref{fig:print-x86-output-gc}, the instruction
  12780. %
  12781. \lstinline{movq $0, 0(%r15)}
  12782. %
  12783. is sufficient to accomplish this task because there is only one spill.
  12784. In general, we have to clear as many words as there are spills of
  12785. tuple-typed variables. The garbage collector tests each root to see
  12786. if it is null prior to dereferencing it.
  12787. \begin{figure}[htbp]
  12788. \begin{tcolorbox}[colback=white]
  12789. {\if\edition\racketEd
  12790. \begin{minipage}[t]{0.5\textwidth}
  12791. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12792. .globl main
  12793. main:
  12794. pushq %rbp
  12795. movq %rsp, %rbp
  12796. subq $0, %rsp
  12797. movq $65536, %rdi
  12798. movq $65536, %rsi
  12799. callq initialize
  12800. movq rootstack_begin(%rip), %r15
  12801. movq $0, 0(%r15)
  12802. addq $8, %r15
  12803. jmp start
  12804. conclusion:
  12805. subq $8, %r15
  12806. addq $0, %rsp
  12807. popq %rbp
  12808. retq
  12809. \end{lstlisting}
  12810. \end{minipage}
  12811. \fi}
  12812. {\if\edition\pythonEd
  12813. \begin{minipage}[t]{0.5\textwidth}
  12814. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12815. .globl main
  12816. main:
  12817. pushq %rbp
  12818. movq %rsp, %rbp
  12819. pushq %rbx
  12820. subq $8, %rsp
  12821. movq $65536, %rdi
  12822. movq $16, %rsi
  12823. callq initialize
  12824. movq rootstack_begin(%rip), %r15
  12825. movq $0, 0(%r15)
  12826. addq $8, %r15
  12827. jmp start
  12828. conclusion:
  12829. subq $8, %r15
  12830. addq $8, %rsp
  12831. popq %rbx
  12832. popq %rbp
  12833. retq
  12834. \end{lstlisting}
  12835. \end{minipage}
  12836. \fi}
  12837. \end{tcolorbox}
  12838. \caption{The prelude and conclusion for the running example.}
  12839. \label{fig:print-x86-output-gc}
  12840. \end{figure}
  12841. \begin{figure}[tbp]
  12842. \begin{tcolorbox}[colback=white]
  12843. {\if\edition\racketEd
  12844. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12845. \node (Lvec) at (0,2) {\large \LangVec{}};
  12846. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12847. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12848. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12849. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12850. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12851. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12852. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12853. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12854. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12855. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12856. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12857. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12858. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12859. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12860. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12861. \path[->,bend left=15] (Lvec-4) edge [right] node
  12862. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12863. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12864. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12865. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12866. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12867. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12868. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12869. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12870. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12871. \end{tikzpicture}
  12872. \fi}
  12873. {\if\edition\pythonEd\pythonColor
  12874. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12875. \node (Lvec) at (0,2) {\large \LangVec{}};
  12876. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12877. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12878. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12879. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12880. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12881. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12882. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12883. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12884. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12885. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12886. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12887. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12888. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12889. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12890. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12891. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12892. \end{tikzpicture}
  12893. \fi}
  12894. \end{tcolorbox}
  12895. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12896. \label{fig:Lvec-passes}
  12897. \end{figure}
  12898. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12899. for the compilation of \LangVec{}.
  12900. \clearpage
  12901. {\if\edition\racketEd
  12902. \section{Challenge: Simple Structures}
  12903. \label{sec:simple-structures}
  12904. \index{subject}{struct}
  12905. \index{subject}{structure}
  12906. The language \LangStruct{} extends \LangVec{} with support for simple
  12907. structures. The definition of its concrete syntax is shown in
  12908. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12909. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12910. in Typed Racket is a user-defined data type that contains named fields
  12911. and that is heap allocated\index{subject}{heap allocated},
  12912. similarly to a vector. The following is an
  12913. example of a structure definition, in this case the definition of a
  12914. \code{point} type:
  12915. \begin{lstlisting}
  12916. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12917. \end{lstlisting}
  12918. \newcommand{\LstructGrammarRacket}{
  12919. \begin{array}{lcl}
  12920. \Type &::=& \Var \\
  12921. \Exp &::=& (\Var\;\Exp \ldots)\\
  12922. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12923. \end{array}
  12924. }
  12925. \newcommand{\LstructASTRacket}{
  12926. \begin{array}{lcl}
  12927. \Type &::=& \VAR{\Var} \\
  12928. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12929. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12930. \end{array}
  12931. }
  12932. \begin{figure}[tbp]
  12933. \centering
  12934. \begin{tcolorbox}[colback=white]
  12935. \[
  12936. \begin{array}{l}
  12937. \gray{\LintGrammarRacket{}} \\ \hline
  12938. \gray{\LvarGrammarRacket{}} \\ \hline
  12939. \gray{\LifGrammarRacket{}} \\ \hline
  12940. \gray{\LwhileGrammarRacket} \\ \hline
  12941. \gray{\LtupGrammarRacket} \\ \hline
  12942. \LstructGrammarRacket \\
  12943. \begin{array}{lcl}
  12944. \LangStruct{} &::=& \Def \ldots \; \Exp
  12945. \end{array}
  12946. \end{array}
  12947. \]
  12948. \end{tcolorbox}
  12949. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12950. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12951. \label{fig:Lstruct-concrete-syntax}
  12952. \end{figure}
  12953. \begin{figure}[tbp]
  12954. \centering
  12955. \begin{tcolorbox}[colback=white]
  12956. \small
  12957. \[
  12958. \begin{array}{l}
  12959. \gray{\LintASTRacket{}} \\ \hline
  12960. \gray{\LvarASTRacket{}} \\ \hline
  12961. \gray{\LifASTRacket{}} \\ \hline
  12962. \gray{\LwhileASTRacket} \\ \hline
  12963. \gray{\LtupASTRacket} \\ \hline
  12964. \LstructASTRacket \\
  12965. \begin{array}{lcl}
  12966. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12967. \end{array}
  12968. \end{array}
  12969. \]
  12970. \end{tcolorbox}
  12971. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12972. (figure~\ref{fig:Lvec-syntax}).}
  12973. \label{fig:Lstruct-syntax}
  12974. \end{figure}
  12975. An instance of a structure is created using function-call syntax, with
  12976. the name of the structure in the function position, as follows:
  12977. \begin{lstlisting}
  12978. (point 7 12)
  12979. \end{lstlisting}
  12980. Function-call syntax is also used to read a field of a structure. The
  12981. function name is formed by the structure name, a dash, and the field
  12982. name. The following example uses \code{point-x} and \code{point-y} to
  12983. access the \code{x} and \code{y} fields of two point instances:
  12984. \begin{center}
  12985. \begin{lstlisting}
  12986. (let ([pt1 (point 7 12)])
  12987. (let ([pt2 (point 4 3)])
  12988. (+ (- (point-x pt1) (point-x pt2))
  12989. (- (point-y pt1) (point-y pt2)))))
  12990. \end{lstlisting}
  12991. \end{center}
  12992. Similarly, to write to a field of a structure, use its set function,
  12993. whose name starts with \code{set-}, followed by the structure name,
  12994. then a dash, then the field name, and finally with an exclamation
  12995. mark. The following example uses \code{set-point-x!} to change the
  12996. \code{x} field from \code{7} to \code{42}:
  12997. \begin{center}
  12998. \begin{lstlisting}
  12999. (let ([pt (point 7 12)])
  13000. (let ([_ (set-point-x! pt 42)])
  13001. (point-x pt)))
  13002. \end{lstlisting}
  13003. \end{center}
  13004. \begin{exercise}\normalfont\normalsize
  13005. Create a type checker for \LangStruct{} by extending the type
  13006. checker for \LangVec{}. Extend your compiler with support for simple
  13007. structures, compiling \LangStruct{} to x86 assembly code. Create
  13008. five new test cases that use structures, and test your compiler.
  13009. \end{exercise}
  13010. % TODO: create an interpreter for L_struct
  13011. \clearpage
  13012. \fi}
  13013. \section{Challenge: Arrays}
  13014. \label{sec:arrays}
  13015. % TODO mention trapped-error
  13016. In this chapter we have studied tuples, that is, heterogeneous
  13017. sequences of elements whose length is determined at compile time. This
  13018. challenge is also about sequences, but this time the length is
  13019. determined at runtime and all the elements have the same type (they
  13020. are homogeneous). We use the traditional term \emph{array} for this
  13021. latter kind of sequence.
  13022. %
  13023. \racket{
  13024. The Racket language does not distinguish between tuples and arrays;
  13025. they are both represented by vectors. However, Typed Racket
  13026. distinguishes between tuples and arrays: the \code{Vector} type is for
  13027. tuples, and the \code{Vectorof} type is for arrays.}%
  13028. \python{Arrays correspond to the \code{list} type in the Python language.}
  13029. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13030. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13031. presents the definition of the abstract syntax, extending \LangVec{}
  13032. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13033. \racket{\code{make-vector} primitive operator for creating an array,
  13034. whose arguments are the length of the array and an initial value for
  13035. all the elements in the array.}%
  13036. \python{bracket notation for creating an array literal.}
  13037. \racket{The \code{vector-length},
  13038. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13039. for tuples become overloaded for use with arrays.}
  13040. \python{
  13041. The subscript operator becomes overloaded for use with arrays and tuples
  13042. and now may appear on the left-hand side of an assignment.
  13043. Note that the index of the subscript, when applied to an array, may be an
  13044. arbitrary expression and not exclusively a constant integer.
  13045. The \code{len} function is also applicable to arrays.
  13046. }
  13047. %
  13048. We include integer multiplication in \LangArray{} because it is
  13049. useful in many examples involving arrays such as computing the
  13050. inner product of two arrays (figure~\ref{fig:inner_product}).
  13051. \newcommand{\LarrayGrammarRacket}{
  13052. \begin{array}{lcl}
  13053. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13054. \Exp &::=& \CMUL{\Exp}{\Exp}
  13055. \MID \CMAKEVEC{\Exp}{\Exp}
  13056. \end{array}
  13057. }
  13058. \newcommand{\LarrayASTRacket}{
  13059. \begin{array}{lcl}
  13060. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13061. \Exp &::=& \MUL{\Exp}{\Exp}
  13062. \MID \MAKEVEC{\Exp}{\Exp}
  13063. \end{array}
  13064. }
  13065. \newcommand{\LarrayGrammarPython}{
  13066. \begin{array}{lcl}
  13067. \Type &::=& \key{list}\LS\Type\RS \\
  13068. \Exp &::=& \CMUL{\Exp}{\Exp}
  13069. \MID \CGET{\Exp}{\Exp}
  13070. \MID \LS \Exp \code{,} \ldots \RS \\
  13071. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13072. \end{array}
  13073. }
  13074. \newcommand{\LarrayASTPython}{
  13075. \begin{array}{lcl}
  13076. \Type &::=& \key{ListType}\LP\Type\RP \\
  13077. \Exp &::=& \MUL{\Exp}{\Exp}
  13078. \MID \GET{\Exp}{\Exp} \\
  13079. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13080. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13081. \end{array}
  13082. }
  13083. \begin{figure}[tp]
  13084. \centering
  13085. \begin{tcolorbox}[colback=white]
  13086. \small
  13087. {\if\edition\racketEd
  13088. \[
  13089. \begin{array}{l}
  13090. \gray{\LintGrammarRacket{}} \\ \hline
  13091. \gray{\LvarGrammarRacket{}} \\ \hline
  13092. \gray{\LifGrammarRacket{}} \\ \hline
  13093. \gray{\LwhileGrammarRacket} \\ \hline
  13094. \gray{\LtupGrammarRacket} \\ \hline
  13095. \LarrayGrammarRacket \\
  13096. \begin{array}{lcl}
  13097. \LangArray{} &::=& \Exp
  13098. \end{array}
  13099. \end{array}
  13100. \]
  13101. \fi}
  13102. {\if\edition\pythonEd\pythonColor
  13103. \[
  13104. \begin{array}{l}
  13105. \gray{\LintGrammarPython{}} \\ \hline
  13106. \gray{\LvarGrammarPython{}} \\ \hline
  13107. \gray{\LifGrammarPython{}} \\ \hline
  13108. \gray{\LwhileGrammarPython} \\ \hline
  13109. \gray{\LtupGrammarPython} \\ \hline
  13110. \LarrayGrammarPython \\
  13111. \begin{array}{rcl}
  13112. \LangArrayM{} &::=& \Stmt^{*}
  13113. \end{array}
  13114. \end{array}
  13115. \]
  13116. \fi}
  13117. \end{tcolorbox}
  13118. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13119. \label{fig:Lvecof-concrete-syntax}
  13120. \end{figure}
  13121. \begin{figure}[tp]
  13122. \centering
  13123. \begin{tcolorbox}[colback=white]
  13124. \small
  13125. {\if\edition\racketEd
  13126. \[
  13127. \begin{array}{l}
  13128. \gray{\LintASTRacket{}} \\ \hline
  13129. \gray{\LvarASTRacket{}} \\ \hline
  13130. \gray{\LifASTRacket{}} \\ \hline
  13131. \gray{\LwhileASTRacket} \\ \hline
  13132. \gray{\LtupASTRacket} \\ \hline
  13133. \LarrayASTRacket \\
  13134. \begin{array}{lcl}
  13135. \LangArray{} &::=& \Exp
  13136. \end{array}
  13137. \end{array}
  13138. \]
  13139. \fi}
  13140. {\if\edition\pythonEd\pythonColor
  13141. \[
  13142. \begin{array}{l}
  13143. \gray{\LintASTPython{}} \\ \hline
  13144. \gray{\LvarASTPython{}} \\ \hline
  13145. \gray{\LifASTPython{}} \\ \hline
  13146. \gray{\LwhileASTPython} \\ \hline
  13147. \gray{\LtupASTPython} \\ \hline
  13148. \LarrayASTPython \\
  13149. \begin{array}{rcl}
  13150. \LangArrayM{} &::=& \Stmt^{*}
  13151. \end{array}
  13152. \end{array}
  13153. \]
  13154. \fi}
  13155. \end{tcolorbox}
  13156. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13157. \label{fig:Lvecof-syntax}
  13158. \end{figure}
  13159. \begin{figure}[tp]
  13160. \begin{tcolorbox}[colback=white]
  13161. {\if\edition\racketEd
  13162. % TODO: remove the function from the following example, like the python version -Jeremy
  13163. \begin{lstlisting}
  13164. (let ([A (make-vector 2 2)])
  13165. (let ([B (make-vector 2 3)])
  13166. (let ([i 0])
  13167. (let ([prod 0])
  13168. (begin
  13169. (while (< i n)
  13170. (begin
  13171. (set! prod (+ prod (* (vector-ref A i)
  13172. (vector-ref B i))))
  13173. (set! i (+ i 1))))
  13174. prod)))))
  13175. \end{lstlisting}
  13176. \fi}
  13177. {\if\edition\pythonEd\pythonColor
  13178. \begin{lstlisting}
  13179. A = [2, 2]
  13180. B = [3, 3]
  13181. i = 0
  13182. prod = 0
  13183. while i != len(A):
  13184. prod = prod + A[i] * B[i]
  13185. i = i + 1
  13186. print(prod)
  13187. \end{lstlisting}
  13188. \fi}
  13189. \end{tcolorbox}
  13190. \caption{Example program that computes the inner product.}
  13191. \label{fig:inner_product}
  13192. \end{figure}
  13193. {\if\edition\racketEd
  13194. %
  13195. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13196. checker for \LangArray{}. The result type of
  13197. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13198. of the initializing expression. The length expression is required to
  13199. have type \code{Integer}. The type checking of the operators
  13200. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13201. updated to handle the situation in which the vector has type
  13202. \code{Vectorof}. In these cases we translate the operators to their
  13203. \code{vectorof} form so that later passes can easily distinguish
  13204. between operations on tuples versus arrays. We override the
  13205. \code{operator-types} method to provide the type signature for
  13206. multiplication: it takes two integers and returns an integer.
  13207. \fi}
  13208. %
  13209. {\if\edition\pythonEd\pythonColor
  13210. %
  13211. The type checker for \LangArray{} is defined in
  13212. figure~\ref{fig:type-check-Lvecof} and
  13213. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13214. is \code{list[T]}, where \code{T} is the type of the initializing
  13215. expressions. The type checking of the \code{len} function and the
  13216. subscript operator are updated to handle lists. The type checker now
  13217. also handles a subscript on the left-hand side of an assignment.
  13218. Regarding multiplication, it takes two integers and returns an
  13219. integer.
  13220. %
  13221. \fi}
  13222. \begin{figure}[tbp]
  13223. \begin{tcolorbox}[colback=white]
  13224. {\if\edition\racketEd
  13225. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13226. (define type-check-Lvecof-class
  13227. (class type-check-Lvec-class
  13228. (super-new)
  13229. (inherit check-type-equal?)
  13230. (define/override (operator-types)
  13231. (append '((* . ((Integer Integer) . Integer)))
  13232. (super operator-types)))
  13233. (define/override (type-check-exp env)
  13234. (lambda (e)
  13235. (define recur (type-check-exp env))
  13236. (match e
  13237. [(Prim 'make-vector (list e1 e2))
  13238. (define-values (e1^ t1) (recur e1))
  13239. (define-values (e2^ elt-type) (recur e2))
  13240. (define vec-type `(Vectorof ,elt-type))
  13241. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13242. [(Prim 'vector-ref (list e1 e2))
  13243. (define-values (e1^ t1) (recur e1))
  13244. (define-values (e2^ t2) (recur e2))
  13245. (match* (t1 t2)
  13246. [(`(Vectorof ,elt-type) 'Integer)
  13247. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13248. [(other wise) ((super type-check-exp env) e)])]
  13249. [(Prim 'vector-set! (list e1 e2 e3) )
  13250. (define-values (e-vec t-vec) (recur e1))
  13251. (define-values (e2^ t2) (recur e2))
  13252. (define-values (e-arg^ t-arg) (recur e3))
  13253. (match t-vec
  13254. [`(Vectorof ,elt-type)
  13255. (check-type-equal? elt-type t-arg e)
  13256. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13257. [else ((super type-check-exp env) e)])]
  13258. [(Prim 'vector-length (list e1))
  13259. (define-values (e1^ t1) (recur e1))
  13260. (match t1
  13261. [`(Vectorof ,t)
  13262. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13263. [else ((super type-check-exp env) e)])]
  13264. [else ((super type-check-exp env) e)])))
  13265. ))
  13266. (define (type-check-Lvecof p)
  13267. (send (new type-check-Lvecof-class) type-check-program p))
  13268. \end{lstlisting}
  13269. \fi}
  13270. {\if\edition\pythonEd\pythonColor
  13271. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13272. class TypeCheckLarray(TypeCheckLtup):
  13273. def type_check_exp(self, e, env):
  13274. match e:
  13275. case ast.List(es, Load()):
  13276. ts = [self.type_check_exp(e, env) for e in es]
  13277. elt_ty = ts[0]
  13278. for (ty, elt) in zip(ts, es):
  13279. self.check_type_equal(elt_ty, ty, elt)
  13280. e.has_type = ListType(elt_ty)
  13281. return e.has_type
  13282. case Call(Name('len'), [tup]):
  13283. tup_t = self.type_check_exp(tup, env)
  13284. tup.has_type = tup_t
  13285. match tup_t:
  13286. case TupleType(ts):
  13287. return IntType()
  13288. case ListType(ty):
  13289. return IntType()
  13290. case _:
  13291. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13292. case Subscript(tup, index, Load()):
  13293. tup_ty = self.type_check_exp(tup, env)
  13294. index_ty = self.type_check_exp(index, env)
  13295. self.check_type_equal(index_ty, IntType(), index)
  13296. match tup_ty:
  13297. case TupleType(ts):
  13298. match index:
  13299. case Constant(i):
  13300. return ts[i]
  13301. case _:
  13302. raise Exception('subscript required constant integer index')
  13303. case ListType(ty):
  13304. return ty
  13305. case _:
  13306. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13307. case BinOp(left, Mult(), right):
  13308. l = self.type_check_exp(left, env)
  13309. self.check_type_equal(l, IntType(), left)
  13310. r = self.type_check_exp(right, env)
  13311. self.check_type_equal(r, IntType(), right)
  13312. return IntType()
  13313. case _:
  13314. return super().type_check_exp(e, env)
  13315. \end{lstlisting}
  13316. \fi}
  13317. \end{tcolorbox}
  13318. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13319. \label{fig:type-check-Lvecof}
  13320. \end{figure}
  13321. {\if\edition\pythonEd
  13322. \begin{figure}[tbp]
  13323. \begin{tcolorbox}[colback=white]
  13324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13325. def type_check_stmts(self, ss, env):
  13326. if len(ss) == 0:
  13327. return VoidType()
  13328. match ss[0]:
  13329. case Assign([Subscript(tup, index, Store())], value):
  13330. tup_t = self.type_check_exp(tup, env)
  13331. value_t = self.type_check_exp(value, env)
  13332. index_ty = self.type_check_exp(index, env)
  13333. self.check_type_equal(index_ty, IntType(), index)
  13334. match tup_t:
  13335. case ListType(ty):
  13336. self.check_type_equal(ty, value_t, ss[0])
  13337. case TupleType(ts):
  13338. return self.type_check_stmts(ss, env)
  13339. case _:
  13340. raise Exception('type_check_stmts: '
  13341. 'expected tuple or list, not ' + repr(tup_t))
  13342. return self.type_check_stmts(ss[1:], env)
  13343. case _:
  13344. return super().type_check_stmts(ss, env)
  13345. \end{lstlisting}
  13346. \end{tcolorbox}
  13347. \caption{Type checker for the \LangArray{} language, part 2.}
  13348. \label{fig:type-check-Lvecof-part2}
  13349. \end{figure}
  13350. \fi}
  13351. The definition of the interpreter for \LangArray{} is shown in
  13352. \racket{figure~\ref{fig:interp-Lvecof}}
  13353. \python{figure~\ref{fig:interp-Lvecof}}.
  13354. \racket{The \code{make-vector} operator is
  13355. interpreted using Racket's \code{make-vector} function,
  13356. and multiplication is interpreted using \code{fx*},
  13357. which is multiplication for \code{fixnum} integers.
  13358. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13359. we translate array access operations
  13360. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13361. which we interpret using \code{vector} operations with additional
  13362. bounds checks that signal a \code{trapped-error}.
  13363. }
  13364. %
  13365. \python{We implement array creation with a Python list comprehension,
  13366. and multiplication is implemented with 64-bit multiplication. We
  13367. add a case for a subscript on the left-hand side of
  13368. assignment. Other uses of subscript can be handled by the existing
  13369. code for tuples.}
  13370. \begin{figure}[tbp]
  13371. \begin{tcolorbox}[colback=white]
  13372. {\if\edition\racketEd
  13373. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13374. (define interp-Lvecof-class
  13375. (class interp-Lvec-class
  13376. (super-new)
  13377. (define/override (interp-op op)
  13378. (match op
  13379. ['make-vector make-vector]
  13380. ['vectorof-length vector-length]
  13381. ['vectorof-ref
  13382. (lambda (v i)
  13383. (if (< i (vector-length v))
  13384. (vector-ref v i)
  13385. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13386. ['vectorof-set!
  13387. (lambda (v i e)
  13388. (if (< i (vector-length v))
  13389. (vector-set! v i e)
  13390. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13391. [else (super interp-op op)]))
  13392. ))
  13393. (define (interp-Lvecof p)
  13394. (send (new interp-Lvecof-class) interp-program p))
  13395. \end{lstlisting}
  13396. \fi}
  13397. {\if\edition\pythonEd\pythonColor
  13398. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13399. class InterpLarray(InterpLtup):
  13400. def interp_exp(self, e, env):
  13401. match e:
  13402. case ast.List(es, Load()):
  13403. return [self.interp_exp(e, env) for e in es]
  13404. case BinOp(left, Mult(), right):
  13405. l = self.interp_exp(left, env)
  13406. r = self.interp_exp(right, env)
  13407. return mul64(l, r)
  13408. case Subscript(tup, index, Load()):
  13409. t = self.interp_exp(tup, env)
  13410. n = self.interp_exp(index, env)
  13411. if n < len(t):
  13412. return t[n]
  13413. else:
  13414. raise TrappedError('array index out of bounds')
  13415. case _:
  13416. return super().interp_exp(e, env)
  13417. def interp_stmt(self, s, env, cont):
  13418. match s:
  13419. case Assign([Subscript(tup, index)], value):
  13420. t = self.interp_exp(tup, env)
  13421. n = self.interp_exp(index, env)
  13422. if n < len(t):
  13423. t[n] = self.interp_exp(value, env)
  13424. else:
  13425. raise TrappedError('array index out of bounds')
  13426. return self.interp_stmts(cont, env)
  13427. case _:
  13428. return super().interp_stmt(s, env, cont)
  13429. \end{lstlisting}
  13430. \fi}
  13431. \end{tcolorbox}
  13432. \caption{Interpreter for \LangArray{}.}
  13433. \label{fig:interp-Lvecof}
  13434. \end{figure}
  13435. \subsection{Data Representation}
  13436. \label{sec:array-rep}
  13437. Just as with tuples, we store arrays on the heap, which means that the
  13438. garbage collector will need to inspect arrays. An immediate thought is
  13439. to use the same representation for arrays that we use for tuples.
  13440. However, we limit tuples to a length of fifty so that their length and
  13441. pointer mask can fit into the 64-bit tag at the beginning of each
  13442. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13443. millions of elements, so we need more bits to store the length.
  13444. However, because arrays are homogeneous, we need only 1 bit for the
  13445. pointer mask instead of 1 bit per array element. Finally, the
  13446. garbage collector must be able to distinguish between tuples
  13447. and arrays, so we need to reserve one bit for that purpose. We
  13448. arrive at the following layout for the 64-bit tag at the beginning of
  13449. an array:
  13450. \begin{itemize}
  13451. \item The right-most bit is the forwarding bit, just as in a tuple.
  13452. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13453. that it is not.
  13454. \item The next bit to the left is the pointer mask. A $0$ indicates
  13455. that none of the elements are pointers, and a $1$ indicates that all
  13456. the elements are pointers.
  13457. \item The next $60$ bits store the length of the array.
  13458. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13459. and an array ($1$).
  13460. \item The left-most bit is reserved as explained in
  13461. chapter~\ref{ch:Lgrad}.
  13462. \end{itemize}
  13463. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13464. %% differentiate the kinds of values that have been injected into the
  13465. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13466. %% to indicate that the value is an array.
  13467. In the following subsections we provide hints regarding how to update
  13468. the passes to handle arrays.
  13469. \subsection{Overload Resolution}
  13470. \label{sec:array-resolution}
  13471. As noted previously, with the addition of arrays, several operators
  13472. have become \emph{overloaded}; that is, they can be applied to values
  13473. of more than one type. In this case, the element access and length
  13474. operators can be applied to both tuples and arrays. This kind of
  13475. overloading is quite common in programming languages, so many
  13476. compilers perform \emph{overload resolution}\index{subject}{overload
  13477. resolution} to handle it. The idea is to translate each overloaded
  13478. operator into different operators for the different types.
  13479. Implement a new pass named \code{resolve}.
  13480. Translate the reading of an array element to
  13481. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13482. and the writing of an array element to
  13483. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13484. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13485. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13486. When these operators are applied to tuples, leave them as is.
  13487. %
  13488. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13489. field, which can be inspected to determine whether the operator
  13490. is applied to a tuple or an array.}
  13491. \subsection{Bounds Checking}
  13492. Recall that the interpreter for \LangArray{} signals a
  13493. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13494. when there is an array access that is out of
  13495. bounds. Therefore your compiler is obliged to also catch these errors
  13496. during execution and halt, signaling an error. We recommend inserting
  13497. a new pass named \code{check\_bounds} that inserts code around each
  13498. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13499. \python{subscript} operation to ensure that the index is greater than
  13500. or equal to zero and less than the array's length. If not, the program
  13501. should halt, for which we recommend using a new primitive operation
  13502. named \code{exit}.
  13503. %% \subsection{Reveal Casts}
  13504. %% The array-access operators \code{vectorof-ref} and
  13505. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13506. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13507. %% that the type checker cannot tell whether the index will be in bounds,
  13508. %% so the bounds check must be performed at run time. Recall that the
  13509. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13510. %% an \code{If} around a vector reference for update to check whether
  13511. %% the index is less than the length. You should do the same for
  13512. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13513. %% In addition, the handling of the \code{any-vector} operators in
  13514. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13515. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13516. %% generated code should test whether the tag is for tuples (\code{010})
  13517. %% or arrays (\code{110}) and then dispatch to either
  13518. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13519. %% we add a case in \code{select\_instructions} to generate the
  13520. %% appropriate instructions for accessing the array length from the
  13521. %% header of an array.
  13522. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13523. %% the generated code needs to check that the index is less than the
  13524. %% vector length, so like the code for \code{any-vector-length}, check
  13525. %% the tag to determine whether to use \code{any-vector-length} or
  13526. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13527. %% is complete, the generated code can use \code{any-vector-ref} and
  13528. %% \code{any-vector-set!} for both tuples and arrays because the
  13529. %% instructions used for those operators do not look at the tag at the
  13530. %% front of the tuple or array.
  13531. \subsection{Expose Allocation}
  13532. This pass should translate array creation into lower-level
  13533. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13534. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13535. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13536. array. The \code{AllocateArray} AST node allocates an array of the
  13537. length specified by the $\Exp$ (of type \INTTY), but does not
  13538. initialize the elements of the array. Generate code in this pass to
  13539. initialize the elements analogous to the case for tuples.
  13540. {\if\edition\racketEd
  13541. \subsection{Uncover \texttt{get!}}
  13542. \label{sec:uncover-get-bang-vecof}
  13543. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13544. \code{uncover-get!-exp}.
  13545. \fi}
  13546. \subsection{Remove Complex Operands}
  13547. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13548. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13549. complex, and its subexpression must be atomic.
  13550. \subsection{Explicate Control}
  13551. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13552. \code{explicate\_assign}.
  13553. \subsection{Select Instructions}
  13554. \index{subject}{select instructions}
  13555. Generate instructions for \code{AllocateArray} similar to those for
  13556. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13557. except that the tag at the front of the array should instead use the
  13558. representation discussed in section~\ref{sec:array-rep}.
  13559. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13560. extract the length from the tag.
  13561. The instructions generated for accessing an element of an array differ
  13562. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13563. that the index is not a constant so you need to generate instructions
  13564. that compute the offset at runtime.
  13565. Compile the \code{exit} primitive into a call to the \code{exit}
  13566. function of the C standard library, with an argument of $255$.
  13567. %% Also, note that assignment to an array element may appear in
  13568. %% as a stand-alone statement, so make sure to handle that situation in
  13569. %% this pass.
  13570. %% Finally, the instructions for \code{any-vectorof-length} should be
  13571. %% similar to those for \code{vectorof-length}, except that one must
  13572. %% first project the array by writing zeroes into the $3$-bit tag
  13573. \begin{exercise}\normalfont\normalsize
  13574. Implement a compiler for the \LangArray{} language by extending your
  13575. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13576. programs, including the one shown in figure~\ref{fig:inner_product}
  13577. and also a program that multiplies two matrices. Note that although
  13578. matrices are two-dimensional arrays, they can be encoded into
  13579. one-dimensional arrays by laying out each row in the array, one after
  13580. the next.
  13581. \end{exercise}
  13582. {\if\edition\racketEd
  13583. \section{Challenge: Generational Collection}
  13584. The copying collector described in section~\ref{sec:GC} can incur
  13585. significant runtime overhead because the call to \code{collect} takes
  13586. time proportional to all the live data. One way to reduce this
  13587. overhead is to reduce how much data is inspected in each call to
  13588. \code{collect}. In particular, researchers have observed that recently
  13589. allocated data is more likely to become garbage then data that has
  13590. survived one or more previous calls to \code{collect}. This insight
  13591. motivated the creation of \emph{generational garbage collectors}
  13592. \index{subject}{generational garbage collector} that
  13593. (1) segregate data according to its age into two or more generations;
  13594. (2) allocate less space for younger generations, so collecting them is
  13595. faster, and more space for the older generations; and (3) perform
  13596. collection on the younger generations more frequently than on older
  13597. generations~\citep{Wilson:1992fk}.
  13598. For this challenge assignment, the goal is to adapt the copying
  13599. collector implemented in \code{runtime.c} to use two generations, one
  13600. for young data and one for old data. Each generation consists of a
  13601. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13602. \code{collect} function to use the two generations:
  13603. \begin{enumerate}
  13604. \item Copy the young generation's FromSpace to its ToSpace and then
  13605. switch the role of the ToSpace and FromSpace.
  13606. \item If there is enough space for the requested number of bytes in
  13607. the young FromSpace, then return from \code{collect}.
  13608. \item If there is not enough space in the young FromSpace for the
  13609. requested bytes, then move the data from the young generation to the
  13610. old one with the following steps:
  13611. \begin{enumerate}
  13612. \item[a.] If there is enough room in the old FromSpace, copy the young
  13613. FromSpace to the old FromSpace and then return.
  13614. \item[b.] If there is not enough room in the old FromSpace, then collect
  13615. the old generation by copying the old FromSpace to the old ToSpace
  13616. and swap the roles of the old FromSpace and ToSpace.
  13617. \item[c.] If there is enough room now, copy the young FromSpace to the
  13618. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13619. and ToSpace for the old generation. Copy the young FromSpace and
  13620. the old FromSpace into the larger FromSpace for the old
  13621. generation and then return.
  13622. \end{enumerate}
  13623. \end{enumerate}
  13624. We recommend that you generalize the \code{cheney} function so that it
  13625. can be used for all the copies mentioned: between the young FromSpace
  13626. and ToSpace, between the old FromSpace and ToSpace, and between the
  13627. young FromSpace and old FromSpace. This can be accomplished by adding
  13628. parameters to \code{cheney} that replace its use of the global
  13629. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13630. \code{tospace\_begin}, and \code{tospace\_end}.
  13631. Note that the collection of the young generation does not traverse the
  13632. old generation. This introduces a potential problem: there may be
  13633. young data that is reachable only through pointers in the old
  13634. generation. If these pointers are not taken into account, the
  13635. collector could throw away young data that is live! One solution,
  13636. called \emph{pointer recording}, is to maintain a set of all the
  13637. pointers from the old generation into the new generation and consider
  13638. this set as part of the root set. To maintain this set, the compiler
  13639. must insert extra instructions around every \code{vector-set!}. If the
  13640. vector being modified is in the old generation, and if the value being
  13641. written is a pointer into the new generation, then that pointer must
  13642. be added to the set. Also, if the value being overwritten was a
  13643. pointer into the new generation, then that pointer should be removed
  13644. from the set.
  13645. \begin{exercise}\normalfont\normalsize
  13646. Adapt the \code{collect} function in \code{runtime.c} to implement
  13647. generational garbage collection, as outlined in this section.
  13648. Update the code generation for \code{vector-set!} to implement
  13649. pointer recording. Make sure that your new compiler and runtime
  13650. execute without error on your test suite.
  13651. \end{exercise}
  13652. \fi}
  13653. \section{Further Reading}
  13654. \citet{Appel90} describes many data representation approaches
  13655. including the ones used in the compilation of Standard ML.
  13656. There are many alternatives to copying collectors (and their bigger
  13657. siblings, the generational collectors) with regard to garbage
  13658. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13659. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13660. collectors are that allocation is fast (just a comparison and pointer
  13661. increment), there is no fragmentation, cyclic garbage is collected,
  13662. and the time complexity of collection depends only on the amount of
  13663. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13664. main disadvantages of a two-space copying collector is that it uses a
  13665. lot of extra space and takes a long time to perform the copy, though
  13666. these problems are ameliorated in generational collectors.
  13667. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13668. small objects and generate a lot of garbage, so copying and
  13669. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13670. Garbage collection is an active research topic, especially concurrent
  13671. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13672. developing new techniques and revisiting old
  13673. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13674. meet every year at the International Symposium on Memory Management to
  13675. present these findings.
  13676. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13677. \chapter{Functions}
  13678. \label{ch:Lfun}
  13679. \index{subject}{function}
  13680. \setcounter{footnote}{0}
  13681. This chapter studies the compilation of a subset of \racket{Typed
  13682. Racket}\python{Python} in which only top-level function definitions
  13683. are allowed. This kind of function appears in the C programming
  13684. language, and it serves as an important stepping-stone to implementing
  13685. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13686. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13687. \section{The \LangFun{} Language}
  13688. The concrete syntax and abstract syntax for function definitions and
  13689. function application are shown in
  13690. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13691. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13692. with zero or more function definitions. The function names from these
  13693. definitions are in scope for the entire program, including all the
  13694. function definitions, and therefore the ordering of function
  13695. definitions does not matter.
  13696. %
  13697. \python{The abstract syntax for function parameters in
  13698. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13699. consists of a parameter name and its type. This design differs from
  13700. Python's \code{ast} module, which has a more complex structure for
  13701. function parameters to handle keyword parameters,
  13702. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13703. complex Python abstract syntax into the simpler syntax shown in
  13704. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13705. \code{FunctionDef} constructor are for decorators and a type
  13706. comment, neither of which are used by our compiler. We recommend
  13707. replacing them with \code{None} in the \code{shrink} pass.
  13708. }
  13709. %
  13710. The concrete syntax for function application
  13711. \index{subject}{function application}
  13712. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13713. where the first expression
  13714. must evaluate to a function and the remaining expressions are the arguments. The
  13715. abstract syntax for function application is
  13716. $\APPLY{\Exp}{\Exp^*}$.
  13717. %% The syntax for function application does not include an explicit
  13718. %% keyword, which is error prone when using \code{match}. To alleviate
  13719. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13720. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13721. Functions are first-class in the sense that a function pointer
  13722. \index{subject}{function pointer} is data and can be stored in memory or passed
  13723. as a parameter to another function. Thus, there is a function
  13724. type, written
  13725. {\if\edition\racketEd
  13726. \begin{lstlisting}
  13727. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13728. \end{lstlisting}
  13729. \fi}
  13730. {\if\edition\pythonEd\pythonColor
  13731. \begin{lstlisting}
  13732. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13733. \end{lstlisting}
  13734. \fi}
  13735. %
  13736. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13737. through $\Type_n$ and whose return type is $\Type_R$. The main
  13738. limitation of these functions (with respect to
  13739. \racket{Racket}\python{Python} functions) is that they are not
  13740. lexically scoped. That is, the only external entities that can be
  13741. referenced from inside a function body are other globally defined
  13742. functions. The syntax of \LangFun{} prevents function definitions from
  13743. being nested inside each other.
  13744. \newcommand{\LfunGrammarRacket}{
  13745. \begin{array}{lcl}
  13746. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13747. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13748. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13749. \end{array}
  13750. }
  13751. \newcommand{\LfunASTRacket}{
  13752. \begin{array}{lcl}
  13753. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13754. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13755. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13756. \end{array}
  13757. }
  13758. \newcommand{\LfunGrammarPython}{
  13759. \begin{array}{lcl}
  13760. \Type &::=& \key{int}
  13761. \MID \key{bool} \MID \key{void}
  13762. \MID \key{tuple}\LS \Type^+ \RS
  13763. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13764. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13765. \Stmt &::=& \CRETURN{\Exp} \\
  13766. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13767. \end{array}
  13768. }
  13769. \newcommand{\LfunASTPython}{
  13770. \begin{array}{lcl}
  13771. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13772. \MID \key{TupleType}\LS\Type^+\RS\\
  13773. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13774. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13775. \Stmt &::=& \RETURN{\Exp} \\
  13776. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13777. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13778. \end{array}
  13779. }
  13780. \begin{figure}[tp]
  13781. \centering
  13782. \begin{tcolorbox}[colback=white]
  13783. \small
  13784. {\if\edition\racketEd
  13785. \[
  13786. \begin{array}{l}
  13787. \gray{\LintGrammarRacket{}} \\ \hline
  13788. \gray{\LvarGrammarRacket{}} \\ \hline
  13789. \gray{\LifGrammarRacket{}} \\ \hline
  13790. \gray{\LwhileGrammarRacket} \\ \hline
  13791. \gray{\LtupGrammarRacket} \\ \hline
  13792. \LfunGrammarRacket \\
  13793. \begin{array}{lcl}
  13794. \LangFunM{} &::=& \Def \ldots \; \Exp
  13795. \end{array}
  13796. \end{array}
  13797. \]
  13798. \fi}
  13799. {\if\edition\pythonEd\pythonColor
  13800. \[
  13801. \begin{array}{l}
  13802. \gray{\LintGrammarPython{}} \\ \hline
  13803. \gray{\LvarGrammarPython{}} \\ \hline
  13804. \gray{\LifGrammarPython{}} \\ \hline
  13805. \gray{\LwhileGrammarPython} \\ \hline
  13806. \gray{\LtupGrammarPython} \\ \hline
  13807. \LfunGrammarPython \\
  13808. \begin{array}{rcl}
  13809. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13810. \end{array}
  13811. \end{array}
  13812. \]
  13813. \fi}
  13814. \end{tcolorbox}
  13815. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13816. \label{fig:Lfun-concrete-syntax}
  13817. \end{figure}
  13818. \begin{figure}[tp]
  13819. \centering
  13820. \begin{tcolorbox}[colback=white]
  13821. \small
  13822. {\if\edition\racketEd
  13823. \[
  13824. \begin{array}{l}
  13825. \gray{\LintOpAST} \\ \hline
  13826. \gray{\LvarASTRacket{}} \\ \hline
  13827. \gray{\LifASTRacket{}} \\ \hline
  13828. \gray{\LwhileASTRacket{}} \\ \hline
  13829. \gray{\LtupASTRacket{}} \\ \hline
  13830. \LfunASTRacket \\
  13831. \begin{array}{lcl}
  13832. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13833. \end{array}
  13834. \end{array}
  13835. \]
  13836. \fi}
  13837. {\if\edition\pythonEd\pythonColor
  13838. \[
  13839. \begin{array}{l}
  13840. \gray{\LintASTPython{}} \\ \hline
  13841. \gray{\LvarASTPython{}} \\ \hline
  13842. \gray{\LifASTPython{}} \\ \hline
  13843. \gray{\LwhileASTPython} \\ \hline
  13844. \gray{\LtupASTPython} \\ \hline
  13845. \LfunASTPython \\
  13846. \begin{array}{rcl}
  13847. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13848. \end{array}
  13849. \end{array}
  13850. \]
  13851. \fi}
  13852. \end{tcolorbox}
  13853. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13854. \label{fig:Lfun-syntax}
  13855. \end{figure}
  13856. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13857. representative example of defining and using functions in \LangFun{}.
  13858. We define a function \code{map} that applies some other function
  13859. \code{f} to both elements of a tuple and returns a new tuple
  13860. containing the results. We also define a function \code{inc}. The
  13861. program applies \code{map} to \code{inc} and
  13862. %
  13863. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13864. %
  13865. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13866. %
  13867. from which we return \code{42}.
  13868. \begin{figure}[tbp]
  13869. \begin{tcolorbox}[colback=white]
  13870. {\if\edition\racketEd
  13871. \begin{lstlisting}
  13872. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13873. : (Vector Integer Integer)
  13874. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13875. (define (inc [x : Integer]) : Integer
  13876. (+ x 1))
  13877. (vector-ref (map inc (vector 0 41)) 1)
  13878. \end{lstlisting}
  13879. \fi}
  13880. {\if\edition\pythonEd\pythonColor
  13881. \begin{lstlisting}
  13882. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13883. return f(v[0]), f(v[1])
  13884. def inc(x : int) -> int:
  13885. return x + 1
  13886. print(map(inc, (0, 41))[1])
  13887. \end{lstlisting}
  13888. \fi}
  13889. \end{tcolorbox}
  13890. \caption{Example of using functions in \LangFun{}.}
  13891. \label{fig:Lfun-function-example}
  13892. \end{figure}
  13893. The definitional interpreter for \LangFun{} is shown in
  13894. figure~\ref{fig:interp-Lfun}. The case for the
  13895. %
  13896. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13897. %
  13898. AST is responsible for setting up the mutual recursion between the
  13899. top-level function definitions.
  13900. %
  13901. \racket{We use the classic back-patching
  13902. \index{subject}{back-patching} approach that uses mutable variables
  13903. and makes two passes over the function
  13904. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13905. top-level environment using a mutable cons cell for each function
  13906. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13907. for each function is incomplete; it does not yet include the environment.
  13908. Once the top-level environment has been constructed, we iterate over it and
  13909. update the \code{lambda} values to use the top-level environment.}
  13910. %
  13911. \python{We create a dictionary named \code{env} and fill it in
  13912. by mapping each function name to a new \code{Function} value,
  13913. each of which stores a reference to the \code{env}.
  13914. (We define the class \code{Function} for this purpose.)}
  13915. %
  13916. To interpret a function \racket{application}\python{call}, we match
  13917. the result of the function expression to obtain a function value. We
  13918. then extend the function's environment with the mapping of parameters to
  13919. argument values. Finally, we interpret the body of the function in
  13920. this extended environment.
  13921. \begin{figure}[tp]
  13922. \begin{tcolorbox}[colback=white]
  13923. {\if\edition\racketEd
  13924. \begin{lstlisting}
  13925. (define interp-Lfun-class
  13926. (class interp-Lvec-class
  13927. (super-new)
  13928. (define/override ((interp-exp env) e)
  13929. (define recur (interp-exp env))
  13930. (match e
  13931. [(Apply fun args)
  13932. (define fun-val (recur fun))
  13933. (define arg-vals (for/list ([e args]) (recur e)))
  13934. (match fun-val
  13935. [`(function (,xs ...) ,body ,fun-env)
  13936. (define params-args (for/list ([x xs] [arg arg-vals])
  13937. (cons x (box arg))))
  13938. (define new-env (append params-args fun-env))
  13939. ((interp-exp new-env) body)]
  13940. [else
  13941. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13942. [else ((super interp-exp env) e)]
  13943. ))
  13944. (define/public (interp-def d)
  13945. (match d
  13946. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13947. (cons f (box `(function ,xs ,body ())))]))
  13948. (define/override (interp-program p)
  13949. (match p
  13950. [(ProgramDefsExp info ds body)
  13951. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13952. (for/list ([f (in-dict-values top-level)])
  13953. (set-box! f (match (unbox f)
  13954. [`(function ,xs ,body ())
  13955. `(function ,xs ,body ,top-level)])))
  13956. ((interp-exp top-level) body))]))
  13957. ))
  13958. (define (interp-Lfun p)
  13959. (send (new interp-Lfun-class) interp-program p))
  13960. \end{lstlisting}
  13961. \fi}
  13962. {\if\edition\pythonEd\pythonColor
  13963. \begin{lstlisting}
  13964. class InterpLfun(InterpLtup):
  13965. def apply_fun(self, fun, args, e):
  13966. match fun:
  13967. case Function(name, xs, body, env):
  13968. new_env = env.copy().update(zip(xs, args))
  13969. return self.interp_stmts(body, new_env)
  13970. case _:
  13971. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13972. def interp_exp(self, e, env):
  13973. match e:
  13974. case Call(Name('input_int'), []):
  13975. return super().interp_exp(e, env)
  13976. case Call(func, args):
  13977. f = self.interp_exp(func, env)
  13978. vs = [self.interp_exp(arg, env) for arg in args]
  13979. return self.apply_fun(f, vs, e)
  13980. case _:
  13981. return super().interp_exp(e, env)
  13982. def interp_stmt(self, s, env, cont):
  13983. match s:
  13984. case Return(value):
  13985. return self.interp_exp(value, env)
  13986. case FunctionDef(name, params, bod, dl, returns, comment):
  13987. if isinstance(params, ast.arguments):
  13988. ps = [p.arg for p in params.args]
  13989. else:
  13990. ps = [x for (x,t) in params]
  13991. env[name] = Function(name, ps, bod, env)
  13992. return self.interp_stmts(cont, env)
  13993. case _:
  13994. return super().interp_stmt(s, env, cont)
  13995. def interp(self, p):
  13996. match p:
  13997. case Module(ss):
  13998. env = {}
  13999. self.interp_stmts(ss, env)
  14000. if 'main' in env.keys():
  14001. self.apply_fun(env['main'], [], None)
  14002. case _:
  14003. raise Exception('interp: unexpected ' + repr(p))
  14004. \end{lstlisting}
  14005. \fi}
  14006. \end{tcolorbox}
  14007. \caption{Interpreter for the \LangFun{} language.}
  14008. \label{fig:interp-Lfun}
  14009. \end{figure}
  14010. %\margincomment{TODO: explain type checker}
  14011. The type checker for \LangFun{} is shown in
  14012. figure~\ref{fig:type-check-Lfun}.
  14013. %
  14014. \python{(We omit the code that parses function parameters into the
  14015. simpler abstract syntax.)}
  14016. %
  14017. Similarly to the interpreter, the case for the
  14018. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14019. %
  14020. AST is responsible for setting up the mutual recursion between the
  14021. top-level function definitions. We begin by creating a mapping
  14022. \code{env} from every function name to its type. We then type check
  14023. the program using this mapping.
  14024. %
  14025. \python{To check a function definition, we copy and extend the
  14026. \code{env} with the parameters of the function. We then type check
  14027. the body of the function and obtain the actual return type
  14028. \code{rt}, which is either the type of the expression in a
  14029. \code{return} statement, or the \code{VoidType} if control reaches
  14030. the end of the function without a \code{return} statement. (If
  14031. there are multiple \code{return} statements, the types of their
  14032. expressions must agree.) Finally we check that the actual return
  14033. type \code{rt} is equal to the declared return type \code{returns}.}
  14034. %
  14035. To check a function \racket{application}\python{call}, we match
  14036. the type of the function expression to a function type and check that
  14037. the types of the argument expressions are equal to the function's
  14038. parameter types. The type of the \racket{application}\python{call} as
  14039. a whole is the return type from the function type.
  14040. \begin{figure}[tp]
  14041. \begin{tcolorbox}[colback=white]
  14042. {\if\edition\racketEd
  14043. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14044. (define type-check-Lfun-class
  14045. (class type-check-Lvec-class
  14046. (super-new)
  14047. (inherit check-type-equal?)
  14048. (define/public (type-check-apply env e es)
  14049. (define-values (e^ ty) ((type-check-exp env) e))
  14050. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14051. ((type-check-exp env) e)))
  14052. (match ty
  14053. [`(,ty^* ... -> ,rt)
  14054. (for ([arg-ty ty*] [param-ty ty^*])
  14055. (check-type-equal? arg-ty param-ty (Apply e es)))
  14056. (values e^ e* rt)]))
  14057. (define/override (type-check-exp env)
  14058. (lambda (e)
  14059. (match e
  14060. [(FunRef f n)
  14061. (values (FunRef f n) (dict-ref env f))]
  14062. [(Apply e es)
  14063. (define-values (e^ es^ rt) (type-check-apply env e es))
  14064. (values (Apply e^ es^) rt)]
  14065. [(Call e es)
  14066. (define-values (e^ es^ rt) (type-check-apply env e es))
  14067. (values (Call e^ es^) rt)]
  14068. [else ((super type-check-exp env) e)])))
  14069. (define/public (type-check-def env)
  14070. (lambda (e)
  14071. (match e
  14072. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14073. (define new-env (append (map cons xs ps) env))
  14074. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14075. (check-type-equal? ty^ rt body)
  14076. (Def f p:t* rt info body^)])))
  14077. (define/public (fun-def-type d)
  14078. (match d
  14079. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14080. (define/override (type-check-program e)
  14081. (match e
  14082. [(ProgramDefsExp info ds body)
  14083. (define env (for/list ([d ds])
  14084. (cons (Def-name d) (fun-def-type d))))
  14085. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14086. (define-values (body^ ty) ((type-check-exp env) body))
  14087. (check-type-equal? ty 'Integer body)
  14088. (ProgramDefsExp info ds^ body^)]))))
  14089. (define (type-check-Lfun p)
  14090. (send (new type-check-Lfun-class) type-check-program p))
  14091. \end{lstlisting}
  14092. \fi}
  14093. {\if\edition\pythonEd\pythonColor
  14094. \begin{lstlisting}
  14095. class TypeCheckLfun(TypeCheckLtup):
  14096. def type_check_exp(self, e, env):
  14097. match e:
  14098. case Call(Name('input_int'), []):
  14099. return super().type_check_exp(e, env)
  14100. case Call(func, args):
  14101. func_t = self.type_check_exp(func, env)
  14102. args_t = [self.type_check_exp(arg, env) for arg in args]
  14103. match func_t:
  14104. case FunctionType(params_t, return_t):
  14105. for (arg_t, param_t) in zip(args_t, params_t):
  14106. check_type_equal(param_t, arg_t, e)
  14107. return return_t
  14108. case _:
  14109. raise Exception('type_check_exp: in call, unexpected ' +
  14110. repr(func_t))
  14111. case _:
  14112. return super().type_check_exp(e, env)
  14113. def type_check_stmts(self, ss, env):
  14114. if len(ss) == 0:
  14115. return VoidType()
  14116. match ss[0]:
  14117. case FunctionDef(name, params, body, dl, returns, comment):
  14118. new_env = env.copy().update(params)
  14119. rt = self.type_check_stmts(body, new_env)
  14120. check_type_equal(returns, rt, ss[0])
  14121. return self.type_check_stmts(ss[1:], env)
  14122. case Return(value):
  14123. return self.type_check_exp(value, env)
  14124. case _:
  14125. return super().type_check_stmts(ss, env)
  14126. def type_check(self, p):
  14127. match p:
  14128. case Module(body):
  14129. env = {}
  14130. for s in body:
  14131. match s:
  14132. case FunctionDef(name, params, bod, dl, returns, comment):
  14133. if name in env:
  14134. raise Exception('type_check: function ' +
  14135. repr(name) + ' defined twice')
  14136. params_t = [t for (x,t) in params]
  14137. env[name] = FunctionType(params_t, returns)
  14138. self.type_check_stmts(body, env)
  14139. case _:
  14140. raise Exception('type_check: unexpected ' + repr(p))
  14141. \end{lstlisting}
  14142. \fi}
  14143. \end{tcolorbox}
  14144. \caption{Type checker for the \LangFun{} language.}
  14145. \label{fig:type-check-Lfun}
  14146. \end{figure}
  14147. \clearpage
  14148. \section{Functions in x86}
  14149. \label{sec:fun-x86}
  14150. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14151. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14152. %% \margincomment{\tiny Talk about the return address on the
  14153. %% stack and what callq and retq does.\\ --Jeremy }
  14154. The x86 architecture provides a few features to support the
  14155. implementation of functions. We have already seen that there are
  14156. labels in x86 so that one can refer to the location of an instruction,
  14157. as is needed for jump instructions. Labels can also be used to mark
  14158. the beginning of the instructions for a function. Going further, we
  14159. can obtain the address of a label by using the \key{leaq}
  14160. instruction. For example, the following puts the address of the
  14161. \code{inc} label into the \code{rbx} register:
  14162. \begin{lstlisting}
  14163. leaq inc(%rip), %rbx
  14164. \end{lstlisting}
  14165. Recall from section~\ref{sec:select-instructions-gc} that
  14166. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14167. addressing.
  14168. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14169. to functions whose locations were given by a label, such as
  14170. \code{read\_int}. To support function calls in this chapter we instead
  14171. jump to functions whose location are given by an address in
  14172. a register; that is, we use \emph{indirect function calls}. The
  14173. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14174. before the register name.\index{subject}{indirect function call}
  14175. \begin{lstlisting}
  14176. callq *%rbx
  14177. \end{lstlisting}
  14178. \subsection{Calling Conventions}
  14179. \label{sec:calling-conventions-fun}
  14180. \index{subject}{calling conventions}
  14181. The \code{callq} instruction provides partial support for implementing
  14182. functions: it pushes the return address on the stack and it jumps to
  14183. the target. However, \code{callq} does not handle
  14184. \begin{enumerate}
  14185. \item parameter passing,
  14186. \item pushing frames on the procedure call stack and popping them off,
  14187. or
  14188. \item determining how registers are shared by different functions.
  14189. \end{enumerate}
  14190. Regarding parameter passing, recall that the x86-64 calling
  14191. convention for Unix-based systems uses the following six registers to
  14192. pass arguments to a function, in the given order:
  14193. \begin{lstlisting}
  14194. rdi rsi rdx rcx r8 r9
  14195. \end{lstlisting}
  14196. If there are more than six arguments, then the calling convention
  14197. mandates using space on the frame of the caller for the rest of the
  14198. arguments. However, to ease the implementation of efficient tail calls
  14199. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14200. arguments.
  14201. %
  14202. The return value of the function is stored in register \code{rax}.
  14203. Regarding frames \index{subject}{frame} and the procedure call stack,
  14204. \index{subject}{procedure call stack} recall from
  14205. section~\ref{sec:x86} that the stack grows down and each function call
  14206. uses a chunk of space on the stack called a frame. The caller sets the
  14207. stack pointer, register \code{rsp}, to the last data item in its
  14208. frame. The callee must not change anything in the caller's frame, that
  14209. is, anything that is at or above the stack pointer. The callee is free
  14210. to use locations that are below the stack pointer.
  14211. Recall that we store variables of tuple type on the root stack. So,
  14212. the prelude\index{subject}{prelude} of a function needs to move the
  14213. root stack pointer \code{r15} up according to the number of variables
  14214. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14215. move the root stack pointer back down. Also, the prelude must
  14216. initialize to \code{0} this frame's slots in the root stack to signal
  14217. to the garbage collector that those slots do not yet contain a valid
  14218. pointer. Otherwise the garbage collector will interpret the garbage
  14219. bits in those slots as memory addresses and try to traverse them,
  14220. causing serious mayhem!
  14221. Regarding the sharing of registers between different functions, recall
  14222. from section~\ref{sec:calling-conventions} that the registers are
  14223. divided into two groups, the caller-saved registers and the
  14224. callee-saved registers. The caller should assume that all the
  14225. caller-saved registers are overwritten with arbitrary values by the
  14226. callee. For that reason we recommend in
  14227. section~\ref{sec:calling-conventions} that variables that are live
  14228. during a function call should not be assigned to caller-saved
  14229. registers.
  14230. On the flip side, if the callee wants to use a callee-saved register,
  14231. the callee must save the contents of those registers on their stack
  14232. frame and then put them back prior to returning to the caller. For
  14233. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14234. the register allocator assigns a variable to a callee-saved register,
  14235. then the prelude of the \code{main} function must save that register
  14236. to the stack and the conclusion of \code{main} must restore it. This
  14237. recommendation now generalizes to all functions.
  14238. Recall that the base pointer, register \code{rbp}, is used as a
  14239. point of reference within a frame, so that each local variable can be
  14240. accessed at a fixed offset from the base pointer
  14241. (section~\ref{sec:x86}).
  14242. %
  14243. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14244. frames.
  14245. \begin{figure}[tbp]
  14246. \centering
  14247. \begin{tcolorbox}[colback=white]
  14248. \begin{tabular}{r|r|l|l} \hline
  14249. Caller View & Callee View & Contents & Frame \\ \hline
  14250. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14251. 0(\key{\%rbp}) & & old \key{rbp} \\
  14252. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14253. \ldots & & \ldots \\
  14254. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14255. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14256. \ldots & & \ldots \\
  14257. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14258. %% & & \\
  14259. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14260. %% & \ldots & \ldots \\
  14261. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14262. \hline
  14263. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14264. & 0(\key{\%rbp}) & old \key{rbp} \\
  14265. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14266. & \ldots & \ldots \\
  14267. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14268. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14269. & \ldots & \ldots \\
  14270. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14271. \end{tabular}
  14272. \end{tcolorbox}
  14273. \caption{Memory layout of caller and callee frames.}
  14274. \label{fig:call-frames}
  14275. \end{figure}
  14276. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14277. %% local variables and for storing the values of callee-saved registers
  14278. %% (we shall refer to all of these collectively as ``locals''), and that
  14279. %% at the beginning of a function we move the stack pointer \code{rsp}
  14280. %% down to make room for them.
  14281. %% We recommend storing the local variables
  14282. %% first and then the callee-saved registers, so that the local variables
  14283. %% can be accessed using \code{rbp} the same as before the addition of
  14284. %% functions.
  14285. %% To make additional room for passing arguments, we shall
  14286. %% move the stack pointer even further down. We count how many stack
  14287. %% arguments are needed for each function call that occurs inside the
  14288. %% body of the function and find their maximum. Adding this number to the
  14289. %% number of locals gives us how much the \code{rsp} should be moved at
  14290. %% the beginning of the function. In preparation for a function call, we
  14291. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14292. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14293. %% so on.
  14294. %% Upon calling the function, the stack arguments are retrieved by the
  14295. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14296. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14297. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14298. %% the layout of the caller and callee frames. Notice how important it is
  14299. %% that we correctly compute the maximum number of arguments needed for
  14300. %% function calls; if that number is too small then the arguments and
  14301. %% local variables will smash into each other!
  14302. \subsection{Efficient Tail Calls}
  14303. \label{sec:tail-call}
  14304. In general, the amount of stack space used by a program is determined
  14305. by the longest chain of nested function calls. That is, if function
  14306. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14307. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14308. large if functions are recursive. However, in some cases we can
  14309. arrange to use only a constant amount of space for a long chain of
  14310. nested function calls.
  14311. A \emph{tail call}\index{subject}{tail call} is a function call that
  14312. happens as the last action in a function body. For example, in the
  14313. following program, the recursive call to \code{tail\_sum} is a tail
  14314. call:
  14315. \begin{center}
  14316. {\if\edition\racketEd
  14317. \begin{lstlisting}
  14318. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14319. (if (eq? n 0)
  14320. r
  14321. (tail_sum (- n 1) (+ n r))))
  14322. (+ (tail_sum 3 0) 36)
  14323. \end{lstlisting}
  14324. \fi}
  14325. {\if\edition\pythonEd\pythonColor
  14326. \begin{lstlisting}
  14327. def tail_sum(n : int, r : int) -> int:
  14328. if n == 0:
  14329. return r
  14330. else:
  14331. return tail_sum(n - 1, n + r)
  14332. print(tail_sum(3, 0) + 36)
  14333. \end{lstlisting}
  14334. \fi}
  14335. \end{center}
  14336. At a tail call, the frame of the caller is no longer needed, so we can
  14337. pop the caller's frame before making the tail
  14338. call. \index{subject}{frame} With this approach, a recursive function
  14339. that makes only tail calls ends up using a constant amount of stack
  14340. space. \racket{Functional languages like Racket rely heavily on
  14341. recursive functions, so the definition of Racket \emph{requires}
  14342. that all tail calls be optimized in this way.}
  14343. Some care is needed with regard to argument passing in tail calls. As
  14344. mentioned, for arguments beyond the sixth, the convention is to use
  14345. space in the caller's frame for passing arguments. However, for a
  14346. tail call we pop the caller's frame and can no longer use it. An
  14347. alternative is to use space in the callee's frame for passing
  14348. arguments. However, this option is also problematic because the caller
  14349. and callee's frames overlap in memory. As we begin to copy the
  14350. arguments from their sources in the caller's frame, the target
  14351. locations in the callee's frame might collide with the sources for
  14352. later arguments! We solve this problem by using the heap instead of
  14353. the stack for passing more than six arguments
  14354. (section~\ref{sec:limit-functions-r4}).
  14355. As mentioned, for a tail call we pop the caller's frame prior to
  14356. making the tail call. The instructions for popping a frame are the
  14357. instructions that we usually place in the conclusion of a
  14358. function. Thus, we also need to place such code immediately before
  14359. each tail call. These instructions include restoring the callee-saved
  14360. registers, so it is fortunate that the argument passing registers are
  14361. all caller-saved registers.
  14362. One note remains regarding which instruction to use to make the tail
  14363. call. When the callee is finished, it should not return to the current
  14364. function but instead return to the function that called the current
  14365. one. Thus, the return address that is already on the stack is the
  14366. right one, and we should not use \key{callq} to make the tail call
  14367. because that would overwrite the return address. Instead we simply use
  14368. the \key{jmp} instruction. As with the indirect function call, we write
  14369. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14370. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14371. jump target because the conclusion can overwrite just about everything
  14372. else.
  14373. \begin{lstlisting}
  14374. jmp *%rax
  14375. \end{lstlisting}
  14376. \section{Shrink \LangFun{}}
  14377. \label{sec:shrink-r4}
  14378. The \code{shrink} pass performs a minor modification to ease the
  14379. later passes. This pass introduces an explicit \code{main} function
  14380. that gobbles up all the top-level statements of the module.
  14381. %
  14382. \racket{It also changes the top \code{ProgramDefsExp} form to
  14383. \code{ProgramDefs}.}
  14384. {\if\edition\racketEd
  14385. \begin{lstlisting}
  14386. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14387. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14388. \end{lstlisting}
  14389. where $\itm{mainDef}$ is
  14390. \begin{lstlisting}
  14391. (Def 'main '() 'Integer '() |$\Exp'$|)
  14392. \end{lstlisting}
  14393. \fi}
  14394. {\if\edition\pythonEd\pythonColor
  14395. \begin{lstlisting}
  14396. Module(|$\Def\ldots\Stmt\ldots$|)
  14397. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14398. \end{lstlisting}
  14399. where $\itm{mainDef}$ is
  14400. \begin{lstlisting}
  14401. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14402. \end{lstlisting}
  14403. \fi}
  14404. \section{Reveal Functions and the \LangFunRef{} Language}
  14405. \label{sec:reveal-functions-r4}
  14406. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14407. in that it conflates the use of function names and local
  14408. variables. This is a problem because we need to compile the use of a
  14409. function name differently from the use of a local variable. In
  14410. particular, we use \code{leaq} to convert the function name (a label
  14411. in x86) to an address in a register. Thus, we create a new pass that
  14412. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14413. $n$ is the arity of the function.\python{\footnote{The arity is not
  14414. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14415. This pass is named \code{reveal\_functions} and the output language
  14416. is \LangFunRef{}.
  14417. %is defined in figure~\ref{fig:f1-syntax}.
  14418. %% The concrete syntax for a
  14419. %% function reference is $\CFUNREF{f}$.
  14420. %% \begin{figure}[tp]
  14421. %% \centering
  14422. %% \fbox{
  14423. %% \begin{minipage}{0.96\textwidth}
  14424. %% {\if\edition\racketEd
  14425. %% \[
  14426. %% \begin{array}{lcl}
  14427. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14428. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14429. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14430. %% \end{array}
  14431. %% \]
  14432. %% \fi}
  14433. %% {\if\edition\pythonEd\pythonColor
  14434. %% \[
  14435. %% \begin{array}{lcl}
  14436. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14437. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14438. %% \end{array}
  14439. %% \]
  14440. %% \fi}
  14441. %% \end{minipage}
  14442. %% }
  14443. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14444. %% (figure~\ref{fig:Lfun-syntax}).}
  14445. %% \label{fig:f1-syntax}
  14446. %% \end{figure}
  14447. %% Distinguishing between calls in tail position and non-tail position
  14448. %% requires the pass to have some notion of context. We recommend using
  14449. %% two mutually recursive functions, one for processing expressions in
  14450. %% tail position and another for the rest.
  14451. \racket{Placing this pass after \code{uniquify} will make sure that
  14452. there are no local variables and functions that share the same
  14453. name.}
  14454. %
  14455. The \code{reveal\_functions} pass should come before the
  14456. \code{remove\_complex\_operands} pass because function references
  14457. should be categorized as complex expressions.
  14458. \section{Limit Functions}
  14459. \label{sec:limit-functions-r4}
  14460. Recall that we wish to limit the number of function parameters to six
  14461. so that we do not need to use the stack for argument passing, which
  14462. makes it easier to implement efficient tail calls. However, because
  14463. the input language \LangFun{} supports arbitrary numbers of function
  14464. arguments, we have some work to do! The \code{limit\_functions} pass
  14465. transforms functions and function calls that involve more than six
  14466. arguments to pass the first five arguments as usual, but it packs the
  14467. rest of the arguments into a tuple and passes it as the sixth
  14468. argument.\footnote{The implementation this pass can be postponed to
  14469. last because you can test the rest of the passes on functions with
  14470. six or fewer parameters.}
  14471. Each function definition with seven or more parameters is transformed as
  14472. follows:
  14473. {\if\edition\racketEd
  14474. \begin{lstlisting}
  14475. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14476. |$\Rightarrow$|
  14477. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14478. \end{lstlisting}
  14479. \fi}
  14480. {\if\edition\pythonEd\pythonColor
  14481. \begin{lstlisting}
  14482. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14483. |$\Rightarrow$|
  14484. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14485. |$T_r$|, None, |$\itm{body}'$|, None)
  14486. \end{lstlisting}
  14487. \fi}
  14488. %
  14489. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14490. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14491. the $k$th element of the tuple, where $k = i - 6$.
  14492. %
  14493. {\if\edition\racketEd
  14494. \begin{lstlisting}
  14495. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14496. \end{lstlisting}
  14497. \fi}
  14498. {\if\edition\pythonEd\pythonColor
  14499. \begin{lstlisting}
  14500. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14501. \end{lstlisting}
  14502. \fi}
  14503. For function calls with too many arguments, the \code{limit\_functions}
  14504. pass transforms them in the following way:
  14505. \begin{tabular}{lll}
  14506. \begin{minipage}{0.3\textwidth}
  14507. {\if\edition\racketEd
  14508. \begin{lstlisting}
  14509. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14510. \end{lstlisting}
  14511. \fi}
  14512. {\if\edition\pythonEd\pythonColor
  14513. \begin{lstlisting}
  14514. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14515. \end{lstlisting}
  14516. \fi}
  14517. \end{minipage}
  14518. &
  14519. $\Rightarrow$
  14520. &
  14521. \begin{minipage}{0.5\textwidth}
  14522. {\if\edition\racketEd
  14523. \begin{lstlisting}
  14524. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14525. \end{lstlisting}
  14526. \fi}
  14527. {\if\edition\pythonEd\pythonColor
  14528. \begin{lstlisting}
  14529. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14530. \end{lstlisting}
  14531. \fi}
  14532. \end{minipage}
  14533. \end{tabular}
  14534. \section{Remove Complex Operands}
  14535. \label{sec:rco-r4}
  14536. The primary decisions to make for this pass are whether to classify
  14537. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14538. atomic or complex expressions. Recall that an atomic expression
  14539. ends up as an immediate argument of an x86 instruction. Function
  14540. application translates to a sequence of instructions, so
  14541. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14542. a complex expression. On the other hand, the arguments of
  14543. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14544. expressions.
  14545. %
  14546. Regarding \code{FunRef}, as discussed previously, the function label
  14547. needs to be converted to an address using the \code{leaq}
  14548. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14549. needs to be classified as a complex expression so that we generate an
  14550. assignment statement with a left-hand side that can serve as the
  14551. target of the \code{leaq}.
  14552. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14553. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14554. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14555. and augments programs to include a list of function definitions.
  14556. %
  14557. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14558. \newcommand{\LfunMonadASTRacket}{
  14559. \begin{array}{lcl}
  14560. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14561. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14562. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14563. \end{array}
  14564. }
  14565. \newcommand{\LfunMonadASTPython}{
  14566. \begin{array}{lcl}
  14567. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14568. \MID \key{TupleType}\LS\Type^+\RS\\
  14569. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14570. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14571. \Stmt &::=& \RETURN{\Exp} \\
  14572. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14573. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14574. \end{array}
  14575. }
  14576. \begin{figure}[tp]
  14577. \centering
  14578. \begin{tcolorbox}[colback=white]
  14579. \footnotesize
  14580. {\if\edition\racketEd
  14581. \[
  14582. \begin{array}{l}
  14583. \gray{\LvarMonadASTRacket} \\ \hline
  14584. \gray{\LifMonadASTRacket} \\ \hline
  14585. \gray{\LwhileMonadASTRacket} \\ \hline
  14586. \gray{\LtupMonadASTRacket} \\ \hline
  14587. \LfunMonadASTRacket \\
  14588. \begin{array}{rcl}
  14589. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14590. \end{array}
  14591. \end{array}
  14592. \]
  14593. \fi}
  14594. {\if\edition\pythonEd\pythonColor
  14595. \[
  14596. \begin{array}{l}
  14597. \gray{\LvarMonadASTPython} \\ \hline
  14598. \gray{\LifMonadASTPython} \\ \hline
  14599. \gray{\LwhileMonadASTPython} \\ \hline
  14600. \gray{\LtupMonadASTPython} \\ \hline
  14601. \LfunMonadASTPython \\
  14602. \begin{array}{rcl}
  14603. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14604. \end{array}
  14605. \end{array}
  14606. \]
  14607. \fi}
  14608. \end{tcolorbox}
  14609. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14610. \label{fig:Lfun-anf-syntax}
  14611. \end{figure}
  14612. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14613. %% \LangFunANF{} of this pass.
  14614. %% \begin{figure}[tp]
  14615. %% \centering
  14616. %% \fbox{
  14617. %% \begin{minipage}{0.96\textwidth}
  14618. %% \small
  14619. %% \[
  14620. %% \begin{array}{rcl}
  14621. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14622. %% \MID \VOID{} } \\
  14623. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14624. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14625. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14626. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14627. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14628. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14629. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14630. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14631. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14632. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14633. %% \end{array}
  14634. %% \]
  14635. %% \end{minipage}
  14636. %% }
  14637. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14638. %% \label{fig:Lfun-anf-syntax}
  14639. %% \end{figure}
  14640. \section{Explicate Control and the \LangCFun{} Language}
  14641. \label{sec:explicate-control-r4}
  14642. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14643. output of \code{explicate\_control}.
  14644. %
  14645. %% \racket{(The concrete syntax is given in
  14646. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14647. %
  14648. The auxiliary functions for assignment\racket{ and tail contexts} should
  14649. be updated with cases for
  14650. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14651. function for predicate context should be updated for
  14652. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14653. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14654. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14655. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14656. auxiliary function for processing function definitions. This code is
  14657. similar to the case for \code{Program} in \LangVec{}. The top-level
  14658. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14659. form of \LangFun{} can then apply this new function to all the
  14660. function definitions.
  14661. {\if\edition\pythonEd\pythonColor
  14662. The translation of \code{Return} statements requires a new auxiliary
  14663. function to handle expressions in tail context, called
  14664. \code{explicate\_tail}. The function should take an expression and the
  14665. dictionary of basic blocks and produce a list of statements in the
  14666. \LangCFun{} language. The \code{explicate\_tail} function should
  14667. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14668. and a default case for other kinds of expressions. The default case
  14669. should produce a \code{Return} statement. The case for \code{Call}
  14670. should change it into \code{TailCall}. The other cases should
  14671. recursively process their subexpressions and statements, choosing the
  14672. appropriate explicate functions for the various contexts.
  14673. \fi}
  14674. \newcommand{\CfunASTRacket}{
  14675. \begin{array}{lcl}
  14676. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14677. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14678. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14679. \end{array}
  14680. }
  14681. \newcommand{\CfunASTPython}{
  14682. \begin{array}{lcl}
  14683. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14684. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14685. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14686. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14687. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14688. \end{array}
  14689. }
  14690. \begin{figure}[tp]
  14691. \begin{tcolorbox}[colback=white]
  14692. \footnotesize
  14693. {\if\edition\racketEd
  14694. \[
  14695. \begin{array}{l}
  14696. \gray{\CvarASTRacket} \\ \hline
  14697. \gray{\CifASTRacket} \\ \hline
  14698. \gray{\CloopASTRacket} \\ \hline
  14699. \gray{\CtupASTRacket} \\ \hline
  14700. \CfunASTRacket \\
  14701. \begin{array}{lcl}
  14702. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14703. \end{array}
  14704. \end{array}
  14705. \]
  14706. \fi}
  14707. {\if\edition\pythonEd\pythonColor
  14708. \[
  14709. \begin{array}{l}
  14710. \gray{\CifASTPython} \\ \hline
  14711. \gray{\CtupASTPython} \\ \hline
  14712. \CfunASTPython \\
  14713. \begin{array}{lcl}
  14714. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14715. \end{array}
  14716. \end{array}
  14717. \]
  14718. \fi}
  14719. \end{tcolorbox}
  14720. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14721. \label{fig:c3-syntax}
  14722. \end{figure}
  14723. \clearpage
  14724. \section{Select Instructions and the \LangXIndCall{} Language}
  14725. \label{sec:select-r4}
  14726. \index{subject}{select instructions}
  14727. The output of select instructions is a program in the \LangXIndCall{}
  14728. language; the definition of its concrete syntax is shown in
  14729. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14730. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14731. directive on the labels of function definitions to make sure the
  14732. bottom three bits are zero, which we put to use in
  14733. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14734. this section. \index{subject}{x86}
  14735. \newcommand{\GrammarXIndCall}{
  14736. \begin{array}{lcl}
  14737. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14738. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14739. \Block &::= & \Instr^{+} \\
  14740. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14741. \end{array}
  14742. }
  14743. \newcommand{\ASTXIndCallRacket}{
  14744. \begin{array}{lcl}
  14745. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14746. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14747. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14748. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14749. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14750. \end{array}
  14751. }
  14752. \begin{figure}[tp]
  14753. \begin{tcolorbox}[colback=white]
  14754. \small
  14755. \[
  14756. \begin{array}{l}
  14757. \gray{\GrammarXInt} \\ \hline
  14758. \gray{\GrammarXIf} \\ \hline
  14759. \gray{\GrammarXGlobal} \\ \hline
  14760. \GrammarXIndCall \\
  14761. \begin{array}{lcl}
  14762. \LangXIndCallM{} &::= & \Def^{*}
  14763. \end{array}
  14764. \end{array}
  14765. \]
  14766. \end{tcolorbox}
  14767. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14768. \label{fig:x86-3-concrete}
  14769. \end{figure}
  14770. \begin{figure}[tp]
  14771. \begin{tcolorbox}[colback=white]
  14772. \small
  14773. {\if\edition\racketEd
  14774. \[\arraycolsep=3pt
  14775. \begin{array}{l}
  14776. \gray{\ASTXIntRacket} \\ \hline
  14777. \gray{\ASTXIfRacket} \\ \hline
  14778. \gray{\ASTXGlobalRacket} \\ \hline
  14779. \ASTXIndCallRacket \\
  14780. \begin{array}{lcl}
  14781. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14782. \end{array}
  14783. \end{array}
  14784. \]
  14785. \fi}
  14786. {\if\edition\pythonEd\pythonColor
  14787. \[
  14788. \begin{array}{lcl}
  14789. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14790. \MID \BYTEREG{\Reg} } \\
  14791. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14792. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14793. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14794. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14795. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14796. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14797. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14798. \end{array}
  14799. \]
  14800. \fi}
  14801. \end{tcolorbox}
  14802. \caption{The abstract syntax of \LangXIndCall{} (extends
  14803. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14804. \label{fig:x86-3}
  14805. \end{figure}
  14806. An assignment of a function reference to a variable becomes a
  14807. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14808. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14809. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14810. node, whose concrete syntax is instruction-pointer-relative
  14811. addressing.
  14812. \begin{center}
  14813. \begin{tabular}{lcl}
  14814. \begin{minipage}{0.35\textwidth}
  14815. {\if\edition\racketEd
  14816. \begin{lstlisting}
  14817. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14818. \end{lstlisting}
  14819. \fi}
  14820. {\if\edition\pythonEd\pythonColor
  14821. \begin{lstlisting}
  14822. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14823. \end{lstlisting}
  14824. \fi}
  14825. \end{minipage}
  14826. &
  14827. $\Rightarrow$\qquad\qquad
  14828. &
  14829. \begin{minipage}{0.3\textwidth}
  14830. \begin{lstlisting}
  14831. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14832. \end{lstlisting}
  14833. \end{minipage}
  14834. \end{tabular}
  14835. \end{center}
  14836. Regarding function definitions, we need to remove the parameters and
  14837. instead perform parameter passing using the conventions discussed in
  14838. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14839. registers. We recommend turning the parameters into local variables
  14840. and generating instructions at the beginning of the function to move
  14841. from the argument-passing registers
  14842. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14843. {\if\edition\racketEd
  14844. \begin{lstlisting}
  14845. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14846. |$\Rightarrow$|
  14847. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14848. \end{lstlisting}
  14849. \fi}
  14850. {\if\edition\pythonEd\pythonColor
  14851. \begin{lstlisting}
  14852. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14853. |$\Rightarrow$|
  14854. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14855. \end{lstlisting}
  14856. \fi}
  14857. The basic blocks $B'$ are the same as $B$ except that the
  14858. \code{start} block is modified to add the instructions for moving from
  14859. the argument registers to the parameter variables. So the \code{start}
  14860. block of $B$ shown on the left of the following is changed to the code
  14861. on the right:
  14862. \begin{center}
  14863. \begin{minipage}{0.3\textwidth}
  14864. \begin{lstlisting}
  14865. start:
  14866. |$\itm{instr}_1$|
  14867. |$\cdots$|
  14868. |$\itm{instr}_n$|
  14869. \end{lstlisting}
  14870. \end{minipage}
  14871. $\Rightarrow$
  14872. \begin{minipage}{0.3\textwidth}
  14873. \begin{lstlisting}
  14874. |$f$|start:
  14875. movq %rdi, |$x_1$|
  14876. movq %rsi, |$x_2$|
  14877. |$\cdots$|
  14878. |$\itm{instr}_1$|
  14879. |$\cdots$|
  14880. |$\itm{instr}_n$|
  14881. \end{lstlisting}
  14882. \end{minipage}
  14883. \end{center}
  14884. Recall that we use the label \code{start} for the initial block of a
  14885. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14886. the conclusion of the program with \code{conclusion}, so that
  14887. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14888. by a jump to \code{conclusion}. With the addition of function
  14889. definitions, there is a start block and conclusion for each function,
  14890. but their labels need to be unique. We recommend prepending the
  14891. function's name to \code{start} and \code{conclusion}, respectively,
  14892. to obtain unique labels.
  14893. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14894. number of parameters the function expects, but the parameters are no
  14895. longer in the syntax of function definitions. Instead, add an entry
  14896. to $\itm{info}$ that maps \code{num-params} to the number of
  14897. parameters to construct $\itm{info}'$.}
  14898. By changing the parameters to local variables, we are giving the
  14899. register allocator control over which registers or stack locations to
  14900. use for them. If you implement the move-biasing challenge
  14901. (section~\ref{sec:move-biasing}), the register allocator will try to
  14902. assign the parameter variables to the corresponding argument register,
  14903. in which case the \code{patch\_instructions} pass will remove the
  14904. \code{movq} instruction. This happens in the example translation given
  14905. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14906. the \code{add} function.
  14907. %
  14908. Also, note that the register allocator will perform liveness analysis
  14909. on this sequence of move instructions and build the interference
  14910. graph. So, for example, $x_1$ will be marked as interfering with
  14911. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14912. which is good because otherwise the first \code{movq} would overwrite
  14913. the argument in \code{rsi} that is needed for $x_2$.
  14914. Next, consider the compilation of function calls. In the mirror image
  14915. of the handling of parameters in function definitions, the arguments
  14916. are moved to the argument-passing registers. Note that the function
  14917. is not given as a label, but its address is produced by the argument
  14918. $\itm{arg}_0$. So, we translate the call into an indirect function
  14919. call. The return value from the function is stored in \code{rax}, so
  14920. it needs to be moved into the \itm{lhs}.
  14921. \begin{lstlisting}
  14922. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14923. |$\Rightarrow$|
  14924. movq |$\itm{arg}_1$|, %rdi
  14925. movq |$\itm{arg}_2$|, %rsi
  14926. |$\vdots$|
  14927. callq *|$\itm{arg}_0$|
  14928. movq %rax, |$\itm{lhs}$|
  14929. \end{lstlisting}
  14930. The \code{IndirectCallq} AST node includes an integer for the arity of
  14931. the function, that is, the number of parameters. That information is
  14932. useful in the \code{uncover\_live} pass for determining which
  14933. argument-passing registers are potentially read during the call.
  14934. For tail calls, the parameter passing is the same as non-tail calls:
  14935. generate instructions to move the arguments into the argument-passing
  14936. registers. After that we need to pop the frame from the procedure
  14937. call stack. However, we do not yet know how big the frame is; that
  14938. gets determined during register allocation. So, instead of generating
  14939. those instructions here, we invent a new instruction that means ``pop
  14940. the frame and then do an indirect jump,'' which we name
  14941. \code{TailJmp}. The abstract syntax for this instruction includes an
  14942. argument that specifies where to jump and an integer that represents
  14943. the arity of the function being called.
  14944. \section{Register Allocation}
  14945. \label{sec:register-allocation-r4}
  14946. The addition of functions requires some changes to all three aspects
  14947. of register allocation, which we discuss in the following subsections.
  14948. \subsection{Liveness Analysis}
  14949. \label{sec:liveness-analysis-r4}
  14950. \index{subject}{liveness analysis}
  14951. %% The rest of the passes need only minor modifications to handle the new
  14952. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14953. %% \code{leaq}.
  14954. The \code{IndirectCallq} instruction should be treated like
  14955. \code{Callq} regarding its written locations $W$, in that they should
  14956. include all the caller-saved registers. Recall that the reason for
  14957. that is to force variables that are live across a function call to be assigned to callee-saved
  14958. registers or to be spilled to the stack.
  14959. Regarding the set of read locations $R$, the arity fields of
  14960. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14961. argument-passing registers should be considered as read by those
  14962. instructions. Also, the target field of \code{TailJmp} and
  14963. \code{IndirectCallq} should be included in the set of read locations
  14964. $R$.
  14965. \subsection{Build Interference Graph}
  14966. \label{sec:build-interference-r4}
  14967. With the addition of function definitions, we compute a separate interference
  14968. graph for each function (not just one for the whole program).
  14969. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14970. spill tuple-typed variables that are live during a call to
  14971. \code{collect}, the garbage collector. With the addition of functions
  14972. to our language, we need to revisit this issue. Functions that perform
  14973. allocation contain calls to the collector. Thus, we should not only
  14974. spill a tuple-typed variable when it is live during a call to
  14975. \code{collect}, but we should spill the variable if it is live during
  14976. a call to any user-defined function. Thus, in the
  14977. \code{build\_interference} pass, we recommend adding interference
  14978. edges between call-live tuple-typed variables and the callee-saved
  14979. registers (in addition to creating edges between
  14980. call-live variables and the caller-saved registers).
  14981. \subsection{Allocate Registers}
  14982. The primary change to the \code{allocate\_registers} pass is adding an
  14983. auxiliary function for handling definitions (the \Def{} nonterminal
  14984. shown in figure~\ref{fig:x86-3}) with one case for function
  14985. definitions. The logic is the same as described in
  14986. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14987. allocation is performed many times, once for each function definition,
  14988. instead of just once for the whole program.
  14989. \section{Patch Instructions}
  14990. In \code{patch\_instructions}, you should deal with the x86
  14991. idiosyncrasy that the destination argument of \code{leaq} must be a
  14992. register. Additionally, you should ensure that the argument of
  14993. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14994. trample many other registers before the tail call, as explained in the
  14995. next section.
  14996. \section{Generate Prelude and Conclusion}
  14997. Now that register allocation is complete, we can translate the
  14998. \code{TailJmp} into a sequence of instructions. A naive translation of
  14999. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15000. before the jump we need to pop the current frame to achieve efficient
  15001. tail calls. This sequence of instructions is the same as the code for
  15002. the conclusion of a function, except that the \code{retq} is replaced with
  15003. \code{jmp *$\itm{arg}$}.
  15004. Regarding function definitions, we generate a prelude and conclusion
  15005. for each one. This code is similar to the prelude and conclusion
  15006. generated for the \code{main} function presented in
  15007. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15008. carry out the following steps:
  15009. % TODO: .align the functions!
  15010. \begin{enumerate}
  15011. %% \item Start with \code{.global} and \code{.align} directives followed
  15012. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15013. %% example.)
  15014. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15015. pointer.
  15016. \item Push to the stack all the callee-saved registers that were
  15017. used for register allocation.
  15018. \item Move the stack pointer \code{rsp} down to make room for the
  15019. regular spills (aligned to 16 bytes).
  15020. \item Move the root stack pointer \code{r15} up by the size of the
  15021. root-stack frame for this function, which depends on the number of
  15022. spilled tuple-typed variables. \label{root-stack-init}
  15023. \item Initialize to zero all new entries in the root-stack frame.
  15024. \item Jump to the start block.
  15025. \end{enumerate}
  15026. The prelude of the \code{main} function has an additional task: call
  15027. the \code{initialize} function to set up the garbage collector, and
  15028. then move the value of the global \code{rootstack\_begin} in
  15029. \code{r15}. This initialization should happen before step
  15030. \ref{root-stack-init}, which depends on \code{r15}.
  15031. The conclusion of every function should do the following:
  15032. \begin{enumerate}
  15033. \item Move the stack pointer back up past the regular spills.
  15034. \item Restore the callee-saved registers by popping them from the
  15035. stack.
  15036. \item Move the root stack pointer back down by the size of the
  15037. root-stack frame for this function.
  15038. \item Restore \code{rbp} by popping it from the stack.
  15039. \item Return to the caller with the \code{retq} instruction.
  15040. \end{enumerate}
  15041. The output of this pass is \LangXIndCallFlat{}, which differs from
  15042. \LangXIndCall{} in that there is no longer an AST node for function
  15043. definitions. Instead, a program is just
  15044. \racket{an association list}\python{dictionary}
  15045. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15046. {\if\edition\racketEd
  15047. \[
  15048. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15049. \]
  15050. \fi}
  15051. {\if\edition\pythonEd
  15052. \[
  15053. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15054. \]
  15055. \fi}
  15056. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15057. compiling \LangFun{} to x86.
  15058. \begin{exercise}\normalfont\normalsize
  15059. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15060. Create eight new programs that use functions including examples that
  15061. pass functions and return functions from other functions, recursive
  15062. functions, functions that create tuples, and functions that make tail
  15063. calls. Test your compiler on these new programs and all your
  15064. previously created test programs.
  15065. \end{exercise}
  15066. \begin{figure}[tbp]
  15067. \begin{tcolorbox}[colback=white]
  15068. {\if\edition\racketEd
  15069. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15070. \node (Lfun) at (0,2) {\large \LangFun{}};
  15071. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15072. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15073. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15074. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15075. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15076. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15077. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15078. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15079. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15080. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15081. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15082. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15083. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15084. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15085. \path[->,bend left=15] (Lfun) edge [above] node
  15086. {\ttfamily\footnotesize shrink} (Lfun-1);
  15087. \path[->,bend left=15] (Lfun-1) edge [above] node
  15088. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15089. \path[->,bend left=15] (Lfun-2) edge [above] node
  15090. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15091. \path[->,bend left=15] (F1-1) edge [left] node
  15092. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15093. \path[->,bend left=15] (F1-2) edge [below] node
  15094. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15095. \path[->,bend left=15] (F1-3) edge [below] node
  15096. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15097. \path[->,bend right=15] (F1-4) edge [above] node
  15098. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15099. \path[->,bend right=15] (F1-5) edge [right] node
  15100. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15101. \path[->,bend right=15] (C3-2) edge [right] node
  15102. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15103. \path[->,bend left=15] (x86-2) edge [right] node
  15104. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15105. \path[->,bend right=15] (x86-2-1) edge [below] node
  15106. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15107. \path[->,bend right=15] (x86-2-2) edge [right] node
  15108. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15109. \path[->,bend left=15] (x86-3) edge [above] node
  15110. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15111. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15112. \end{tikzpicture}
  15113. \fi}
  15114. {\if\edition\pythonEd\pythonColor
  15115. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15116. \node (Lfun) at (0,2) {\large \LangFun{}};
  15117. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15118. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15119. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15120. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15121. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15122. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15123. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15124. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15125. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15126. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15127. \path[->,bend left=15] (Lfun) edge [above] node
  15128. {\ttfamily\footnotesize shrink} (Lfun-2);
  15129. \path[->,bend left=15] (Lfun-2) edge [above] node
  15130. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15131. \path[->,bend left=15] (F1-1) edge [above] node
  15132. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15133. \path[->,bend left=15] (F1-2) edge [right] node
  15134. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15135. \path[->,bend right=15] (F1-4) edge [above] node
  15136. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15137. \path[->,bend right=15] (F1-5) edge [right] node
  15138. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15139. \path[->,bend left=15] (C3-2) edge [right] node
  15140. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15141. \path[->,bend right=15] (x86-2) edge [below] node
  15142. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15143. \path[->,bend left=15] (x86-3) edge [above] node
  15144. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15145. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15146. \end{tikzpicture}
  15147. \fi}
  15148. \end{tcolorbox}
  15149. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15150. \label{fig:Lfun-passes}
  15151. \end{figure}
  15152. \section{An Example Translation}
  15153. \label{sec:functions-example}
  15154. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15155. function in \LangFun{} to x86. The figure includes the results of
  15156. \code{explicate\_control} and \code{select\_instructions}.
  15157. \begin{figure}[hbtp]
  15158. \begin{tcolorbox}[colback=white]
  15159. \begin{tabular}{ll}
  15160. \begin{minipage}{0.4\textwidth}
  15161. % s3_2.rkt
  15162. {\if\edition\racketEd
  15163. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15164. (define (add [x : Integer]
  15165. [y : Integer])
  15166. : Integer
  15167. (+ x y))
  15168. (add 40 2)
  15169. \end{lstlisting}
  15170. \fi}
  15171. {\if\edition\pythonEd\pythonColor
  15172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15173. def add(x:int, y:int) -> int:
  15174. return x + y
  15175. print(add(40, 2))
  15176. \end{lstlisting}
  15177. \fi}
  15178. $\Downarrow$
  15179. {\if\edition\racketEd
  15180. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15181. (define (add86 [x87 : Integer]
  15182. [y88 : Integer])
  15183. : Integer
  15184. add86start:
  15185. return (+ x87 y88);
  15186. )
  15187. (define (main) : Integer ()
  15188. mainstart:
  15189. tmp89 = (fun-ref add86 2);
  15190. (tail-call tmp89 40 2)
  15191. )
  15192. \end{lstlisting}
  15193. \fi}
  15194. {\if\edition\pythonEd\pythonColor
  15195. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15196. def add(x:int, y:int) -> int:
  15197. addstart:
  15198. return x + y
  15199. def main() -> int:
  15200. mainstart:
  15201. fun.0 = add
  15202. tmp.1 = fun.0(40, 2)
  15203. print(tmp.1)
  15204. return 0
  15205. \end{lstlisting}
  15206. \fi}
  15207. \end{minipage}
  15208. &
  15209. $\Rightarrow$
  15210. \begin{minipage}{0.5\textwidth}
  15211. {\if\edition\racketEd
  15212. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15213. (define (add86) : Integer
  15214. add86start:
  15215. movq %rdi, x87
  15216. movq %rsi, y88
  15217. movq x87, %rax
  15218. addq y88, %rax
  15219. jmp inc1389conclusion
  15220. )
  15221. (define (main) : Integer
  15222. mainstart:
  15223. leaq (fun-ref add86 2), tmp89
  15224. movq $40, %rdi
  15225. movq $2, %rsi
  15226. tail-jmp tmp89
  15227. )
  15228. \end{lstlisting}
  15229. \fi}
  15230. {\if\edition\pythonEd\pythonColor
  15231. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15232. def add() -> int:
  15233. addstart:
  15234. movq %rdi, x
  15235. movq %rsi, y
  15236. movq x, %rax
  15237. addq y, %rax
  15238. jmp addconclusion
  15239. def main() -> int:
  15240. mainstart:
  15241. leaq add, fun.0
  15242. movq $40, %rdi
  15243. movq $2, %rsi
  15244. callq *fun.0
  15245. movq %rax, tmp.1
  15246. movq tmp.1, %rdi
  15247. callq print_int
  15248. movq $0, %rax
  15249. jmp mainconclusion
  15250. \end{lstlisting}
  15251. \fi}
  15252. $\Downarrow$
  15253. \end{minipage}
  15254. \end{tabular}
  15255. \begin{tabular}{ll}
  15256. \begin{minipage}{0.3\textwidth}
  15257. {\if\edition\racketEd
  15258. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15259. .globl add86
  15260. .align 8
  15261. add86:
  15262. pushq %rbp
  15263. movq %rsp, %rbp
  15264. jmp add86start
  15265. add86start:
  15266. movq %rdi, %rax
  15267. addq %rsi, %rax
  15268. jmp add86conclusion
  15269. add86conclusion:
  15270. popq %rbp
  15271. retq
  15272. \end{lstlisting}
  15273. \fi}
  15274. {\if\edition\pythonEd\pythonColor
  15275. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15276. .align 8
  15277. add:
  15278. pushq %rbp
  15279. movq %rsp, %rbp
  15280. subq $0, %rsp
  15281. jmp addstart
  15282. addstart:
  15283. movq %rdi, %rdx
  15284. movq %rsi, %rcx
  15285. movq %rdx, %rax
  15286. addq %rcx, %rax
  15287. jmp addconclusion
  15288. addconclusion:
  15289. subq $0, %r15
  15290. addq $0, %rsp
  15291. popq %rbp
  15292. retq
  15293. \end{lstlisting}
  15294. \fi}
  15295. \end{minipage}
  15296. &
  15297. \begin{minipage}{0.5\textwidth}
  15298. {\if\edition\racketEd
  15299. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15300. .globl main
  15301. .align 8
  15302. main:
  15303. pushq %rbp
  15304. movq %rsp, %rbp
  15305. movq $16384, %rdi
  15306. movq $16384, %rsi
  15307. callq initialize
  15308. movq rootstack_begin(%rip), %r15
  15309. jmp mainstart
  15310. mainstart:
  15311. leaq add86(%rip), %rcx
  15312. movq $40, %rdi
  15313. movq $2, %rsi
  15314. movq %rcx, %rax
  15315. popq %rbp
  15316. jmp *%rax
  15317. mainconclusion:
  15318. popq %rbp
  15319. retq
  15320. \end{lstlisting}
  15321. \fi}
  15322. {\if\edition\pythonEd\pythonColor
  15323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15324. .globl main
  15325. .align 8
  15326. main:
  15327. pushq %rbp
  15328. movq %rsp, %rbp
  15329. subq $0, %rsp
  15330. movq $65536, %rdi
  15331. movq $65536, %rsi
  15332. callq initialize
  15333. movq rootstack_begin(%rip), %r15
  15334. jmp mainstart
  15335. mainstart:
  15336. leaq add(%rip), %rcx
  15337. movq $40, %rdi
  15338. movq $2, %rsi
  15339. callq *%rcx
  15340. movq %rax, %rcx
  15341. movq %rcx, %rdi
  15342. callq print_int
  15343. movq $0, %rax
  15344. jmp mainconclusion
  15345. mainconclusion:
  15346. subq $0, %r15
  15347. addq $0, %rsp
  15348. popq %rbp
  15349. retq
  15350. \end{lstlisting}
  15351. \fi}
  15352. \end{minipage}
  15353. \end{tabular}
  15354. \end{tcolorbox}
  15355. \caption{Example compilation of a simple function to x86.}
  15356. \label{fig:add-fun}
  15357. \end{figure}
  15358. % Challenge idea: inlining! (simple version)
  15359. % Further Reading
  15360. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15361. \chapter{Lexically Scoped Functions}
  15362. \label{ch:Llambda}
  15363. \setcounter{footnote}{0}
  15364. This chapter studies lexically scoped functions. Lexical
  15365. scoping\index{subject}{lexical scoping} means that a function's body
  15366. may refer to variables whose binding site is outside of the function,
  15367. in an enclosing scope.
  15368. %
  15369. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15370. in \LangLam{}, which extends \LangFun{} with the
  15371. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15372. functions. The body of the \key{lambda} refers to three variables:
  15373. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15374. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15375. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15376. function \code{f}}, and \code{x} is a parameter of function
  15377. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15378. result value. The main expression of the program includes two calls to
  15379. \code{f} with different arguments for \code{x}: first \code{5} and
  15380. then \code{3}. The functions returned from \code{f} are bound to
  15381. variables \code{g} and \code{h}. Even though these two functions were
  15382. created by the same \code{lambda}, they are really different functions
  15383. because they use different values for \code{x}. Applying \code{g} to
  15384. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15385. produces \code{22}, so the result of the program is \code{42}.
  15386. \begin{figure}[btp]
  15387. \begin{tcolorbox}[colback=white]
  15388. {\if\edition\racketEd
  15389. % lambda_test_21.rkt
  15390. \begin{lstlisting}
  15391. (define (f [x : Integer]) : (Integer -> Integer)
  15392. (let ([y 4])
  15393. (lambda: ([z : Integer]) : Integer
  15394. (+ x (+ y z)))))
  15395. (let ([g (f 5)])
  15396. (let ([h (f 3)])
  15397. (+ (g 11) (h 15))))
  15398. \end{lstlisting}
  15399. \fi}
  15400. {\if\edition\pythonEd\pythonColor
  15401. \begin{lstlisting}
  15402. def f(x : int) -> Callable[[int], int]:
  15403. y = 4
  15404. return lambda z: x + y + z
  15405. g = f(5)
  15406. h = f(3)
  15407. print(g(11) + h(15))
  15408. \end{lstlisting}
  15409. \fi}
  15410. \end{tcolorbox}
  15411. \caption{Example of a lexically scoped function.}
  15412. \label{fig:lexical-scoping}
  15413. \end{figure}
  15414. The approach that we take for implementing lexically scoped functions
  15415. is to compile them into top-level function definitions, translating
  15416. from \LangLam{} into \LangFun{}. However, the compiler must give
  15417. special treatment to variable occurrences such as \code{x} and
  15418. \code{y} in the body of the \code{lambda} shown in
  15419. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15420. may not refer to variables defined outside of it. To identify such
  15421. variable occurrences, we review the standard notion of free variable.
  15422. \begin{definition}\normalfont
  15423. A variable is \emph{free in expression} $e$ if the variable occurs
  15424. inside $e$ but does not have an enclosing definition that is also in
  15425. $e$.\index{subject}{free variable}
  15426. \end{definition}
  15427. For example, in the expression
  15428. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15429. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15430. only \code{x} and \code{y} are free in the following expression,
  15431. because \code{z} is defined by the \code{lambda}
  15432. {\if\edition\racketEd
  15433. \begin{lstlisting}
  15434. (lambda: ([z : Integer]) : Integer
  15435. (+ x (+ y z)))
  15436. \end{lstlisting}
  15437. \fi}
  15438. {\if\edition\pythonEd\pythonColor
  15439. \begin{lstlisting}
  15440. lambda z: x + y + z
  15441. \end{lstlisting}
  15442. \fi}
  15443. %
  15444. \noindent Thus the free variables of a \code{lambda} are the ones that
  15445. need special treatment. We need to transport at runtime the values
  15446. of those variables from the point where the \code{lambda} was created
  15447. to the point where the \code{lambda} is applied. An efficient solution
  15448. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15449. values of the free variables together with a function pointer into a
  15450. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15451. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15452. closure}
  15453. %
  15454. By design, we have all the ingredients to make closures:
  15455. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15456. function pointers. The function pointer resides at index $0$, and the
  15457. values for the free variables fill in the rest of the tuple.
  15458. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15459. to see how closures work. It is a three-step dance. The program calls
  15460. function \code{f}, which creates a closure for the \code{lambda}. The
  15461. closure is a tuple whose first element is a pointer to the top-level
  15462. function that we will generate for the \code{lambda}; the second
  15463. element is the value of \code{x}, which is \code{5}; and the third
  15464. element is \code{4}, the value of \code{y}. The closure does not
  15465. contain an element for \code{z} because \code{z} is not a free
  15466. variable of the \code{lambda}. Creating the closure is step 1 of the
  15467. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15468. shown in figure~\ref{fig:closures}.
  15469. %
  15470. The second call to \code{f} creates another closure, this time with
  15471. \code{3} in the second slot (for \code{x}). This closure is also
  15472. returned from \code{f} but bound to \code{h}, which is also shown in
  15473. figure~\ref{fig:closures}.
  15474. \begin{figure}[tbp]
  15475. \centering
  15476. \begin{minipage}{0.65\textwidth}
  15477. \begin{tcolorbox}[colback=white]
  15478. \includegraphics[width=\textwidth]{figs/closures}
  15479. \end{tcolorbox}
  15480. \end{minipage}
  15481. \caption{Flat closure representations for the two functions
  15482. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15483. \label{fig:closures}
  15484. \end{figure}
  15485. Continuing with the example, consider the application of \code{g} to
  15486. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15487. closure, we obtain the function pointer from the first element of the
  15488. closure and call it, passing in the closure itself and then the
  15489. regular arguments, in this case \code{11}. This technique for applying
  15490. a closure is step 2 of the dance.
  15491. %
  15492. But doesn't this \code{lambda} take only one argument, for parameter
  15493. \code{z}? The third and final step of the dance is generating a
  15494. top-level function for a \code{lambda}. We add an additional
  15495. parameter for the closure and insert an initialization at the beginning
  15496. of the function for each free variable, to bind those variables to the
  15497. appropriate elements from the closure parameter.
  15498. %
  15499. This three-step dance is known as \emph{closure
  15500. conversion}\index{subject}{closure conversion}. We discuss the
  15501. details of closure conversion in section~\ref{sec:closure-conversion}
  15502. and show the code generated from the example in
  15503. section~\ref{sec:example-lambda}. First, we define the syntax and
  15504. semantics of \LangLam{} in section~\ref{sec:r5}.
  15505. \section{The \LangLam{} Language}
  15506. \label{sec:r5}
  15507. The definitions of the concrete syntax and abstract syntax for
  15508. \LangLam{}, a language with anonymous functions and lexical scoping,
  15509. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15510. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15511. for \LangFun{}, which already has syntax for function application.
  15512. %
  15513. \python{The syntax also includes an assignment statement that includes
  15514. a type annotation for the variable on the left-hand side, which
  15515. facilitates the type checking of \code{lambda} expressions that we
  15516. discuss later in this section.}
  15517. %
  15518. \racket{The \code{procedure-arity} operation returns the number of parameters
  15519. of a given function, an operation that we need for the translation
  15520. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15521. %
  15522. \python{The \code{arity} operation returns the number of parameters of
  15523. a given function, an operation that we need for the translation
  15524. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15525. The \code{arity} operation is not in Python, but the same functionality
  15526. is available in a more complex form. We include \code{arity} in the
  15527. \LangLam{} source language to enable testing.}
  15528. \newcommand{\LlambdaGrammarRacket}{
  15529. \begin{array}{lcl}
  15530. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15531. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15532. \end{array}
  15533. }
  15534. \newcommand{\LlambdaASTRacket}{
  15535. \begin{array}{lcl}
  15536. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15537. \itm{op} &::=& \code{procedure-arity}
  15538. \end{array}
  15539. }
  15540. \newcommand{\LlambdaGrammarPython}{
  15541. \begin{array}{lcl}
  15542. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15543. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15544. \end{array}
  15545. }
  15546. \newcommand{\LlambdaASTPython}{
  15547. \begin{array}{lcl}
  15548. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15549. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15550. \end{array}
  15551. }
  15552. % include AnnAssign in ASTPython
  15553. \begin{figure}[tp]
  15554. \centering
  15555. \begin{tcolorbox}[colback=white]
  15556. \small
  15557. {\if\edition\racketEd
  15558. \[
  15559. \begin{array}{l}
  15560. \gray{\LintGrammarRacket{}} \\ \hline
  15561. \gray{\LvarGrammarRacket{}} \\ \hline
  15562. \gray{\LifGrammarRacket{}} \\ \hline
  15563. \gray{\LwhileGrammarRacket} \\ \hline
  15564. \gray{\LtupGrammarRacket} \\ \hline
  15565. \gray{\LfunGrammarRacket} \\ \hline
  15566. \LlambdaGrammarRacket \\
  15567. \begin{array}{lcl}
  15568. \LangLamM{} &::=& \Def\ldots \; \Exp
  15569. \end{array}
  15570. \end{array}
  15571. \]
  15572. \fi}
  15573. {\if\edition\pythonEd\pythonColor
  15574. \[
  15575. \begin{array}{l}
  15576. \gray{\LintGrammarPython{}} \\ \hline
  15577. \gray{\LvarGrammarPython{}} \\ \hline
  15578. \gray{\LifGrammarPython{}} \\ \hline
  15579. \gray{\LwhileGrammarPython} \\ \hline
  15580. \gray{\LtupGrammarPython} \\ \hline
  15581. \gray{\LfunGrammarPython} \\ \hline
  15582. \LlambdaGrammarPython \\
  15583. \begin{array}{lcl}
  15584. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15585. \end{array}
  15586. \end{array}
  15587. \]
  15588. \fi}
  15589. \end{tcolorbox}
  15590. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15591. with \key{lambda}.}
  15592. \label{fig:Llam-concrete-syntax}
  15593. \end{figure}
  15594. \begin{figure}[tp]
  15595. \centering
  15596. \begin{tcolorbox}[colback=white]
  15597. \small
  15598. {\if\edition\racketEd
  15599. \[\arraycolsep=3pt
  15600. \begin{array}{l}
  15601. \gray{\LintOpAST} \\ \hline
  15602. \gray{\LvarASTRacket{}} \\ \hline
  15603. \gray{\LifASTRacket{}} \\ \hline
  15604. \gray{\LwhileASTRacket{}} \\ \hline
  15605. \gray{\LtupASTRacket{}} \\ \hline
  15606. \gray{\LfunASTRacket} \\ \hline
  15607. \LlambdaASTRacket \\
  15608. \begin{array}{lcl}
  15609. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15610. \end{array}
  15611. \end{array}
  15612. \]
  15613. \fi}
  15614. {\if\edition\pythonEd\pythonColor
  15615. \[
  15616. \begin{array}{l}
  15617. \gray{\LintASTPython} \\ \hline
  15618. \gray{\LvarASTPython{}} \\ \hline
  15619. \gray{\LifASTPython{}} \\ \hline
  15620. \gray{\LwhileASTPython{}} \\ \hline
  15621. \gray{\LtupASTPython{}} \\ \hline
  15622. \gray{\LfunASTPython} \\ \hline
  15623. \LlambdaASTPython \\
  15624. \begin{array}{lcl}
  15625. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15626. \end{array}
  15627. \end{array}
  15628. \]
  15629. \fi}
  15630. \end{tcolorbox}
  15631. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15632. \label{fig:Llam-syntax}
  15633. \end{figure}
  15634. Figure~\ref{fig:interp-Llambda} shows the definitional
  15635. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15636. \key{Lambda} saves the current environment inside the returned
  15637. function value. Recall that during function application, the
  15638. environment stored in the function value, extended with the mapping of
  15639. parameters to argument values, is used to interpret the body of the
  15640. function.
  15641. \begin{figure}[tbp]
  15642. \begin{tcolorbox}[colback=white]
  15643. {\if\edition\racketEd
  15644. \begin{lstlisting}
  15645. (define interp-Llambda-class
  15646. (class interp-Lfun-class
  15647. (super-new)
  15648. (define/override (interp-op op)
  15649. (match op
  15650. ['procedure-arity
  15651. (lambda (v)
  15652. (match v
  15653. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15654. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15655. [else (super interp-op op)]))
  15656. (define/override ((interp-exp env) e)
  15657. (define recur (interp-exp env))
  15658. (match e
  15659. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15660. `(function ,xs ,body ,env)]
  15661. [else ((super interp-exp env) e)]))
  15662. ))
  15663. (define (interp-Llambda p)
  15664. (send (new interp-Llambda-class) interp-program p))
  15665. \end{lstlisting}
  15666. \fi}
  15667. {\if\edition\pythonEd\pythonColor
  15668. \begin{lstlisting}
  15669. class InterpLlambda(InterpLfun):
  15670. def arity(self, v):
  15671. match v:
  15672. case Function(name, params, body, env):
  15673. return len(params)
  15674. case _:
  15675. raise Exception('Llambda arity unexpected ' + repr(v))
  15676. def interp_exp(self, e, env):
  15677. match e:
  15678. case Call(Name('arity'), [fun]):
  15679. f = self.interp_exp(fun, env)
  15680. return self.arity(f)
  15681. case Lambda(params, body):
  15682. return Function('lambda', params, [Return(body)], env)
  15683. case _:
  15684. return super().interp_exp(e, env)
  15685. def interp_stmt(self, s, env, cont):
  15686. match s:
  15687. case AnnAssign(lhs, typ, value, simple):
  15688. env[lhs.id] = self.interp_exp(value, env)
  15689. return self.interp_stmts(cont, env)
  15690. case Pass():
  15691. return self.interp_stmts(cont, env)
  15692. case _:
  15693. return super().interp_stmt(s, env, cont)
  15694. \end{lstlisting}
  15695. \fi}
  15696. \end{tcolorbox}
  15697. \caption{Interpreter for \LangLam{}.}
  15698. \label{fig:interp-Llambda}
  15699. \end{figure}
  15700. {\if\edition\racketEd
  15701. %
  15702. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15703. \key{lambda} form. The body of the \key{lambda} is checked in an
  15704. environment that includes the current environment (because it is
  15705. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15706. require the body's type to match the declared return type.
  15707. %
  15708. \fi}
  15709. {\if\edition\pythonEd\pythonColor
  15710. %
  15711. Figures~\ref{fig:type-check-Llambda} and
  15712. \ref{fig:type-check-Llambda-part2} define the type checker for
  15713. \LangLam{}, which is more complex than one might expect. The reason
  15714. for the added complexity is that the syntax of \key{lambda} does not
  15715. include type annotations for the parameters or return type. Instead
  15716. they must be inferred. There are many approaches to type inference
  15717. from which to choose, of varying degrees of complexity. We choose one
  15718. of the simpler approaches, bidirectional type
  15719. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15720. book is compilation, not type inference.
  15721. The main idea of bidirectional type inference is to add an auxiliary
  15722. function, here named \code{check\_exp}, that takes an expected type
  15723. and checks whether the given expression is of that type. Thus, in
  15724. \code{check\_exp}, type information flows in a top-down manner with
  15725. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15726. function, where type information flows in a primarily bottom-up
  15727. manner.
  15728. %
  15729. The idea then is to use \code{check\_exp} in all the places where we
  15730. already know what the type of an expression should be, such as in the
  15731. \code{return} statement of a top-level function definition or on the
  15732. right-hand side of an annotated assignment statement.
  15733. With regard to \code{lambda}, it is straightforward to check a
  15734. \code{lambda} inside \code{check\_exp} because the expected type
  15735. provides the parameter types and the return type. On the other hand,
  15736. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15737. that we do not allow \code{lambda} in contexts in which we don't already
  15738. know its type. This restriction does not incur a loss of
  15739. expressiveness for \LangLam{} because it is straightforward to modify
  15740. a program to sidestep the restriction, for example, by using an
  15741. annotated assignment statement to assign the \code{lambda} to a
  15742. temporary variable.
  15743. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15744. checker records their type in a \code{has\_type} field. This type
  15745. information is used further on in this chapter.
  15746. %
  15747. \fi}
  15748. \begin{figure}[tbp]
  15749. \begin{tcolorbox}[colback=white]
  15750. {\if\edition\racketEd
  15751. \begin{lstlisting}
  15752. (define (type-check-Llambda env)
  15753. (lambda (e)
  15754. (match e
  15755. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15756. (define-values (new-body bodyT)
  15757. ((type-check-exp (append (map cons xs Ts) env)) body))
  15758. (define ty `(,@Ts -> ,rT))
  15759. (cond
  15760. [(equal? rT bodyT)
  15761. (values (HasType (Lambda params rT new-body) ty) ty)]
  15762. [else
  15763. (error "mismatch in return type" bodyT rT)])]
  15764. ...
  15765. )))
  15766. \end{lstlisting}
  15767. \fi}
  15768. {\if\edition\pythonEd\pythonColor
  15769. \begin{lstlisting}
  15770. class TypeCheckLlambda(TypeCheckLfun):
  15771. def type_check_exp(self, e, env):
  15772. match e:
  15773. case Name(id):
  15774. e.has_type = env[id]
  15775. return env[id]
  15776. case Lambda(params, body):
  15777. raise Exception('cannot synthesize a type for a lambda')
  15778. case Call(Name('arity'), [func]):
  15779. func_t = self.type_check_exp(func, env)
  15780. match func_t:
  15781. case FunctionType(params_t, return_t):
  15782. return IntType()
  15783. case _:
  15784. raise Exception('in arity, unexpected ' + repr(func_t))
  15785. case _:
  15786. return super().type_check_exp(e, env)
  15787. def check_exp(self, e, ty, env):
  15788. match e:
  15789. case Lambda(params, body):
  15790. e.has_type = ty
  15791. match ty:
  15792. case FunctionType(params_t, return_t):
  15793. new_env = env.copy().update(zip(params, params_t))
  15794. self.check_exp(body, return_t, new_env)
  15795. case _:
  15796. raise Exception('lambda does not have type ' + str(ty))
  15797. case Call(func, args):
  15798. func_t = self.type_check_exp(func, env)
  15799. match func_t:
  15800. case FunctionType(params_t, return_t):
  15801. for (arg, param_t) in zip(args, params_t):
  15802. self.check_exp(arg, param_t, env)
  15803. self.check_type_equal(return_t, ty, e)
  15804. case _:
  15805. raise Exception('type_check_exp: in call, unexpected ' + \
  15806. repr(func_t))
  15807. case _:
  15808. t = self.type_check_exp(e, env)
  15809. self.check_type_equal(t, ty, e)
  15810. \end{lstlisting}
  15811. \fi}
  15812. \end{tcolorbox}
  15813. \caption{Type checking \LangLam{}\python{, part 1}.}
  15814. \label{fig:type-check-Llambda}
  15815. \end{figure}
  15816. {\if\edition\pythonEd\pythonColor
  15817. \begin{figure}[tbp]
  15818. \begin{tcolorbox}[colback=white]
  15819. \begin{lstlisting}
  15820. def check_stmts(self, ss, return_ty, env):
  15821. if len(ss) == 0:
  15822. return
  15823. match ss[0]:
  15824. case FunctionDef(name, params, body, dl, returns, comment):
  15825. new_env = env.copy().update(params)
  15826. rt = self.check_stmts(body, returns, new_env)
  15827. self.check_stmts(ss[1:], return_ty, env)
  15828. case Return(value):
  15829. self.check_exp(value, return_ty, env)
  15830. case Assign([Name(id)], value):
  15831. if id in env:
  15832. self.check_exp(value, env[id], env)
  15833. else:
  15834. env[id] = self.type_check_exp(value, env)
  15835. self.check_stmts(ss[1:], return_ty, env)
  15836. case Assign([Subscript(tup, Constant(index), Store())], value):
  15837. tup_t = self.type_check_exp(tup, env)
  15838. match tup_t:
  15839. case TupleType(ts):
  15840. self.check_exp(value, ts[index], env)
  15841. case _:
  15842. raise Exception('expected a tuple, not ' + repr(tup_t))
  15843. self.check_stmts(ss[1:], return_ty, env)
  15844. case AnnAssign(Name(id), ty_annot, value, simple):
  15845. ss[0].annotation = ty_annot
  15846. if id in env:
  15847. self.check_type_equal(env[id], ty_annot)
  15848. else:
  15849. env[id] = ty_annot
  15850. self.check_exp(value, ty_annot, env)
  15851. self.check_stmts(ss[1:], return_ty, env)
  15852. case _:
  15853. self.type_check_stmts(ss, env)
  15854. def type_check(self, p):
  15855. match p:
  15856. case Module(body):
  15857. env = {}
  15858. for s in body:
  15859. match s:
  15860. case FunctionDef(name, params, bod, dl, returns, comment):
  15861. params_t = [t for (x,t) in params]
  15862. env[name] = FunctionType(params_t, returns)
  15863. self.check_stmts(body, int, env)
  15864. \end{lstlisting}
  15865. \end{tcolorbox}
  15866. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15867. \label{fig:type-check-Llambda-part2}
  15868. \end{figure}
  15869. \fi}
  15870. \clearpage
  15871. \section{Assignment and Lexically Scoped Functions}
  15872. \label{sec:assignment-scoping}
  15873. The combination of lexically scoped functions and assignment to
  15874. variables raises a challenge with the flat-closure approach to
  15875. implementing lexically scoped functions. Consider the following
  15876. example in which function \code{f} has a free variable \code{x} that
  15877. is changed after \code{f} is created but before the call to \code{f}.
  15878. % loop_test_11.rkt
  15879. {\if\edition\racketEd
  15880. \begin{lstlisting}
  15881. (let ([x 0])
  15882. (let ([y 0])
  15883. (let ([z 20])
  15884. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15885. (begin
  15886. (set! x 10)
  15887. (set! y 12)
  15888. (f y))))))
  15889. \end{lstlisting}
  15890. \fi}
  15891. {\if\edition\pythonEd\pythonColor
  15892. % box_free_assign.py
  15893. \begin{lstlisting}
  15894. def g(z : int) -> int:
  15895. x = 0
  15896. y = 0
  15897. f : Callable[[int],int] = lambda a: a + x + z
  15898. x = 10
  15899. y = 12
  15900. return f(y)
  15901. print(g(20))
  15902. \end{lstlisting}
  15903. \fi} The correct output for this example is \code{42} because the call
  15904. to \code{f} is required to use the current value of \code{x} (which is
  15905. \code{10}). Unfortunately, the closure conversion pass
  15906. (section~\ref{sec:closure-conversion}) generates code for the
  15907. \code{lambda} that copies the old value of \code{x} into a
  15908. closure. Thus, if we naively applied closure conversion, the output of
  15909. this program would be \code{32}.
  15910. A first attempt at solving this problem would be to save a pointer to
  15911. \code{x} in the closure and change the occurrences of \code{x} inside
  15912. the lambda to dereference the pointer. Of course, this would require
  15913. assigning \code{x} to the stack and not to a register. However, the
  15914. problem goes a bit deeper.
  15915. Consider the following example that returns a function that refers to
  15916. a local variable of the enclosing function:
  15917. \begin{center}
  15918. \begin{minipage}{\textwidth}
  15919. {\if\edition\racketEd
  15920. \begin{lstlisting}
  15921. (define (f) : ( -> Integer)
  15922. (let ([x 0])
  15923. (let ([g (lambda: () : Integer x)])
  15924. (begin
  15925. (set! x 42)
  15926. g))))
  15927. ((f))
  15928. \end{lstlisting}
  15929. \fi}
  15930. {\if\edition\pythonEd\pythonColor
  15931. % counter.py
  15932. \begin{lstlisting}
  15933. def f():
  15934. x = 0
  15935. g = lambda: x
  15936. x = 42
  15937. return g
  15938. print(f()())
  15939. \end{lstlisting}
  15940. \fi}
  15941. \end{minipage}
  15942. \end{center}
  15943. In this example, the lifetime of \code{x} extends beyond the lifetime
  15944. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15945. stack frame for the call to \code{f}, it would be gone by the time we
  15946. called \code{g}, leaving us with dangling pointers for
  15947. \code{x}. This example demonstrates that when a variable occurs free
  15948. inside a function, its lifetime becomes indefinite. Thus, the value of
  15949. the variable needs to live on the heap. The verb
  15950. \emph{box}\index{subject}{box} is often used for allocating a single
  15951. value on the heap, producing a pointer, and
  15952. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15953. %
  15954. We introduce a new pass named \code{convert\_assignments} to address
  15955. this challenge.
  15956. %
  15957. \python{But before diving into that, we have one more
  15958. problem to discuss.}
  15959. {\if\edition\pythonEd\pythonColor
  15960. \section{Uniquify Variables}
  15961. \label{sec:uniquify-lambda}
  15962. With the addition of \code{lambda} we have a complication to deal
  15963. with: name shadowing. Consider the following program with a function
  15964. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15965. \code{lambda} expressions. The first \code{lambda} has a parameter
  15966. that is also named \code{x}.
  15967. \begin{lstlisting}
  15968. def f(x:int, y:int) -> Callable[[int], int]:
  15969. g : Callable[[int],int] = (lambda x: x + y)
  15970. h : Callable[[int],int] = (lambda y: x + y)
  15971. x = input_int()
  15972. return g
  15973. print(f(0, 10)(32))
  15974. \end{lstlisting}
  15975. Many of our compiler passes rely on being able to connect variable
  15976. uses with their definitions using just the name of the
  15977. variable. However, in the example above, the name of the variable does
  15978. not uniquely determine its definition. To solve this problem we
  15979. recommend implementing a pass named \code{uniquify} that renames every
  15980. variable in the program to make sure that they are all unique.
  15981. The following shows the result of \code{uniquify} for the example
  15982. above. The \code{x} parameter of function \code{f} is renamed to
  15983. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15984. renamed to \code{x\_4}.
  15985. \begin{lstlisting}
  15986. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15987. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15988. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15989. x_0 = input_int()
  15990. return g_2
  15991. def main() -> int :
  15992. print(f(0, 10)(32))
  15993. return 0
  15994. \end{lstlisting}
  15995. \fi} % pythonEd
  15996. %% \section{Reveal Functions}
  15997. %% \label{sec:reveal-functions-r5}
  15998. %% \racket{To support the \code{procedure-arity} operator we need to
  15999. %% communicate the arity of a function to the point of closure
  16000. %% creation.}
  16001. %% %
  16002. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16003. %% function at runtime. Thus, we need to communicate the arity of a
  16004. %% function to the point of closure creation.}
  16005. %% %
  16006. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16007. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16008. %% \[
  16009. %% \begin{array}{lcl}
  16010. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16011. %% \end{array}
  16012. %% \]
  16013. \section{Assignment Conversion}
  16014. \label{sec:convert-assignments}
  16015. The purpose of the \code{convert\_assignments} pass is to address the
  16016. challenge regarding the interaction between variable assignments and
  16017. closure conversion. First we identify which variables need to be
  16018. boxed, and then we transform the program to box those variables. In
  16019. general, boxing introduces runtime overhead that we would like to
  16020. avoid, so we should box as few variables as possible. We recommend
  16021. boxing the variables in the intersection of the following two sets of
  16022. variables:
  16023. \begin{enumerate}
  16024. \item The variables that are free in a \code{lambda}.
  16025. \item The variables that appear on the left-hand side of an
  16026. assignment.
  16027. \end{enumerate}
  16028. The first condition is a must but the second condition is
  16029. conservative. It is possible to develop a more liberal condition using
  16030. static program analysis.
  16031. Consider again the first example from
  16032. section~\ref{sec:assignment-scoping}:
  16033. %
  16034. {\if\edition\racketEd
  16035. \begin{lstlisting}
  16036. (let ([x 0])
  16037. (let ([y 0])
  16038. (let ([z 20])
  16039. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16040. (begin
  16041. (set! x 10)
  16042. (set! y 12)
  16043. (f y))))))
  16044. \end{lstlisting}
  16045. \fi}
  16046. {\if\edition\pythonEd\pythonColor
  16047. \begin{lstlisting}
  16048. def g(z : int) -> int:
  16049. x = 0
  16050. y = 0
  16051. f : Callable[[int],int] = lambda a: a + x + z
  16052. x = 10
  16053. y = 12
  16054. return f(y)
  16055. print(g(20))
  16056. \end{lstlisting}
  16057. \fi}
  16058. %
  16059. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16060. side of assignments. The variables \code{x} and \code{z} occur free
  16061. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16062. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16063. three transformations: initialize \code{x} with a tuple whose element
  16064. is uninitialized, replace reads from \code{x} with tuple reads, and
  16065. replace each assignment to \code{x} with a tuple write. The output of
  16066. \code{convert\_assignments} for this example is as follows:
  16067. %
  16068. {\if\edition\racketEd
  16069. \begin{lstlisting}
  16070. (define (main) : Integer
  16071. (let ([x0 (vector 0)])
  16072. (let ([y1 0])
  16073. (let ([z2 20])
  16074. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16075. (+ a3 (+ (vector-ref x0 0) z2)))])
  16076. (begin
  16077. (vector-set! x0 0 10)
  16078. (set! y1 12)
  16079. (f4 y1)))))))
  16080. \end{lstlisting}
  16081. \fi}
  16082. %
  16083. {\if\edition\pythonEd\pythonColor
  16084. \begin{lstlisting}
  16085. def g(z : int)-> int:
  16086. x = (uninitialized(int),)
  16087. x[0] = 0
  16088. y = 0
  16089. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16090. x[0] = 10
  16091. y = 12
  16092. return f(y)
  16093. def main() -> int:
  16094. print(g(20))
  16095. return 0
  16096. \end{lstlisting}
  16097. \fi}
  16098. To compute the free variables of all the \code{lambda} expressions, we
  16099. recommend defining the following two auxiliary functions:
  16100. \begin{enumerate}
  16101. \item \code{free\_variables} computes the free variables of an expression, and
  16102. \item \code{free\_in\_lambda} collects all the variables that are
  16103. free in any of the \code{lambda} expressions, using
  16104. \code{free\_variables} in the case for each \code{lambda}.
  16105. \end{enumerate}
  16106. {\if\edition\racketEd
  16107. %
  16108. To compute the variables that are assigned to, we recommend updating
  16109. the \code{collect-set!} function that we introduced in
  16110. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16111. as \code{Lambda}.
  16112. %
  16113. \fi}
  16114. {\if\edition\pythonEd\pythonColor
  16115. %
  16116. To compute the variables that are assigned to, we recommend defining
  16117. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16118. the set of variables that occur in the left-hand side of an assignment
  16119. statement and otherwise returns the empty set.
  16120. %
  16121. \fi}
  16122. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16123. free in a \code{lambda} and that are assigned to in the enclosing
  16124. function definition.
  16125. Next we discuss the \code{convert\_assignments} pass. In the case for
  16126. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16127. $\VAR{x}$ to a tuple read.
  16128. %
  16129. {\if\edition\racketEd
  16130. \begin{lstlisting}
  16131. (Var |$x$|)
  16132. |$\Rightarrow$|
  16133. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16134. \end{lstlisting}
  16135. \fi}
  16136. %
  16137. {\if\edition\pythonEd\pythonColor
  16138. \begin{lstlisting}
  16139. Name(|$x$|)
  16140. |$\Rightarrow$|
  16141. Subscript(Name(|$x$|), Constant(0), Load())
  16142. \end{lstlisting}
  16143. \fi}
  16144. %
  16145. \noindent In the case for assignment, recursively process the
  16146. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16147. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16148. as follows:
  16149. %
  16150. {\if\edition\racketEd
  16151. \begin{lstlisting}
  16152. (SetBang |$x$| |$\itm{rhs}$|)
  16153. |$\Rightarrow$|
  16154. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16155. \end{lstlisting}
  16156. \fi}
  16157. {\if\edition\pythonEd\pythonColor
  16158. \begin{lstlisting}
  16159. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16160. |$\Rightarrow$|
  16161. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16162. \end{lstlisting}
  16163. \fi}
  16164. %
  16165. {\if\edition\racketEd
  16166. The case for \code{Lambda} is nontrivial, but it is similar to the
  16167. case for function definitions, which we discuss next.
  16168. \fi}
  16169. %
  16170. To translate a function definition, we first compute $\mathit{AF}$,
  16171. the intersection of the variables that are free in a \code{lambda} and
  16172. that are assigned to. We then apply assignment conversion to the body
  16173. of the function definition. Finally, we box the parameters of this
  16174. function definition that are in $\mathit{AF}$. For example,
  16175. the parameter \code{x} of the following function \code{g}
  16176. needs to be boxed:
  16177. {\if\edition\racketEd
  16178. \begin{lstlisting}
  16179. (define (g [x : Integer]) : Integer
  16180. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16181. (begin
  16182. (set! x 10)
  16183. (f 32))))
  16184. \end{lstlisting}
  16185. \fi}
  16186. %
  16187. {\if\edition\pythonEd\pythonColor
  16188. \begin{lstlisting}
  16189. def g(x : int) -> int:
  16190. f : Callable[[int],int] = lambda a: a + x
  16191. x = 10
  16192. return f(32)
  16193. \end{lstlisting}
  16194. \fi}
  16195. %
  16196. \noindent We box parameter \code{x} by creating a local variable named
  16197. \code{x} that is initialized to a tuple whose contents is the value of
  16198. the parameter, which is renamed to \code{x\_0}.
  16199. %
  16200. {\if\edition\racketEd
  16201. \begin{lstlisting}
  16202. (define (g [x_0 : Integer]) : Integer
  16203. (let ([x (vector x_0)])
  16204. (let ([f (lambda: ([a : Integer]) : Integer
  16205. (+ a (vector-ref x 0)))])
  16206. (begin
  16207. (vector-set! x 0 10)
  16208. (f 32)))))
  16209. \end{lstlisting}
  16210. \fi}
  16211. %
  16212. {\if\edition\pythonEd\pythonColor
  16213. \begin{lstlisting}
  16214. def g(x_0 : int)-> int:
  16215. x = (x_0,)
  16216. f : Callable[[int], int] = (lambda a: a + x[0])
  16217. x[0] = 10
  16218. return f(32)
  16219. \end{lstlisting}
  16220. \fi}
  16221. \section{Closure Conversion}
  16222. \label{sec:closure-conversion}
  16223. \index{subject}{closure conversion}
  16224. The compiling of lexically scoped functions into top-level function
  16225. definitions and flat closures is accomplished in the pass
  16226. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16227. and before \code{limit\_functions}.
  16228. As usual, we implement the pass as a recursive function over the
  16229. AST. The interesting cases are for \key{lambda} and function
  16230. application. We transform a \key{lambda} expression into an expression
  16231. that creates a closure, that is, a tuple for which the first element
  16232. is a function pointer and the rest of the elements are the values of
  16233. the free variables of the \key{lambda}.
  16234. %
  16235. However, we use the \code{Closure} AST node instead of using a tuple
  16236. so that we can record the arity.
  16237. %
  16238. In the generated code that follows, \itm{fvs} is the list of free
  16239. variables of the lambda and \itm{name} is a unique symbol generated to
  16240. identify the lambda.
  16241. %
  16242. \racket{The \itm{arity} is the number of parameters (the length of
  16243. \itm{ps}).}
  16244. %
  16245. {\if\edition\racketEd
  16246. \begin{lstlisting}
  16247. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16248. |$\Rightarrow$|
  16249. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16250. \end{lstlisting}
  16251. \fi}
  16252. %
  16253. {\if\edition\pythonEd\pythonColor
  16254. \begin{lstlisting}
  16255. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16256. |$\Rightarrow$|
  16257. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16258. \end{lstlisting}
  16259. \fi}
  16260. %
  16261. In addition to transforming each \key{Lambda} AST node into a
  16262. tuple, we create a top-level function definition for each
  16263. \key{Lambda}, as shown next.\\
  16264. \begin{minipage}{0.8\textwidth}
  16265. {\if\edition\racketEd
  16266. \begin{lstlisting}
  16267. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16268. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16269. ...
  16270. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16271. |\itm{body'}|)...))
  16272. \end{lstlisting}
  16273. \fi}
  16274. {\if\edition\pythonEd\pythonColor
  16275. \begin{lstlisting}
  16276. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16277. |$\itm{fvs}_1$| = clos[1]
  16278. |$\ldots$|
  16279. |$\itm{fvs}_m$| = clos[|$m$|]
  16280. |\itm{body'}|
  16281. \end{lstlisting}
  16282. \fi}
  16283. \end{minipage}\\
  16284. %
  16285. The \code{clos} parameter refers to the closure. The type
  16286. \itm{closTy} is a tuple type for which the first element type is
  16287. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16288. rest of the element types are the types of the free variables in the
  16289. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16290. is nontrivial to give a type to the function in the closure's
  16291. type.\footnote{To give an accurate type to a closure, we would need to
  16292. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16293. %
  16294. \racket{Translate the type
  16295. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16296. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16297. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16298. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16299. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16300. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16301. %% The dummy type is considered to be equal to any other type during type
  16302. %% checking.
  16303. The free variables become local variables that are initialized with
  16304. their values in the closure.
  16305. Closure conversion turns every function into a tuple, so the type
  16306. annotations in the program must also be translated. We recommend
  16307. defining an auxiliary recursive function for this purpose. Function
  16308. types should be translated as follows:
  16309. %
  16310. {\if\edition\racketEd
  16311. \begin{lstlisting}
  16312. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16313. |$\Rightarrow$|
  16314. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16315. \end{lstlisting}
  16316. \fi}
  16317. {\if\edition\pythonEd\pythonColor
  16318. \begin{lstlisting}
  16319. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16320. |$\Rightarrow$|
  16321. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16322. \end{lstlisting}
  16323. \fi}
  16324. %
  16325. This type indicates that the first thing in the tuple is a
  16326. function. The first parameter of the function is a tuple (a closure)
  16327. and the rest of the parameters are the ones from the original
  16328. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16329. omits the types of the free variables because (1) those types are not
  16330. available in this context, and (2) we do not need them in the code that
  16331. is generated for function application. So this type describes only the
  16332. first component of the closure tuple. At runtime the tuple may have
  16333. more components, but we ignore them at this point.
  16334. We transform function application into code that retrieves the
  16335. function from the closure and then calls the function, passing the
  16336. closure as the first argument. We place $e'$ in a temporary variable
  16337. to avoid code duplication.
  16338. \begin{center}
  16339. \begin{minipage}{\textwidth}
  16340. {\if\edition\racketEd
  16341. \begin{lstlisting}
  16342. (Apply |$e$| |$\itm{es}$|)
  16343. |$\Rightarrow$|
  16344. (Let |$\itm{tmp}$| |$e'$|
  16345. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16346. \end{lstlisting}
  16347. \fi}
  16348. %
  16349. {\if\edition\pythonEd\pythonColor
  16350. \begin{lstlisting}
  16351. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16352. |$\Rightarrow$|
  16353. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16354. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16355. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16356. \end{lstlisting}
  16357. \fi}
  16358. \end{minipage}
  16359. \end{center}
  16360. There is also the question of what to do with references to top-level
  16361. function definitions. To maintain a uniform translation of function
  16362. application, we turn function references into closures.
  16363. \begin{tabular}{lll}
  16364. \begin{minipage}{0.2\textwidth}
  16365. {\if\edition\racketEd
  16366. \begin{lstlisting}
  16367. (FunRef |$f$| |$n$|)
  16368. \end{lstlisting}
  16369. \fi}
  16370. {\if\edition\pythonEd\pythonColor
  16371. \begin{lstlisting}
  16372. FunRef(|$f$|, |$n$|)
  16373. \end{lstlisting}
  16374. \fi}
  16375. \end{minipage}
  16376. &
  16377. $\Rightarrow\qquad$
  16378. &
  16379. \begin{minipage}{0.5\textwidth}
  16380. {\if\edition\racketEd
  16381. \begin{lstlisting}
  16382. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16383. \end{lstlisting}
  16384. \fi}
  16385. {\if\edition\pythonEd\pythonColor
  16386. \begin{lstlisting}
  16387. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16388. \end{lstlisting}
  16389. \fi}
  16390. \end{minipage}
  16391. \end{tabular} \\
  16392. We no longer need the annotated assignment statement \code{AnnAssign}
  16393. to support the type checking of \code{lambda} expressions, so we
  16394. translate it to a regular \code{Assign} statement.
  16395. The top-level function definitions need to be updated to take an extra
  16396. closure parameter, but that parameter is ignored in the body of those
  16397. functions.
  16398. \subsection{An Example Translation}
  16399. \label{sec:example-lambda}
  16400. Figure~\ref{fig:lexical-functions-example} shows the result of
  16401. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16402. program demonstrating lexical scoping that we discussed at the
  16403. beginning of this chapter.
  16404. \begin{figure}[tbp]
  16405. \begin{tcolorbox}[colback=white]
  16406. \begin{minipage}{0.8\textwidth}
  16407. {\if\edition\racketEd
  16408. % tests/lambda_test_6.rkt
  16409. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16410. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16411. (let ([y8 4])
  16412. (lambda: ([z9 : Integer]) : Integer
  16413. (+ x7 (+ y8 z9)))))
  16414. (define (main) : Integer
  16415. (let ([g0 ((fun-ref f6 1) 5)])
  16416. (let ([h1 ((fun-ref f6 1) 3)])
  16417. (+ (g0 11) (h1 15)))))
  16418. \end{lstlisting}
  16419. $\Rightarrow$
  16420. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16421. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16422. (let ([y8 4])
  16423. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16424. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16425. (let ([x7 (vector-ref fvs3 1)])
  16426. (let ([y8 (vector-ref fvs3 2)])
  16427. (+ x7 (+ y8 z9)))))
  16428. (define (main) : Integer
  16429. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16430. ((vector-ref clos5 0) clos5 5))])
  16431. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16432. ((vector-ref clos6 0) clos6 3))])
  16433. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16434. \end{lstlisting}
  16435. \fi}
  16436. %
  16437. {\if\edition\pythonEd\pythonColor
  16438. % free_var.py
  16439. \begin{lstlisting}
  16440. def f(x: int) -> Callable[[int],int]:
  16441. y = 4
  16442. return lambda z: x + y + z
  16443. g = f(5)
  16444. h = f(3)
  16445. print(g(11) + h(15))
  16446. \end{lstlisting}
  16447. $\Rightarrow$
  16448. \begin{lstlisting}
  16449. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16450. x = fvs_1[1]
  16451. y = fvs_1[2]
  16452. return (x + y[0] + z)
  16453. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16454. y = (uninitialized(int),)
  16455. y[0] = 4
  16456. return closure{1}({lambda_0}, x, y)
  16457. def main() -> int:
  16458. g = (begin: clos_3 = closure{1}({f})
  16459. clos_3[0](clos_3, 5))
  16460. h = (begin: clos_4 = closure{1}({f})
  16461. clos_4[0](clos_4, 3))
  16462. print((begin: clos_5 = g
  16463. clos_5[0](clos_5, 11))
  16464. + (begin: clos_6 = h
  16465. clos_6[0](clos_6, 15)))
  16466. return 0
  16467. \end{lstlisting}
  16468. \fi}
  16469. \end{minipage}
  16470. \end{tcolorbox}
  16471. \caption{Example of closure conversion.}
  16472. \label{fig:lexical-functions-example}
  16473. \end{figure}
  16474. \begin{exercise}\normalfont\normalsize
  16475. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16476. Create five new programs that use \key{lambda} functions and make use of
  16477. lexical scoping. Test your compiler on these new programs and all
  16478. your previously created test programs.
  16479. \end{exercise}
  16480. \section{Expose Allocation}
  16481. \label{sec:expose-allocation-r5}
  16482. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16483. that allocates and initializes a tuple, similar to the translation of
  16484. the tuple creation in section~\ref{sec:expose-allocation}.
  16485. The only difference is replacing the use of
  16486. \ALLOC{\itm{len}}{\itm{type}} with
  16487. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16488. \section{Explicate Control and \LangCLam{}}
  16489. \label{sec:explicate-r5}
  16490. The output language of \code{explicate\_control} is \LangCLam{}; the
  16491. definition of its abstract syntax is shown in
  16492. figure~\ref{fig:Clam-syntax}.
  16493. %
  16494. \racket{The only differences with respect to \LangCFun{} are the
  16495. addition of the \code{AllocateClosure} form to the grammar for
  16496. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16497. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16498. similar to the handling of other expressions such as primitive
  16499. operators.}
  16500. %
  16501. \python{The differences with respect to \LangCFun{} are the
  16502. additions of \code{Uninitialized}, \code{AllocateClosure},
  16503. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16504. \code{explicate\_control} pass is similar to the handling of other
  16505. expressions such as primitive operators.}
  16506. \newcommand{\ClambdaASTRacket}{
  16507. \begin{array}{lcl}
  16508. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16509. \itm{op} &::= & \code{procedure-arity}
  16510. \end{array}
  16511. }
  16512. \newcommand{\ClambdaASTPython}{
  16513. \begin{array}{lcl}
  16514. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16515. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16516. &\MID& \ARITY{\Atm}
  16517. \end{array}
  16518. }
  16519. \begin{figure}[tp]
  16520. \begin{tcolorbox}[colback=white]
  16521. \small
  16522. {\if\edition\racketEd
  16523. \[
  16524. \begin{array}{l}
  16525. \gray{\CvarASTRacket} \\ \hline
  16526. \gray{\CifASTRacket} \\ \hline
  16527. \gray{\CloopASTRacket} \\ \hline
  16528. \gray{\CtupASTRacket} \\ \hline
  16529. \gray{\CfunASTRacket} \\ \hline
  16530. \ClambdaASTRacket \\
  16531. \begin{array}{lcl}
  16532. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16533. \end{array}
  16534. \end{array}
  16535. \]
  16536. \fi}
  16537. {\if\edition\pythonEd\pythonColor
  16538. \[
  16539. \begin{array}{l}
  16540. \gray{\CifASTPython} \\ \hline
  16541. \gray{\CtupASTPython} \\ \hline
  16542. \gray{\CfunASTPython} \\ \hline
  16543. \ClambdaASTPython \\
  16544. \begin{array}{lcl}
  16545. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16546. \end{array}
  16547. \end{array}
  16548. \]
  16549. \fi}
  16550. \end{tcolorbox}
  16551. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16552. \label{fig:Clam-syntax}
  16553. \end{figure}
  16554. \section{Select Instructions}
  16555. \label{sec:select-instructions-Llambda}
  16556. \index{subject}{select instructions}
  16557. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16558. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16559. (section~\ref{sec:select-instructions-gc}). The only difference is
  16560. that you should place the \itm{arity} in the tag that is stored at
  16561. position $0$ of the tuple. Recall that in
  16562. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16563. was not used. We store the arity in the $5$ bits starting at position
  16564. $58$.
  16565. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16566. instructions that access the tag from position $0$ of the vector and
  16567. extract the $5$ bits starting at position $58$ from the tag.}
  16568. %
  16569. \python{Compile a call to the \code{arity} operator to a sequence of
  16570. instructions that access the tag from position $0$ of the tuple
  16571. (representing a closure) and extract the $5$ bits starting at position
  16572. $58$ from the tag.}
  16573. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16574. needed for the compilation of \LangLam{}.
  16575. \begin{figure}[bthp]
  16576. \begin{tcolorbox}[colback=white]
  16577. {\if\edition\racketEd
  16578. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16579. \node (Lfun) at (0,2) {\large \LangLam{}};
  16580. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16581. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16582. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16583. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16584. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16585. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16586. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16587. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16588. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16589. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16590. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16591. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16592. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16593. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16594. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16595. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16596. \path[->,bend left=15] (Lfun) edge [above] node
  16597. {\ttfamily\footnotesize shrink} (Lfun-2);
  16598. \path[->,bend left=15] (Lfun-2) edge [above] node
  16599. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16600. \path[->,bend left=15] (Lfun-3) edge [above] node
  16601. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16602. \path[->,bend left=15] (F1-0) edge [left] node
  16603. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16604. \path[->,bend left=15] (F1-1) edge [below] node
  16605. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16606. \path[->,bend right=15] (F1-2) edge [above] node
  16607. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16608. \path[->,bend right=15] (F1-3) edge [above] node
  16609. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16610. \path[->,bend left=15] (F1-4) edge [right] node
  16611. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16612. \path[->,bend right=15] (F1-5) edge [below] node
  16613. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16614. \path[->,bend left=15] (F1-6) edge [above] node
  16615. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16616. \path[->] (C3-2) edge [right] node
  16617. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16618. \path[->,bend right=15] (x86-2) edge [right] node
  16619. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16620. \path[->,bend right=15] (x86-2-1) edge [below] node
  16621. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16622. \path[->,bend right=15] (x86-2-2) edge [right] node
  16623. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16624. \path[->,bend left=15] (x86-3) edge [above] node
  16625. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16626. \path[->,bend left=15] (x86-4) edge [right] node
  16627. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16628. \end{tikzpicture}
  16629. \fi}
  16630. {\if\edition\pythonEd\pythonColor
  16631. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16632. \node (Lfun) at (0,2) {\large \LangLam{}};
  16633. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16634. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16635. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16636. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16637. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16638. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16639. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16640. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16641. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16642. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16643. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16644. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16645. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16646. \path[->,bend left=15] (Lfun) edge [above] node
  16647. {\ttfamily\footnotesize shrink} (Lfun-2);
  16648. \path[->,bend left=15] (Lfun-2) edge [above] node
  16649. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16650. \path[->,bend left=15] (Lfun-3) edge [above] node
  16651. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16652. \path[->,bend left=15] (F1-0) edge [left] node
  16653. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16654. \path[->,bend left=15] (F1-1) edge [below] node
  16655. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16656. \path[->,bend left=15] (F1-2) edge [below] node
  16657. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16658. \path[->,bend right=15] (F1-3) edge [above] node
  16659. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16660. \path[->,bend right=15] (F1-5) edge [right] node
  16661. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16662. \path[->,bend left=15] (F1-6) edge [right] node
  16663. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16664. \path[->,bend right=15] (C3-2) edge [right] node
  16665. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16666. \path[->,bend right=15] (x86-2) edge [below] node
  16667. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16668. \path[->,bend right=15] (x86-3) edge [below] node
  16669. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16670. \path[->,bend left=15] (x86-4) edge [above] node
  16671. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16672. \end{tikzpicture}
  16673. \fi}
  16674. \end{tcolorbox}
  16675. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16676. functions.}
  16677. \label{fig:Llambda-passes}
  16678. \end{figure}
  16679. \clearpage
  16680. \section{Challenge: Optimize Closures}
  16681. \label{sec:optimize-closures}
  16682. In this chapter we compile lexically scoped functions into a
  16683. relatively efficient representation: flat closures. However, even this
  16684. representation comes with some overhead. For example, consider the
  16685. following program with a function \code{tail\_sum} that does not have
  16686. any free variables and where all the uses of \code{tail\_sum} are in
  16687. applications in which we know that only \code{tail\_sum} is being applied
  16688. (and not any other functions):
  16689. \begin{center}
  16690. \begin{minipage}{0.95\textwidth}
  16691. {\if\edition\racketEd
  16692. \begin{lstlisting}
  16693. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16694. (if (eq? n 0)
  16695. s
  16696. (tail_sum (- n 1) (+ n s))))
  16697. (+ (tail_sum 3 0) 36)
  16698. \end{lstlisting}
  16699. \fi}
  16700. {\if\edition\pythonEd\pythonColor
  16701. \begin{lstlisting}
  16702. def tail_sum(n : int, s : int) -> int:
  16703. if n == 0:
  16704. return s
  16705. else:
  16706. return tail_sum(n - 1, n + s)
  16707. print(tail_sum(3, 0) + 36)
  16708. \end{lstlisting}
  16709. \fi}
  16710. \end{minipage}
  16711. \end{center}
  16712. As described in this chapter, we uniformly apply closure conversion to
  16713. all functions, obtaining the following output for this program:
  16714. \begin{center}
  16715. \begin{minipage}{0.95\textwidth}
  16716. {\if\edition\racketEd
  16717. \begin{lstlisting}
  16718. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16719. (if (eq? n2 0)
  16720. s3
  16721. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16722. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16723. (define (main) : Integer
  16724. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16725. ((vector-ref clos6 0) clos6 3 0)) 27))
  16726. \end{lstlisting}
  16727. \fi}
  16728. {\if\edition\pythonEd\pythonColor
  16729. \begin{lstlisting}
  16730. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16731. if n_0 == 0:
  16732. return s_1
  16733. else:
  16734. return (begin: clos_2 = (tail_sum,)
  16735. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16736. def main() -> int :
  16737. print((begin: clos_4 = (tail_sum,)
  16738. clos_4[0](clos_4, 3, 0)) + 36)
  16739. return 0
  16740. \end{lstlisting}
  16741. \fi}
  16742. \end{minipage}
  16743. \end{center}
  16744. If this program were compiled according to the previous chapter, there
  16745. would be no allocation and the calls to \code{tail\_sum} would be
  16746. direct calls. In contrast, the program presented here allocates memory
  16747. for each closure and the calls to \code{tail\_sum} are indirect. These
  16748. two differences incur considerable overhead in a program such as this,
  16749. in which the allocations and indirect calls occur inside a tight loop.
  16750. One might think that this problem is trivial to solve: can't we just
  16751. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16752. and compile them to direct calls instead of treating it like a call to
  16753. a closure? We would also drop the new \code{fvs} parameter of
  16754. \code{tail\_sum}.
  16755. %
  16756. However, this problem is not so trivial, because a global function may
  16757. \emph{escape} and become involved in applications that also involve
  16758. closures. Consider the following example in which the application
  16759. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16760. application because the \code{lambda} may flow into \code{f}, but the
  16761. \code{inc} function might also flow into \code{f}:
  16762. \begin{center}
  16763. \begin{minipage}{\textwidth}
  16764. % lambda_test_30.rkt
  16765. {\if\edition\racketEd
  16766. \begin{lstlisting}
  16767. (define (inc [x : Integer]) : Integer
  16768. (+ x 1))
  16769. (let ([y (read)])
  16770. (let ([f (if (eq? (read) 0)
  16771. inc
  16772. (lambda: ([x : Integer]) : Integer (- x y)))])
  16773. (f 41)))
  16774. \end{lstlisting}
  16775. \fi}
  16776. {\if\edition\pythonEd\pythonColor
  16777. \begin{lstlisting}
  16778. def add1(x : int) -> int:
  16779. return x + 1
  16780. y = input_int()
  16781. g : Callable[[int], int] = lambda x: x - y
  16782. f = add1 if input_int() == 0 else g
  16783. print(f(41))
  16784. \end{lstlisting}
  16785. \fi}
  16786. \end{minipage}
  16787. \end{center}
  16788. If a global function name is used in any way other than as the
  16789. operator in a direct call, then we say that the function
  16790. \emph{escapes}. If a global function does not escape, then we do not
  16791. need to perform closure conversion on the function.
  16792. \begin{exercise}\normalfont\normalsize
  16793. Implement an auxiliary function for detecting which global
  16794. functions escape. Using that function, implement an improved version
  16795. of closure conversion that does not apply closure conversion to
  16796. global functions that do not escape but instead compiles them as
  16797. regular functions. Create several new test cases that check whether
  16798. your compiler properly detects whether global functions escape or not.
  16799. \end{exercise}
  16800. So far we have reduced the overhead of calling global functions, but
  16801. it would also be nice to reduce the overhead of calling a
  16802. \code{lambda} when we can determine at compile time which
  16803. \code{lambda} will be called. We refer to such calls as \emph{known
  16804. calls}. Consider the following example in which a \code{lambda} is
  16805. bound to \code{f} and then applied.
  16806. {\if\edition\racketEd
  16807. % lambda_test_9.rkt
  16808. \begin{lstlisting}
  16809. (let ([y (read)])
  16810. (let ([f (lambda: ([x : Integer]) : Integer
  16811. (+ x y))])
  16812. (f 21)))
  16813. \end{lstlisting}
  16814. \fi}
  16815. {\if\edition\pythonEd\pythonColor
  16816. \begin{lstlisting}
  16817. y = input_int()
  16818. f : Callable[[int],int] = lambda x: x + y
  16819. print(f(21))
  16820. \end{lstlisting}
  16821. \fi}
  16822. %
  16823. \noindent Closure conversion compiles the application
  16824. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16825. %
  16826. {\if\edition\racketEd
  16827. \begin{lstlisting}
  16828. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16829. (let ([y2 (vector-ref fvs6 1)])
  16830. (+ x3 y2)))
  16831. (define (main) : Integer
  16832. (let ([y2 (read)])
  16833. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16834. ((vector-ref f4 0) f4 21))))
  16835. \end{lstlisting}
  16836. \fi}
  16837. {\if\edition\pythonEd\pythonColor
  16838. \begin{lstlisting}
  16839. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16840. y_1 = fvs_4[1]
  16841. return x_2 + y_1[0]
  16842. def main() -> int:
  16843. y_1 = (777,)
  16844. y_1[0] = input_int()
  16845. f_0 = (lambda_3, y_1)
  16846. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16847. return 0
  16848. \end{lstlisting}
  16849. \fi}
  16850. %
  16851. \noindent However, we can instead compile the application
  16852. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16853. %
  16854. {\if\edition\racketEd
  16855. \begin{lstlisting}
  16856. (define (main) : Integer
  16857. (let ([y2 (read)])
  16858. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16859. ((fun-ref lambda5 1) f4 21))))
  16860. \end{lstlisting}
  16861. \fi}
  16862. {\if\edition\pythonEd\pythonColor
  16863. \begin{lstlisting}
  16864. def main() -> int:
  16865. y_1 = (777,)
  16866. y_1[0] = input_int()
  16867. f_0 = (lambda_3, y_1)
  16868. print(lambda_3(f_0, 21))
  16869. return 0
  16870. \end{lstlisting}
  16871. \fi}
  16872. The problem of determining which \code{lambda} will be called from a
  16873. particular application is quite challenging in general and the topic
  16874. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16875. following exercise we recommend that you compile an application to a
  16876. direct call when the operator is a variable and \racket{the variable
  16877. is \code{let}-bound to a closure}\python{the previous assignment to
  16878. the variable is a closure}. This can be accomplished by maintaining
  16879. an environment that maps variables to function names. Extend the
  16880. environment whenever you encounter a closure on the right-hand side of
  16881. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16882. name of the global function for the closure. This pass should come
  16883. after closure conversion.
  16884. \begin{exercise}\normalfont\normalsize
  16885. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16886. compiles known calls into direct calls. Verify that your compiler is
  16887. successful in this regard on several example programs.
  16888. \end{exercise}
  16889. These exercises only scratch the surface of closure optimization. A
  16890. good next step for the interested reader is to look at the work of
  16891. \citet{Keep:2012ab}.
  16892. \section{Further Reading}
  16893. The notion of lexically scoped functions predates modern computers by
  16894. about a decade. They were invented by \citet{Church:1932aa}, who
  16895. proposed the lambda calculus as a foundation for logic. Anonymous
  16896. functions were included in the LISP~\citep{McCarthy:1960dz}
  16897. programming language but were initially dynamically scoped. The Scheme
  16898. dialect of LISP adopted lexical scoping, and
  16899. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16900. Scheme programs. However, environments were represented as linked
  16901. lists, so variable look-up was linear in the size of the
  16902. environment. \citet{Appel91} gives a detailed description of several
  16903. closure representations. In this chapter we represent environments
  16904. using flat closures, which were invented by
  16905. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16906. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16907. closures, variable look-up is constant time but the time to create a
  16908. closure is proportional to the number of its free variables. Flat
  16909. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16910. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16911. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16912. % compilers)
  16913. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16914. \chapter{Dynamic Typing}
  16915. \label{ch:Ldyn}
  16916. \index{subject}{dynamic typing}
  16917. \setcounter{footnote}{0}
  16918. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16919. typed language that is a subset of \racket{Racket}\python{Python}. The
  16920. focus on dynamic typing is in contrast to the previous chapters, which
  16921. have studied the compilation of statically typed languages. In
  16922. dynamically typed languages such as \LangDyn{}, a particular
  16923. expression may produce a value of a different type each time it is
  16924. executed. Consider the following example with a conditional \code{if}
  16925. expression that may return a Boolean or an integer depending on the
  16926. input to the program:
  16927. % part of dynamic_test_25.rkt
  16928. {\if\edition\racketEd
  16929. \begin{lstlisting}
  16930. (not (if (eq? (read) 1) #f 0))
  16931. \end{lstlisting}
  16932. \fi}
  16933. {\if\edition\pythonEd\pythonColor
  16934. \begin{lstlisting}
  16935. not (False if input_int() == 1 else 0)
  16936. \end{lstlisting}
  16937. \fi}
  16938. Languages that allow expressions to produce different kinds of values
  16939. are called \emph{polymorphic}, a word composed of the Greek roots
  16940. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16941. There are several kinds of polymorphism in programming languages, such as
  16942. subtype polymorphism\index{subject}{subtype polymorphism} and
  16943. parametric polymorphism\index{subject}{parametric polymorphism}
  16944. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16945. study in this chapter does not have a special name; it is the kind
  16946. that arises in dynamically typed languages.
  16947. Another characteristic of dynamically typed languages is that
  16948. their primitive operations, such as \code{not}, are often defined to operate
  16949. on many different types of values. In fact, in
  16950. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16951. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16952. given anything else it returns \FALSE{}.
  16953. Furthermore, even when primitive operations restrict their inputs to
  16954. values of a certain type, this restriction is enforced at runtime
  16955. instead of during compilation. For example, the tuple read
  16956. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16957. results in a runtime error because the first argument must
  16958. be a tuple, not a Boolean.
  16959. \section{The \LangDyn{} Language}
  16960. \newcommand{\LdynGrammarRacket}{
  16961. \begin{array}{rcl}
  16962. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16963. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16964. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16965. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16966. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16967. \end{array}
  16968. }
  16969. \newcommand{\LdynASTRacket}{
  16970. \begin{array}{lcl}
  16971. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16972. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16973. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16974. \end{array}
  16975. }
  16976. \begin{figure}[tp]
  16977. \centering
  16978. \begin{tcolorbox}[colback=white]
  16979. \small
  16980. {\if\edition\racketEd
  16981. \[
  16982. \begin{array}{l}
  16983. \gray{\LintGrammarRacket{}} \\ \hline
  16984. \gray{\LvarGrammarRacket{}} \\ \hline
  16985. \gray{\LifGrammarRacket{}} \\ \hline
  16986. \gray{\LwhileGrammarRacket} \\ \hline
  16987. \gray{\LtupGrammarRacket} \\ \hline
  16988. \LdynGrammarRacket \\
  16989. \begin{array}{rcl}
  16990. \LangDynM{} &::=& \Def\ldots\; \Exp
  16991. \end{array}
  16992. \end{array}
  16993. \]
  16994. \fi}
  16995. {\if\edition\pythonEd\pythonColor
  16996. \[
  16997. \begin{array}{rcl}
  16998. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16999. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17000. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17001. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17002. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17003. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17004. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17005. \MID \CLEN{\Exp} \\
  17006. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17007. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17008. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17009. \MID \Var\mathop{\key{=}}\Exp \\
  17010. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17011. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17012. &\MID& \CRETURN{\Exp} \\
  17013. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17014. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17015. \end{array}
  17016. \]
  17017. \fi}
  17018. \end{tcolorbox}
  17019. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17020. \label{fig:r7-concrete-syntax}
  17021. \end{figure}
  17022. \begin{figure}[tp]
  17023. \centering
  17024. \begin{tcolorbox}[colback=white]
  17025. \small
  17026. {\if\edition\racketEd
  17027. \[
  17028. \begin{array}{l}
  17029. \gray{\LintASTRacket{}} \\ \hline
  17030. \gray{\LvarASTRacket{}} \\ \hline
  17031. \gray{\LifASTRacket{}} \\ \hline
  17032. \gray{\LwhileASTRacket} \\ \hline
  17033. \gray{\LtupASTRacket} \\ \hline
  17034. \LdynASTRacket \\
  17035. \begin{array}{lcl}
  17036. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17037. \end{array}
  17038. \end{array}
  17039. \]
  17040. \fi}
  17041. {\if\edition\pythonEd\pythonColor
  17042. \[
  17043. \begin{array}{rcl}
  17044. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17045. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17046. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17047. \MID \code{Is()} \\
  17048. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17049. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17050. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17051. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17052. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17053. &\MID& \VAR{\Var{}}
  17054. \MID \BOOL{\itm{bool}}
  17055. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17056. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17057. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17058. &\MID& \LEN{\Exp} \\
  17059. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17060. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17061. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17062. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17063. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17064. &\MID& \RETURN{\Exp} \\
  17065. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17066. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17067. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17068. \end{array}
  17069. \]
  17070. \fi}
  17071. \end{tcolorbox}
  17072. \caption{The abstract syntax of \LangDyn{}.}
  17073. \label{fig:r7-syntax}
  17074. \end{figure}
  17075. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17076. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17077. %
  17078. There is no type checker for \LangDyn{} because it checks types only
  17079. at runtime.
  17080. The definitional interpreter for \LangDyn{} is presented in
  17081. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17082. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17083. \INT{n}. Instead of simply returning the integer \code{n} (as
  17084. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17085. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17086. value} that combines an underlying value with a tag that identifies
  17087. what kind of value it is. We define the following \racket{struct}\python{class}
  17088. to represent tagged values:
  17089. %
  17090. {\if\edition\racketEd
  17091. \begin{lstlisting}
  17092. (struct Tagged (value tag) #:transparent)
  17093. \end{lstlisting}
  17094. \fi}
  17095. {\if\edition\pythonEd\pythonColor
  17096. \begin{minipage}{\textwidth}
  17097. \begin{lstlisting}
  17098. @dataclass(eq=True)
  17099. class Tagged(Value):
  17100. value : Value
  17101. tag : str
  17102. def __str__(self):
  17103. return str(self.value)
  17104. \end{lstlisting}
  17105. \end{minipage}
  17106. \fi}
  17107. %
  17108. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17109. \code{Vector}, and \code{Procedure}.}
  17110. %
  17111. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17112. \skey{tuple}, and \skey{function}.}
  17113. %
  17114. Tags are closely related to types but do not always capture all the
  17115. information that a type does.
  17116. %
  17117. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17118. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17119. Any)} is tagged with \code{Procedure}.}
  17120. %
  17121. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17122. is tagged with \skey{tuple} and a function of type
  17123. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17124. is tagged with \skey{function}.}
  17125. Next consider the match case for accessing the element of a tuple.
  17126. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17127. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17128. argument is a tuple and the second is an integer.
  17129. \racket{
  17130. If they are not, a \code{trapped-error} is raised. Recall from
  17131. section~\ref{sec:interp_Lint} that when a definition interpreter
  17132. raises a \code{trapped-error} error, the compiled code must also
  17133. signal an error by exiting with return code \code{255}. A
  17134. \code{trapped-error} is also raised if the index is not less than the
  17135. length of the vector.
  17136. }
  17137. %
  17138. \python{If they are not, an exception is raised. The compiled code
  17139. must also signal an error by exiting with return code \code{255}. A
  17140. exception is also raised if the index is not less than the length of the
  17141. tuple or if it is negative.}
  17142. \begin{figure}[tbp]
  17143. \begin{tcolorbox}[colback=white]
  17144. {\if\edition\racketEd
  17145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17146. (define ((interp-Ldyn-exp env) ast)
  17147. (define recur (interp-Ldyn-exp env))
  17148. (match ast
  17149. [(Var x) (dict-ref env x)]
  17150. [(Int n) (Tagged n 'Integer)]
  17151. [(Bool b) (Tagged b 'Boolean)]
  17152. [(Lambda xs rt body)
  17153. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17154. [(Prim 'vector es)
  17155. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17156. [(Prim 'vector-ref (list e1 e2))
  17157. (define vec (recur e1)) (define i (recur e2))
  17158. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17159. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17160. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17161. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17162. [(Prim 'vector-set! (list e1 e2 e3))
  17163. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17164. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17165. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17166. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17167. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17168. (Tagged (void) 'Void)]
  17169. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17170. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17171. [(Prim 'or (list e1 e2))
  17172. (define v1 (recur e1))
  17173. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17174. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17175. [(Prim op (list e1))
  17176. #:when (set-member? type-predicates op)
  17177. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17178. [(Prim op es)
  17179. (define args (map recur es))
  17180. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17181. (unless (for/or ([expected-tags (op-tags op)])
  17182. (equal? expected-tags tags))
  17183. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17184. (tag-value
  17185. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17186. [(If q t f)
  17187. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17188. [(Apply f es)
  17189. (define new-f (recur f)) (define args (map recur es))
  17190. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17191. (match f-val
  17192. [`(function ,xs ,body ,lam-env)
  17193. (unless (eq? (length xs) (length args))
  17194. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17195. (define new-env (append (map cons xs args) lam-env))
  17196. ((interp-Ldyn-exp new-env) body)]
  17197. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17198. \end{lstlisting}
  17199. \fi}
  17200. {\if\edition\pythonEd\pythonColor
  17201. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17202. class InterpLdyn(InterpLlambda):
  17203. def interp_exp(self, e, env):
  17204. match e:
  17205. case Constant(n):
  17206. return self.tag(super().interp_exp(e, env))
  17207. case Tuple(es, Load()):
  17208. return self.tag(super().interp_exp(e, env))
  17209. case Lambda(params, body):
  17210. return self.tag(super().interp_exp(e, env))
  17211. case Call(Name('input_int'), []):
  17212. return self.tag(super().interp_exp(e, env))
  17213. case BinOp(left, Add(), right):
  17214. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17215. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17216. case BinOp(left, Sub(), right):
  17217. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17218. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17219. case UnaryOp(USub(), e1):
  17220. v = self.interp_exp(e1, env)
  17221. return self.tag(- self.untag(v, 'int', e))
  17222. case IfExp(test, body, orelse):
  17223. v = self.interp_exp(test, env)
  17224. if self.untag(v, 'bool', e):
  17225. return self.interp_exp(body, env)
  17226. else:
  17227. return self.interp_exp(orelse, env)
  17228. case UnaryOp(Not(), e1):
  17229. v = self.interp_exp(e1, env)
  17230. return self.tag(not self.untag(v, 'bool', e))
  17231. case BoolOp(And(), values):
  17232. left = values[0]; right = values[1]
  17233. l = self.interp_exp(left, env)
  17234. if self.untag(l, 'bool', e):
  17235. return self.interp_exp(right, env)
  17236. else:
  17237. return self.tag(False)
  17238. case BoolOp(Or(), values):
  17239. left = values[0]; right = values[1]
  17240. l = self.interp_exp(left, env)
  17241. if self.untag(l, 'bool', e):
  17242. return self.tag(True)
  17243. else:
  17244. return self.interp_exp(right, env)
  17245. \end{lstlisting}
  17246. \fi}
  17247. \end{tcolorbox}
  17248. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17249. \label{fig:interp-Ldyn}
  17250. \end{figure}
  17251. {\if\edition\pythonEd\pythonColor
  17252. \begin{figure}[tbp]
  17253. \begin{tcolorbox}[colback=white]
  17254. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17255. # interp_exp continued
  17256. case Compare(left, [cmp], [right]):
  17257. l = self.interp_exp(left, env)
  17258. r = self.interp_exp(right, env)
  17259. if l.tag == r.tag:
  17260. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17261. else:
  17262. raise Exception('interp Compare unexpected '
  17263. + repr(l) + ' ' + repr(r))
  17264. case Subscript(tup, index, Load()):
  17265. t = self.interp_exp(tup, env)
  17266. n = self.interp_exp(index, env)
  17267. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17268. case Call(Name('len'), [tup]):
  17269. t = self.interp_exp(tup, env)
  17270. return self.tag(len(self.untag(t, 'tuple', e)))
  17271. case _:
  17272. return self.tag(super().interp_exp(e, env))
  17273. def interp_stmt(self, s, env, cont):
  17274. match s:
  17275. case If(test, body, orelse):
  17276. v = self.interp_exp(test, env)
  17277. match self.untag(v, 'bool', s):
  17278. case True:
  17279. return self.interp_stmts(body + cont, env)
  17280. case False:
  17281. return self.interp_stmts(orelse + cont, env)
  17282. case While(test, body, []):
  17283. v = self.interp_exp(test, env)
  17284. if self.untag(v, 'bool', test):
  17285. self.interp_stmts(body + [s] + cont, env)
  17286. else:
  17287. return self.interp_stmts(cont, env)
  17288. case Assign([Subscript(tup, index)], value):
  17289. tup = self.interp_exp(tup, env)
  17290. index = self.interp_exp(index, env)
  17291. tup_v = self.untag(tup, 'tuple', s)
  17292. index_v = self.untag(index, 'int', s)
  17293. tup_v[index_v] = self.interp_exp(value, env)
  17294. return self.interp_stmts(cont, env)
  17295. case FunctionDef(name, params, bod, dl, returns, comment):
  17296. if isinstance(params, ast.arguments):
  17297. ps = [p.arg for p in params.args]
  17298. else:
  17299. ps = [x for (x,t) in params]
  17300. env[name] = self.tag(Function(name, ps, bod, env))
  17301. return self.interp_stmts(cont, env)
  17302. case _:
  17303. return super().interp_stmt(s, env, cont)
  17304. \end{lstlisting}
  17305. \end{tcolorbox}
  17306. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17307. \label{fig:interp-Ldyn-2}
  17308. \end{figure}
  17309. \fi}
  17310. \begin{figure}[tbp]
  17311. \begin{tcolorbox}[colback=white]
  17312. {\if\edition\racketEd
  17313. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17314. (define (interp-op op)
  17315. (match op
  17316. ['+ fx+]
  17317. ['- fx-]
  17318. ['read read-fixnum]
  17319. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17320. ['< (lambda (v1 v2)
  17321. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17322. ['<= (lambda (v1 v2)
  17323. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17324. ['> (lambda (v1 v2)
  17325. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17326. ['>= (lambda (v1 v2)
  17327. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17328. ['boolean? boolean?]
  17329. ['integer? fixnum?]
  17330. ['void? void?]
  17331. ['vector? vector?]
  17332. ['vector-length vector-length]
  17333. ['procedure? (match-lambda
  17334. [`(functions ,xs ,body ,env) #t] [else #f])]
  17335. [else (error 'interp-op "unknown operator" op)]))
  17336. (define (op-tags op)
  17337. (match op
  17338. ['+ '((Integer Integer))]
  17339. ['- '((Integer Integer) (Integer))]
  17340. ['read '(())]
  17341. ['not '((Boolean))]
  17342. ['< '((Integer Integer))]
  17343. ['<= '((Integer Integer))]
  17344. ['> '((Integer Integer))]
  17345. ['>= '((Integer Integer))]
  17346. ['vector-length '((Vector))]))
  17347. (define type-predicates
  17348. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17349. (define (tag-value v)
  17350. (cond [(boolean? v) (Tagged v 'Boolean)]
  17351. [(fixnum? v) (Tagged v 'Integer)]
  17352. [(procedure? v) (Tagged v 'Procedure)]
  17353. [(vector? v) (Tagged v 'Vector)]
  17354. [(void? v) (Tagged v 'Void)]
  17355. [else (error 'tag-value "unidentified value ~a" v)]))
  17356. (define (check-tag val expected ast)
  17357. (define tag (Tagged-tag val))
  17358. (unless (eq? tag expected)
  17359. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17360. \end{lstlisting}
  17361. \fi}
  17362. {\if\edition\pythonEd\pythonColor
  17363. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17364. class InterpLdyn(InterpLlambda):
  17365. def tag(self, v):
  17366. if v is True or v is False:
  17367. return Tagged(v, 'bool')
  17368. elif isinstance(v, int):
  17369. return Tagged(v, 'int')
  17370. elif isinstance(v, Function):
  17371. return Tagged(v, 'function')
  17372. elif isinstance(v, tuple):
  17373. return Tagged(v, 'tuple')
  17374. elif isinstance(v, type(None)):
  17375. return Tagged(v, 'none')
  17376. else:
  17377. raise Exception('tag: unexpected ' + repr(v))
  17378. def untag(self, v, expected_tag, ast):
  17379. match v:
  17380. case Tagged(val, tag) if tag == expected_tag:
  17381. return val
  17382. case _:
  17383. raise TrappedError('expected Tagged value with '
  17384. + expected_tag + ', not ' + ' ' + repr(v))
  17385. def apply_fun(self, fun, args, e):
  17386. f = self.untag(fun, 'function', e)
  17387. return super().apply_fun(f, args, e)
  17388. \end{lstlisting}
  17389. \fi}
  17390. \end{tcolorbox}
  17391. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17392. \label{fig:interp-Ldyn-aux}
  17393. \end{figure}
  17394. %\clearpage
  17395. \section{Representation of Tagged Values}
  17396. The interpreter for \LangDyn{} introduced a new kind of value: the
  17397. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17398. represent tagged values at the bit level. Because almost every
  17399. operation in \LangDyn{} involves manipulating tagged values, the
  17400. representation must be efficient. Recall that all our values are 64
  17401. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17402. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17403. $011$ for procedures, and $101$ for the void value\python{,
  17404. \key{None}}. We define the following auxiliary function for mapping
  17405. types to tag codes:
  17406. %
  17407. {\if\edition\racketEd
  17408. \begin{align*}
  17409. \itm{tagof}(\key{Integer}) &= 001 \\
  17410. \itm{tagof}(\key{Boolean}) &= 100 \\
  17411. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17412. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17413. \itm{tagof}(\key{Void}) &= 101
  17414. \end{align*}
  17415. \fi}
  17416. {\if\edition\pythonEd\pythonColor
  17417. \begin{align*}
  17418. \itm{tagof}(\key{IntType()}) &= 001 \\
  17419. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17420. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17421. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17422. \itm{tagof}(\key{type(None)}) &= 101
  17423. \end{align*}
  17424. \fi}
  17425. %
  17426. This stealing of 3 bits comes at some price: integers are now restricted
  17427. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17428. affect tuples and procedures because those values are addresses, and
  17429. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17430. they are always $000$. Thus, we do not lose information by overwriting
  17431. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17432. to recover the original address.
  17433. To make tagged values into first-class entities, we can give them a
  17434. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17435. operations such as \code{Inject} and \code{Project} for creating and
  17436. using them, yielding the statically typed \LangAny{} intermediate
  17437. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17438. section~\ref{sec:compile-r7}; in the next section we describe the
  17439. \LangAny{} language in greater detail.
  17440. \section{The \LangAny{} Language}
  17441. \label{sec:Rany-lang}
  17442. \newcommand{\LanyASTRacket}{
  17443. \begin{array}{lcl}
  17444. \Type &::= & \ANYTY \\
  17445. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17446. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17447. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17448. \itm{op} &::= & \code{any-vector-length}
  17449. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17450. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17451. \MID \code{procedure?} \MID \code{void?} \\
  17452. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17453. \end{array}
  17454. }
  17455. \newcommand{\LanyASTPython}{
  17456. \begin{array}{lcl}
  17457. \Type &::= & \key{AnyType()} \\
  17458. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17459. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17460. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17461. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17462. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17463. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17464. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17465. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17466. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17467. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17468. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17469. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17470. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17471. \end{array}
  17472. }
  17473. \begin{figure}[tp]
  17474. \centering
  17475. \begin{tcolorbox}[colback=white]
  17476. \small
  17477. {\if\edition\racketEd
  17478. \[
  17479. \begin{array}{l}
  17480. \gray{\LintOpAST} \\ \hline
  17481. \gray{\LvarASTRacket{}} \\ \hline
  17482. \gray{\LifASTRacket{}} \\ \hline
  17483. \gray{\LwhileASTRacket{}} \\ \hline
  17484. \gray{\LtupASTRacket{}} \\ \hline
  17485. \gray{\LfunASTRacket} \\ \hline
  17486. \gray{\LlambdaASTRacket} \\ \hline
  17487. \LanyASTRacket \\
  17488. \begin{array}{lcl}
  17489. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17490. \end{array}
  17491. \end{array}
  17492. \]
  17493. \fi}
  17494. {\if\edition\pythonEd\pythonColor
  17495. \[
  17496. \begin{array}{l}
  17497. \gray{\LintASTPython} \\ \hline
  17498. \gray{\LvarASTPython{}} \\ \hline
  17499. \gray{\LifASTPython{}} \\ \hline
  17500. \gray{\LwhileASTPython{}} \\ \hline
  17501. \gray{\LtupASTPython{}} \\ \hline
  17502. \gray{\LfunASTPython} \\ \hline
  17503. \gray{\LlambdaASTPython} \\ \hline
  17504. \LanyASTPython \\
  17505. \begin{array}{lcl}
  17506. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17507. \end{array}
  17508. \end{array}
  17509. \]
  17510. \fi}
  17511. \end{tcolorbox}
  17512. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17513. \label{fig:Lany-syntax}
  17514. \end{figure}
  17515. The definition of the abstract syntax of \LangAny{} is given in
  17516. figure~\ref{fig:Lany-syntax}.
  17517. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17518. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17519. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17520. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17521. converts the tagged value produced by expression $e$ into a value of
  17522. type $T$ or halts the program if the type tag does not match $T$.
  17523. %
  17524. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17525. restricted to be a flat type (the nonterminal $\FType$) which
  17526. simplifies the implementation and complies with the needs for
  17527. compiling \LangDyn{}.
  17528. The \racket{\code{any-vector}} operators
  17529. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17530. operations so that they can be applied to a value of type
  17531. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17532. tuple operations in that the index is not restricted to a literal
  17533. integer in the grammar but is allowed to be any expression.
  17534. \racket{The type predicates such as
  17535. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17536. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17537. the predicate and return {\FALSE} otherwise.}
  17538. The type checker for \LangAny{} is shown in
  17539. figure~\ref{fig:type-check-Lany}
  17540. %
  17541. \racket{ and uses the auxiliary functions presented in
  17542. figure~\ref{fig:type-check-Lany-aux}}.
  17543. %
  17544. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17545. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17546. \begin{figure}[btp]
  17547. \begin{tcolorbox}[colback=white]
  17548. {\if\edition\racketEd
  17549. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17550. (define type-check-Lany-class
  17551. (class type-check-Llambda-class
  17552. (super-new)
  17553. (inherit check-type-equal?)
  17554. (define/override (type-check-exp env)
  17555. (lambda (e)
  17556. (define recur (type-check-exp env))
  17557. (match e
  17558. [(Inject e1 ty)
  17559. (unless (flat-ty? ty)
  17560. (error 'type-check "may only inject from flat type, not ~a" ty))
  17561. (define-values (new-e1 e-ty) (recur e1))
  17562. (check-type-equal? e-ty ty e)
  17563. (values (Inject new-e1 ty) 'Any)]
  17564. [(Project e1 ty)
  17565. (unless (flat-ty? ty)
  17566. (error 'type-check "may only project to flat type, not ~a" ty))
  17567. (define-values (new-e1 e-ty) (recur e1))
  17568. (check-type-equal? e-ty 'Any e)
  17569. (values (Project new-e1 ty) ty)]
  17570. [(Prim 'any-vector-length (list e1))
  17571. (define-values (e1^ t1) (recur e1))
  17572. (check-type-equal? t1 'Any e)
  17573. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17574. [(Prim 'any-vector-ref (list e1 e2))
  17575. (define-values (e1^ t1) (recur e1))
  17576. (define-values (e2^ t2) (recur e2))
  17577. (check-type-equal? t1 'Any e)
  17578. (check-type-equal? t2 'Integer e)
  17579. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17580. [(Prim 'any-vector-set! (list e1 e2 e3))
  17581. (define-values (e1^ t1) (recur e1))
  17582. (define-values (e2^ t2) (recur e2))
  17583. (define-values (e3^ t3) (recur e3))
  17584. (check-type-equal? t1 'Any e)
  17585. (check-type-equal? t2 'Integer e)
  17586. (check-type-equal? t3 'Any e)
  17587. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17588. [(Prim pred (list e1))
  17589. #:when (set-member? (type-predicates) pred)
  17590. (define-values (new-e1 e-ty) (recur e1))
  17591. (check-type-equal? e-ty 'Any e)
  17592. (values (Prim pred (list new-e1)) 'Boolean)]
  17593. [(Prim 'eq? (list arg1 arg2))
  17594. (define-values (e1 t1) (recur arg1))
  17595. (define-values (e2 t2) (recur arg2))
  17596. (match* (t1 t2)
  17597. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17598. [(other wise) (check-type-equal? t1 t2 e)])
  17599. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17600. [else ((super type-check-exp env) e)])))
  17601. ))
  17602. \end{lstlisting}
  17603. \fi}
  17604. {\if\edition\pythonEd\pythonColor
  17605. \begin{lstlisting}
  17606. class TypeCheckLany(TypeCheckLlambda):
  17607. def type_check_exp(self, e, env):
  17608. match e:
  17609. case Inject(value, typ):
  17610. self.check_exp(value, typ, env)
  17611. return AnyType()
  17612. case Project(value, typ):
  17613. self.check_exp(value, AnyType(), env)
  17614. return typ
  17615. case Call(Name('any_tuple_load'), [tup, index]):
  17616. self.check_exp(tup, AnyType(), env)
  17617. self.check_exp(index, IntType(), env)
  17618. return AnyType()
  17619. case Call(Name('any_len'), [tup]):
  17620. self.check_exp(tup, AnyType(), env)
  17621. return IntType()
  17622. case Call(Name('arity'), [fun]):
  17623. ty = self.type_check_exp(fun, env)
  17624. match ty:
  17625. case FunctionType(ps, rt):
  17626. return IntType()
  17627. case TupleType([FunctionType(ps,rs)]):
  17628. return IntType()
  17629. case _:
  17630. raise Exception('type check arity unexpected ' + repr(ty))
  17631. case Call(Name('make_any'), [value, tag]):
  17632. self.type_check_exp(value, env)
  17633. self.check_exp(tag, IntType(), env)
  17634. return AnyType()
  17635. case AnnLambda(params, returns, body):
  17636. new_env = {x:t for (x,t) in env.items()}
  17637. for (x,t) in params:
  17638. new_env[x] = t
  17639. return_t = self.type_check_exp(body, new_env)
  17640. self.check_type_equal(returns, return_t, e)
  17641. return FunctionType([t for (x,t) in params], return_t)
  17642. case _:
  17643. return super().type_check_exp(e, env)
  17644. \end{lstlisting}
  17645. \fi}
  17646. \end{tcolorbox}
  17647. \caption{Type checker for the \LangAny{} language.}
  17648. \label{fig:type-check-Lany}
  17649. \end{figure}
  17650. {\if\edition\racketEd
  17651. \begin{figure}[tbp]
  17652. \begin{tcolorbox}[colback=white]
  17653. \begin{lstlisting}
  17654. (define/override (operator-types)
  17655. (append
  17656. '((integer? . ((Any) . Boolean))
  17657. (vector? . ((Any) . Boolean))
  17658. (procedure? . ((Any) . Boolean))
  17659. (void? . ((Any) . Boolean)))
  17660. (super operator-types)))
  17661. (define/public (type-predicates)
  17662. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17663. (define/public (flat-ty? ty)
  17664. (match ty
  17665. [(or `Integer `Boolean `Void) #t]
  17666. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17667. [`(,ts ... -> ,rt)
  17668. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17669. [else #f]))
  17670. \end{lstlisting}
  17671. \end{tcolorbox}
  17672. \caption{Auxiliary methods for type checking \LangAny{}.}
  17673. \label{fig:type-check-Lany-aux}
  17674. \end{figure}
  17675. \fi}
  17676. \begin{figure}[tbp]
  17677. \begin{tcolorbox}[colback=white]
  17678. {\if\edition\racketEd
  17679. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17680. (define interp-Lany-class
  17681. (class interp-Llambda-class
  17682. (super-new)
  17683. (define/override (interp-op op)
  17684. (match op
  17685. ['boolean? (match-lambda
  17686. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17687. [else #f])]
  17688. ['integer? (match-lambda
  17689. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17690. [else #f])]
  17691. ['vector? (match-lambda
  17692. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17693. [else #f])]
  17694. ['procedure? (match-lambda
  17695. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17696. [else #f])]
  17697. ['eq? (match-lambda*
  17698. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17699. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17700. [ls (apply (super interp-op op) ls)])]
  17701. ['any-vector-ref (lambda (v i)
  17702. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17703. ['any-vector-set! (lambda (v i a)
  17704. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17705. ['any-vector-length (lambda (v)
  17706. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17707. [else (super interp-op op)]))
  17708. (define/override ((interp-exp env) e)
  17709. (define recur (interp-exp env))
  17710. (match e
  17711. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17712. [(Project e ty2) (apply-project (recur e) ty2)]
  17713. [else ((super interp-exp env) e)]))
  17714. ))
  17715. (define (interp-Lany p)
  17716. (send (new interp-Lany-class) interp-program p))
  17717. \end{lstlisting}
  17718. \fi}
  17719. {\if\edition\pythonEd\pythonColor
  17720. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17721. class InterpLany(InterpLlambda):
  17722. def interp_exp(self, e, env):
  17723. match e:
  17724. case Inject(value, typ):
  17725. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17726. case Project(value, typ):
  17727. match self.interp_exp(value, env):
  17728. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17729. return val
  17730. case _:
  17731. raise Exception('failed project to ' + self.type_to_tag(typ))
  17732. case Call(Name('any_tuple_load'), [tup, index]):
  17733. match self.interp_exp(tup, env):
  17734. case Tagged(v, tag):
  17735. return v[self.interp_exp(index, env)]
  17736. case _:
  17737. raise Exception('in any_tuple_load untagged value')
  17738. case Call(Name('any_len'), [value]):
  17739. match self.interp_exp(value, env):
  17740. case Tagged(value, tag):
  17741. return len(value)
  17742. case _:
  17743. raise Exception('interp any_len untagged value')
  17744. case Call(Name('arity'), [fun]):
  17745. return self.arity(self.interp_exp(fun, env))
  17746. case _:
  17747. return super().interp_exp(e, env)
  17748. \end{lstlisting}
  17749. \fi}
  17750. \end{tcolorbox}
  17751. \caption{Interpreter for \LangAny{}.}
  17752. \label{fig:interp-Lany}
  17753. \end{figure}
  17754. \begin{figure}[btp]
  17755. \begin{tcolorbox}[colback=white]
  17756. {\if\edition\racketEd
  17757. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17758. (define/public (apply-inject v tg) (Tagged v tg))
  17759. (define/public (apply-project v ty2)
  17760. (define tag2 (any-tag ty2))
  17761. (match v
  17762. [(Tagged v1 tag1)
  17763. (cond
  17764. [(eq? tag1 tag2)
  17765. (match ty2
  17766. [`(Vector ,ts ...)
  17767. (define l1 ((interp-op 'vector-length) v1))
  17768. (cond
  17769. [(eq? l1 (length ts)) v1]
  17770. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17771. l1 (length ts))])]
  17772. [`(,ts ... -> ,rt)
  17773. (match v1
  17774. [`(function ,xs ,body ,env)
  17775. (cond [(eq? (length xs) (length ts)) v1]
  17776. [else
  17777. (error 'apply-project "arity mismatch ~a != ~a"
  17778. (length xs) (length ts))])]
  17779. [else (error 'apply-project "expected function not ~a" v1)])]
  17780. [else v1])]
  17781. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17782. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17783. \end{lstlisting}
  17784. \fi}
  17785. {\if\edition\pythonEd\pythonColor
  17786. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17787. class InterpLany(InterpLlambda):
  17788. def type_to_tag(self, typ):
  17789. match typ:
  17790. case FunctionType(params, rt):
  17791. return 'function'
  17792. case TupleType(fields):
  17793. return 'tuple'
  17794. case IntType():
  17795. return 'int'
  17796. case BoolType():
  17797. return 'bool'
  17798. case _:
  17799. raise Exception('type_to_tag unexpected ' + repr(typ))
  17800. def arity(self, v):
  17801. match v:
  17802. case Function(name, params, body, env):
  17803. return len(params)
  17804. case _:
  17805. raise Exception('Lany arity unexpected ' + repr(v))
  17806. \end{lstlisting}
  17807. \fi}
  17808. \end{tcolorbox}
  17809. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17810. \label{fig:interp-Lany-aux}
  17811. \end{figure}
  17812. \clearpage
  17813. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17814. \label{sec:compile-r7}
  17815. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17816. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17817. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17818. is that given any subexpression $e$ in the \LangDyn{} program, the
  17819. pass will produce an expression $e'$ in \LangAny{} that has type
  17820. \ANYTY{}. For example, the first row in
  17821. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17822. \TRUE{}, which must be injected to produce an expression of type
  17823. \ANYTY{}.
  17824. %
  17825. The compilation of addition is shown in the second row of
  17826. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17827. representative of many primitive operations: the arguments have type
  17828. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17829. be performed.
  17830. The compilation of \key{lambda} (third row of
  17831. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17832. produce type annotations: we simply use \ANYTY{}.
  17833. %
  17834. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17835. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17836. this pass has to account for some differences in behavior between
  17837. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17838. permissive than \LangAny{} regarding what kind of values can be used
  17839. in various places. For example, the condition of an \key{if} does
  17840. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17841. of the same type (in that case the result is \code{\#f}).}
  17842. \begin{figure}[btp]
  17843. \centering
  17844. \begin{tcolorbox}[colback=white]
  17845. {\if\edition\racketEd
  17846. \begin{tabular}{lll}
  17847. \begin{minipage}{0.27\textwidth}
  17848. \begin{lstlisting}
  17849. #t
  17850. \end{lstlisting}
  17851. \end{minipage}
  17852. &
  17853. $\Rightarrow$
  17854. &
  17855. \begin{minipage}{0.65\textwidth}
  17856. \begin{lstlisting}
  17857. (inject #t Boolean)
  17858. \end{lstlisting}
  17859. \end{minipage}
  17860. \\[2ex]\hline
  17861. \begin{minipage}{0.27\textwidth}
  17862. \begin{lstlisting}
  17863. (+ |$e_1$| |$e_2$|)
  17864. \end{lstlisting}
  17865. \end{minipage}
  17866. &
  17867. $\Rightarrow$
  17868. &
  17869. \begin{minipage}{0.65\textwidth}
  17870. \begin{lstlisting}
  17871. (inject
  17872. (+ (project |$e'_1$| Integer)
  17873. (project |$e'_2$| Integer))
  17874. Integer)
  17875. \end{lstlisting}
  17876. \end{minipage}
  17877. \\[2ex]\hline
  17878. \begin{minipage}{0.27\textwidth}
  17879. \begin{lstlisting}
  17880. (lambda (|$x_1 \ldots$|) |$e$|)
  17881. \end{lstlisting}
  17882. \end{minipage}
  17883. &
  17884. $\Rightarrow$
  17885. &
  17886. \begin{minipage}{0.65\textwidth}
  17887. \begin{lstlisting}
  17888. (inject
  17889. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17890. (Any|$\ldots$|Any -> Any))
  17891. \end{lstlisting}
  17892. \end{minipage}
  17893. \\[2ex]\hline
  17894. \begin{minipage}{0.27\textwidth}
  17895. \begin{lstlisting}
  17896. (|$e_0$| |$e_1 \ldots e_n$|)
  17897. \end{lstlisting}
  17898. \end{minipage}
  17899. &
  17900. $\Rightarrow$
  17901. &
  17902. \begin{minipage}{0.65\textwidth}
  17903. \begin{lstlisting}
  17904. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17905. \end{lstlisting}
  17906. \end{minipage}
  17907. \\[2ex]\hline
  17908. \begin{minipage}{0.27\textwidth}
  17909. \begin{lstlisting}
  17910. (vector-ref |$e_1$| |$e_2$|)
  17911. \end{lstlisting}
  17912. \end{minipage}
  17913. &
  17914. $\Rightarrow$
  17915. &
  17916. \begin{minipage}{0.65\textwidth}
  17917. \begin{lstlisting}
  17918. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17919. \end{lstlisting}
  17920. \end{minipage}
  17921. \\[2ex]\hline
  17922. \begin{minipage}{0.27\textwidth}
  17923. \begin{lstlisting}
  17924. (if |$e_1$| |$e_2$| |$e_3$|)
  17925. \end{lstlisting}
  17926. \end{minipage}
  17927. &
  17928. $\Rightarrow$
  17929. &
  17930. \begin{minipage}{0.65\textwidth}
  17931. \begin{lstlisting}
  17932. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17933. \end{lstlisting}
  17934. \end{minipage}
  17935. \\[2ex]\hline
  17936. \begin{minipage}{0.27\textwidth}
  17937. \begin{lstlisting}
  17938. (eq? |$e_1$| |$e_2$|)
  17939. \end{lstlisting}
  17940. \end{minipage}
  17941. &
  17942. $\Rightarrow$
  17943. &
  17944. \begin{minipage}{0.65\textwidth}
  17945. \begin{lstlisting}
  17946. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17947. \end{lstlisting}
  17948. \end{minipage}
  17949. \\[2ex]\hline
  17950. \begin{minipage}{0.27\textwidth}
  17951. \begin{lstlisting}
  17952. (not |$e_1$|)
  17953. \end{lstlisting}
  17954. \end{minipage}
  17955. &
  17956. $\Rightarrow$
  17957. &
  17958. \begin{minipage}{0.65\textwidth}
  17959. \begin{lstlisting}
  17960. (if (eq? |$e'_1$| (inject #f Boolean))
  17961. (inject #t Boolean) (inject #f Boolean))
  17962. \end{lstlisting}
  17963. \end{minipage}
  17964. \end{tabular}
  17965. \fi}
  17966. {\if\edition\pythonEd\pythonColor
  17967. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17968. \begin{minipage}{0.23\textwidth}
  17969. \begin{lstlisting}
  17970. True
  17971. \end{lstlisting}
  17972. \end{minipage}
  17973. &
  17974. $\Rightarrow$
  17975. &
  17976. \begin{minipage}{0.7\textwidth}
  17977. \begin{lstlisting}
  17978. Inject(True, BoolType())
  17979. \end{lstlisting}
  17980. \end{minipage}
  17981. \\[2ex]\hline
  17982. \begin{minipage}{0.23\textwidth}
  17983. \begin{lstlisting}
  17984. |$e_1$| + |$e_2$|
  17985. \end{lstlisting}
  17986. \end{minipage}
  17987. &
  17988. $\Rightarrow$
  17989. &
  17990. \begin{minipage}{0.7\textwidth}
  17991. \begin{lstlisting}
  17992. Inject(Project(|$e'_1$|, IntType())
  17993. + Project(|$e'_2$|, IntType()),
  17994. IntType())
  17995. \end{lstlisting}
  17996. \end{minipage}
  17997. \\[2ex]\hline
  17998. \begin{minipage}{0.23\textwidth}
  17999. \begin{lstlisting}
  18000. lambda |$x_1 \ldots$|: |$e$|
  18001. \end{lstlisting}
  18002. \end{minipage}
  18003. &
  18004. $\Rightarrow$
  18005. &
  18006. \begin{minipage}{0.7\textwidth}
  18007. \begin{lstlisting}
  18008. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18009. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18010. \end{lstlisting}
  18011. \end{minipage}
  18012. \\[2ex]\hline
  18013. \begin{minipage}{0.23\textwidth}
  18014. \begin{lstlisting}
  18015. |$e_0$|(|$e_1 \ldots e_n$|)
  18016. \end{lstlisting}
  18017. \end{minipage}
  18018. &
  18019. $\Rightarrow$
  18020. &
  18021. \begin{minipage}{0.7\textwidth}
  18022. \begin{lstlisting}
  18023. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18024. AnyType())), |$e'_1, \ldots, e'_n$|)
  18025. \end{lstlisting}
  18026. \end{minipage}
  18027. \\[2ex]\hline
  18028. \begin{minipage}{0.23\textwidth}
  18029. \begin{lstlisting}
  18030. |$e_1$|[|$e_2$|]
  18031. \end{lstlisting}
  18032. \end{minipage}
  18033. &
  18034. $\Rightarrow$
  18035. &
  18036. \begin{minipage}{0.7\textwidth}
  18037. \begin{lstlisting}
  18038. Call(Name('any_tuple_load'),
  18039. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18040. \end{lstlisting}
  18041. \end{minipage}
  18042. %% \begin{minipage}{0.23\textwidth}
  18043. %% \begin{lstlisting}
  18044. %% |$e_2$| if |$e_1$| else |$e_3$|
  18045. %% \end{lstlisting}
  18046. %% \end{minipage}
  18047. %% &
  18048. %% $\Rightarrow$
  18049. %% &
  18050. %% \begin{minipage}{0.7\textwidth}
  18051. %% \begin{lstlisting}
  18052. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18053. %% \end{lstlisting}
  18054. %% \end{minipage}
  18055. %% \\[2ex]\hline
  18056. %% \begin{minipage}{0.23\textwidth}
  18057. %% \begin{lstlisting}
  18058. %% (eq? |$e_1$| |$e_2$|)
  18059. %% \end{lstlisting}
  18060. %% \end{minipage}
  18061. %% &
  18062. %% $\Rightarrow$
  18063. %% &
  18064. %% \begin{minipage}{0.7\textwidth}
  18065. %% \begin{lstlisting}
  18066. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18067. %% \end{lstlisting}
  18068. %% \end{minipage}
  18069. %% \\[2ex]\hline
  18070. %% \begin{minipage}{0.23\textwidth}
  18071. %% \begin{lstlisting}
  18072. %% (not |$e_1$|)
  18073. %% \end{lstlisting}
  18074. %% \end{minipage}
  18075. %% &
  18076. %% $\Rightarrow$
  18077. %% &
  18078. %% \begin{minipage}{0.7\textwidth}
  18079. %% \begin{lstlisting}
  18080. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18081. %% (inject #t Boolean) (inject #f Boolean))
  18082. %% \end{lstlisting}
  18083. %% \end{minipage}
  18084. %% \\[2ex]\hline
  18085. \\\hline
  18086. \end{tabular}
  18087. \fi}
  18088. \end{tcolorbox}
  18089. \caption{Cast insertion.}
  18090. \label{fig:compile-r7-Lany}
  18091. \end{figure}
  18092. \section{Reveal Casts}
  18093. \label{sec:reveal-casts-Lany}
  18094. % TODO: define R'_6
  18095. In the \code{reveal\_casts} pass, we recommend compiling
  18096. \code{Project} into a conditional expression that checks whether the
  18097. value's tag matches the target type; if it does, the value is
  18098. converted to a value of the target type by removing the tag; if it
  18099. does not, the program exits.
  18100. %
  18101. {\if\edition\racketEd
  18102. %
  18103. To perform these actions we need a new primitive operation,
  18104. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18105. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18106. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18107. underlying value from a tagged value. The \code{ValueOf} form
  18108. includes the type for the underlying value that is used by the type
  18109. checker.
  18110. %
  18111. \fi}
  18112. %
  18113. {\if\edition\pythonEd\pythonColor
  18114. %
  18115. To perform these actions we need two new AST classes: \code{TagOf} and
  18116. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18117. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18118. the underlying value from a tagged value. The \code{ValueOf}
  18119. operation includes the type for the underlying value that is used by
  18120. the type checker.
  18121. %
  18122. \fi}
  18123. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18124. \code{Project} can be translated as follows:
  18125. \begin{center}
  18126. \begin{minipage}{1.0\textwidth}
  18127. {\if\edition\racketEd
  18128. \begin{lstlisting}
  18129. (Project |$e$| |$\FType$|)
  18130. |$\Rightarrow$|
  18131. (Let |$\itm{tmp}$| |$e'$|
  18132. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18133. (Int |$\itm{tagof}(\FType)$|)))
  18134. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18135. (Exit)))
  18136. \end{lstlisting}
  18137. \fi}
  18138. {\if\edition\pythonEd\pythonColor
  18139. \begin{lstlisting}
  18140. Project(|$e$|, |$\FType$|)
  18141. |$\Rightarrow$|
  18142. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18143. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18144. [Constant(|$\itm{tagof}(\FType)$|)]),
  18145. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18146. Call(Name('exit'), [])))
  18147. \end{lstlisting}
  18148. \fi}
  18149. \end{minipage}
  18150. \end{center}
  18151. If the target type of the projection is a tuple or function type, then
  18152. there is a bit more work to do. For tuples, check that the length of
  18153. the tuple type matches the length of the tuple. For functions, check
  18154. that the number of parameters in the function type matches the
  18155. function's arity.
  18156. Regarding \code{Inject}, we recommend compiling it to a slightly
  18157. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18158. takes a tag instead of a type.
  18159. \begin{center}
  18160. \begin{minipage}{1.0\textwidth}
  18161. {\if\edition\racketEd
  18162. \begin{lstlisting}
  18163. (Inject |$e$| |$\FType$|)
  18164. |$\Rightarrow$|
  18165. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18166. \end{lstlisting}
  18167. \fi}
  18168. {\if\edition\pythonEd\pythonColor
  18169. \begin{lstlisting}
  18170. Inject(|$e$|, |$\FType$|)
  18171. |$\Rightarrow$|
  18172. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18173. \end{lstlisting}
  18174. \fi}
  18175. \end{minipage}
  18176. \end{center}
  18177. {\if\edition\pythonEd\pythonColor
  18178. %
  18179. The introduction of \code{make\_any} makes it difficult to use
  18180. bidirectional type checking because we no longer have an expected type
  18181. to use for type checking the expression $e'$. Thus, we run into
  18182. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18183. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18184. annotated lambda) that contains its return type and the types of its
  18185. parameters.
  18186. %
  18187. \fi}
  18188. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18189. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18190. translation of \code{Project}.}
  18191. {\if\edition\racketEd
  18192. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18193. combine the projection action with the vector operation. Also, the
  18194. read and write operations allow arbitrary expressions for the index, so
  18195. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18196. cannot guarantee that the index is within bounds. Thus, we insert code
  18197. to perform bounds checking at runtime. The translation for
  18198. \code{any-vector-ref} is as follows, and the other two operations are
  18199. translated in a similar way:
  18200. \begin{center}
  18201. \begin{minipage}{0.95\textwidth}
  18202. \begin{lstlisting}
  18203. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18204. |$\Rightarrow$|
  18205. (Let |$v$| |$e'_1$|
  18206. (Let |$i$| |$e'_2$|
  18207. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18208. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18209. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18210. (Exit))
  18211. (Exit))))
  18212. \end{lstlisting}
  18213. \end{minipage}
  18214. \end{center}
  18215. \fi}
  18216. %
  18217. {\if\edition\pythonEd\pythonColor
  18218. %
  18219. The \code{any\_tuple\_load} operation combines the projection action
  18220. with the load operation. Also, the load operation allows arbitrary
  18221. expressions for the index, so the type checker for \LangAny{}
  18222. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18223. within bounds. Thus, we insert code to perform bounds checking at
  18224. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18225. \begin{lstlisting}
  18226. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18227. |$\Rightarrow$|
  18228. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18229. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18230. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18231. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18232. Call(Name('exit'), [])),
  18233. Call(Name('exit'), [])))
  18234. \end{lstlisting}
  18235. \fi}
  18236. {\if\edition\pythonEd\pythonColor
  18237. \section{Assignment Conversion}
  18238. \label{sec:convert-assignments-Lany}
  18239. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18240. \code{AnnLambda} AST classes.
  18241. \section{Closure Conversion}
  18242. \label{sec:closure-conversion-Lany}
  18243. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18244. \code{AnnLambda} AST classes.
  18245. \fi}
  18246. \section{Remove Complex Operands}
  18247. \label{sec:rco-Lany}
  18248. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18249. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18250. %
  18251. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18252. complex expressions. Their subexpressions must be atomic.}
  18253. \section{Explicate Control and \LangCAny{}}
  18254. \label{sec:explicate-Lany}
  18255. The output of \code{explicate\_control} is the \LangCAny{} language,
  18256. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18257. %
  18258. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18259. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18260. note that the index argument of \code{vector-ref} and
  18261. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18262. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18263. %
  18264. \python{Update the auxiliary functions \code{explicate\_tail},
  18265. \code{explicate\_effect}, and \code{explicate\_pred} as
  18266. appropriate to handle the new expressions in \LangCAny{}. }
  18267. \newcommand{\CanyASTPython}{
  18268. \begin{array}{lcl}
  18269. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18270. &\MID& \key{TagOf}\LP \Atm \RP
  18271. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18272. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18273. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18274. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18275. \end{array}
  18276. }
  18277. \newcommand{\CanyASTRacket}{
  18278. \begin{array}{lcl}
  18279. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18280. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18281. &\MID& \VALUEOF{\Atm}{\FType} \\
  18282. \Tail &::= & \LP\key{Exit}\RP
  18283. \end{array}
  18284. }
  18285. \begin{figure}[tp]
  18286. \begin{tcolorbox}[colback=white]
  18287. \small
  18288. {\if\edition\racketEd
  18289. \[
  18290. \begin{array}{l}
  18291. \gray{\CvarASTRacket} \\ \hline
  18292. \gray{\CifASTRacket} \\ \hline
  18293. \gray{\CloopASTRacket} \\ \hline
  18294. \gray{\CtupASTRacket} \\ \hline
  18295. \gray{\CfunASTRacket} \\ \hline
  18296. \gray{\ClambdaASTRacket} \\ \hline
  18297. \CanyASTRacket \\
  18298. \begin{array}{lcl}
  18299. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18300. \end{array}
  18301. \end{array}
  18302. \]
  18303. \fi}
  18304. {\if\edition\pythonEd\pythonColor
  18305. \[
  18306. \begin{array}{l}
  18307. \gray{\CifASTPython} \\ \hline
  18308. \gray{\CtupASTPython} \\ \hline
  18309. \gray{\CfunASTPython} \\ \hline
  18310. \gray{\ClambdaASTPython} \\ \hline
  18311. \CanyASTPython \\
  18312. \begin{array}{lcl}
  18313. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18314. \end{array}
  18315. \end{array}
  18316. \]
  18317. \fi}
  18318. \end{tcolorbox}
  18319. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18320. \label{fig:c5-syntax}
  18321. \end{figure}
  18322. \section{Select Instructions}
  18323. \label{sec:select-Lany}
  18324. \index{subject}{select instructions}
  18325. In the \code{select\_instructions} pass, we translate the primitive
  18326. operations on the \ANYTY{} type to x86 instructions that manipulate
  18327. the three tag bits of the tagged value. In the following descriptions,
  18328. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18329. of translating $e$ into an x86 argument:
  18330. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18331. We recommend compiling the
  18332. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18333. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18334. shifts the destination to the left by the number of bits specified by its
  18335. source argument (in this case three, the length of the tag), and it
  18336. preserves the sign of the integer. We use the \key{orq} instruction to
  18337. combine the tag and the value to form the tagged value.
  18338. {\if\edition\racketEd
  18339. \begin{lstlisting}
  18340. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18341. |$\Rightarrow$|
  18342. movq |$e'$|, |\itm{lhs'}|
  18343. salq $3, |\itm{lhs'}|
  18344. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18345. \end{lstlisting}
  18346. \fi}
  18347. %
  18348. {\if\edition\pythonEd\pythonColor
  18349. \begin{lstlisting}
  18350. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18351. |$\Rightarrow$|
  18352. movq |$e'$|, |\itm{lhs'}|
  18353. salq $3, |\itm{lhs'}|
  18354. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18355. \end{lstlisting}
  18356. \fi}
  18357. %
  18358. The instruction selection\index{subject}{instruction selection} for
  18359. tuples and procedures is different because there is no need to shift
  18360. them to the left. The rightmost 3 bits are already zeros, so we simply
  18361. combine the value and the tag using \key{orq}. \\
  18362. %
  18363. {\if\edition\racketEd
  18364. \begin{center}
  18365. \begin{minipage}{\textwidth}
  18366. \begin{lstlisting}
  18367. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18368. |$\Rightarrow$|
  18369. movq |$e'$|, |\itm{lhs'}|
  18370. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18371. \end{lstlisting}
  18372. \end{minipage}
  18373. \end{center}
  18374. \fi}
  18375. %
  18376. {\if\edition\pythonEd\pythonColor
  18377. \begin{lstlisting}
  18378. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18379. |$\Rightarrow$|
  18380. movq |$e'$|, |\itm{lhs'}|
  18381. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18382. \end{lstlisting}
  18383. \fi}
  18384. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18385. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18386. operation extracts the type tag from a value of type \ANYTY{}. The
  18387. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18388. bitwise-and of the value with $111$ ($7$ decimal).
  18389. %
  18390. {\if\edition\racketEd
  18391. \begin{lstlisting}
  18392. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18393. |$\Rightarrow$|
  18394. movq |$e'$|, |\itm{lhs'}|
  18395. andq $7, |\itm{lhs'}|
  18396. \end{lstlisting}
  18397. \fi}
  18398. %
  18399. {\if\edition\pythonEd\pythonColor
  18400. \begin{lstlisting}
  18401. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18402. |$\Rightarrow$|
  18403. movq |$e'$|, |\itm{lhs'}|
  18404. andq $7, |\itm{lhs'}|
  18405. \end{lstlisting}
  18406. \fi}
  18407. \paragraph{\code{ValueOf}}
  18408. The instructions for \key{ValueOf} also differ, depending on whether
  18409. the type $T$ is a pointer (tuple or function) or not (integer or
  18410. Boolean). The following shows the instruction
  18411. selection for integers and
  18412. Booleans, in which we produce an untagged value by shifting it to the
  18413. right by 3 bits:
  18414. %
  18415. {\if\edition\racketEd
  18416. \begin{lstlisting}
  18417. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18418. |$\Rightarrow$|
  18419. movq |$e'$|, |\itm{lhs'}|
  18420. sarq $3, |\itm{lhs'}|
  18421. \end{lstlisting}
  18422. \fi}
  18423. %
  18424. {\if\edition\pythonEd\pythonColor
  18425. \begin{lstlisting}
  18426. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18427. |$\Rightarrow$|
  18428. movq |$e'$|, |\itm{lhs'}|
  18429. sarq $3, |\itm{lhs'}|
  18430. \end{lstlisting}
  18431. \fi}
  18432. %
  18433. In the case for tuples and procedures, we zero out the rightmost 3
  18434. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18435. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18436. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18437. Finally, we apply \code{andq} with the tagged value to get the desired
  18438. result.
  18439. %
  18440. {\if\edition\racketEd
  18441. \begin{lstlisting}
  18442. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18443. |$\Rightarrow$|
  18444. movq $|$-8$|, |\itm{lhs'}|
  18445. andq |$e'$|, |\itm{lhs'}|
  18446. \end{lstlisting}
  18447. \fi}
  18448. %
  18449. {\if\edition\pythonEd\pythonColor
  18450. \begin{lstlisting}
  18451. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18452. |$\Rightarrow$|
  18453. movq $|$-8$|, |\itm{lhs'}|
  18454. andq |$e'$|, |\itm{lhs'}|
  18455. \end{lstlisting}
  18456. \fi}
  18457. %% \paragraph{Type Predicates} We leave it to the reader to
  18458. %% devise a sequence of instructions to implement the type predicates
  18459. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18460. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18461. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18462. operation combines the effect of \code{ValueOf} with accessing the
  18463. length of a tuple from the tag stored at the zero index of the tuple.
  18464. {\if\edition\racketEd
  18465. \begin{lstlisting}
  18466. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18467. |$\Longrightarrow$|
  18468. movq $|$-8$|, %r11
  18469. andq |$e_1'$|, %r11
  18470. movq 0(%r11), %r11
  18471. andq $126, %r11
  18472. sarq $1, %r11
  18473. movq %r11, |$\itm{lhs'}$|
  18474. \end{lstlisting}
  18475. \fi}
  18476. {\if\edition\pythonEd\pythonColor
  18477. \begin{lstlisting}
  18478. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18479. |$\Longrightarrow$|
  18480. movq $|$-8$|, %r11
  18481. andq |$e_1'$|, %r11
  18482. movq 0(%r11), %r11
  18483. andq $126, %r11
  18484. sarq $1, %r11
  18485. movq %r11, |$\itm{lhs'}$|
  18486. \end{lstlisting}
  18487. \fi}
  18488. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18489. This operation combines the effect of \code{ValueOf} with reading an
  18490. element of the tuple (see
  18491. section~\ref{sec:select-instructions-gc}). However, the index may be
  18492. an arbitrary atom, so instead of computing the offset at compile time,
  18493. we must generate instructions to compute the offset at runtime as
  18494. follows. Note the use of the new instruction \code{imulq}.
  18495. \begin{center}
  18496. \begin{minipage}{0.96\textwidth}
  18497. {\if\edition\racketEd
  18498. \begin{lstlisting}
  18499. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18500. |$\Longrightarrow$|
  18501. movq |$\neg 111$|, %r11
  18502. andq |$e_1'$|, %r11
  18503. movq |$e_2'$|, %rax
  18504. addq $1, %rax
  18505. imulq $8, %rax
  18506. addq %rax, %r11
  18507. movq 0(%r11) |$\itm{lhs'}$|
  18508. \end{lstlisting}
  18509. \fi}
  18510. %
  18511. {\if\edition\pythonEd\pythonColor
  18512. \begin{lstlisting}
  18513. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18514. |$\Longrightarrow$|
  18515. movq $|$-8$|, %r11
  18516. andq |$e_1'$|, %r11
  18517. movq |$e_2'$|, %rax
  18518. addq $1, %rax
  18519. imulq $8, %rax
  18520. addq %rax, %r11
  18521. movq 0(%r11) |$\itm{lhs'}$|
  18522. \end{lstlisting}
  18523. \fi}
  18524. \end{minipage}
  18525. \end{center}
  18526. % $ pacify font lock
  18527. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18528. %% The code generation for
  18529. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18530. %% analogous to the above translation for reading from a tuple.
  18531. \section{Register Allocation for \LangAny{} }
  18532. \label{sec:register-allocation-Lany}
  18533. \index{subject}{register allocation}
  18534. There is an interesting interaction between tagged values and garbage
  18535. collection that has an impact on register allocation. A variable of
  18536. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18537. that needs to be inspected and copied during garbage collection. Thus,
  18538. we need to treat variables of type \ANYTY{} in a similar way to
  18539. variables of tuple type for purposes of register allocation,
  18540. with particular attention to the following:
  18541. \begin{itemize}
  18542. \item If a variable of type \ANYTY{} is live during a function call,
  18543. then it must be spilled. This can be accomplished by changing
  18544. \code{build\_interference} to mark all variables of type \ANYTY{}
  18545. that are live after a \code{callq} to be interfering with all the
  18546. registers.
  18547. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18548. the root stack instead of the normal procedure call stack.
  18549. \end{itemize}
  18550. Another concern regarding the root stack is that the garbage collector
  18551. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18552. tagged value that points to a tuple, and (3) a tagged value that is
  18553. not a tuple. We enable this differentiation by choosing not to use the
  18554. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18555. reserved for identifying plain old pointers to tuples. That way, if
  18556. one of the first three bits is set, then we have a tagged value and
  18557. inspecting the tag can differentiate between tuples ($010$) and the
  18558. other kinds of values.
  18559. %% \begin{exercise}\normalfont
  18560. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18561. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18562. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18563. %% compiler on these new programs and all of your previously created test
  18564. %% programs.
  18565. %% \end{exercise}
  18566. \begin{exercise}\normalfont\normalsize
  18567. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18568. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18569. by removing type annotations. Add five more test programs that
  18570. specifically rely on the language being dynamically typed. That is,
  18571. they should not be legal programs in a statically typed language, but
  18572. nevertheless they should be valid \LangDyn{} programs that run to
  18573. completion without error.
  18574. \end{exercise}
  18575. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18576. for the compilation of \LangDyn{}.
  18577. \begin{figure}[bthp]
  18578. \begin{tcolorbox}[colback=white]
  18579. {\if\edition\racketEd
  18580. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18581. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18582. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18583. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18584. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18585. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18586. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18587. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18588. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18589. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18590. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18591. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18592. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18593. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18594. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18595. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18596. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18597. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18598. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18599. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18600. \path[->,bend left=15] (Lfun) edge [above] node
  18601. {\ttfamily\footnotesize shrink} (Lfun-2);
  18602. \path[->,bend left=15] (Lfun-2) edge [above] node
  18603. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18604. \path[->,bend left=15] (Lfun-3) edge [above] node
  18605. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18606. \path[->,bend left=15] (Lfun-4) edge [left] node
  18607. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18608. \path[->,bend left=15] (Lfun-5) edge [below] node
  18609. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18610. \path[->,bend left=15] (Lfun-6) edge [below] node
  18611. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18612. \path[->,bend right=15] (Lfun-7) edge [above] node
  18613. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18614. \path[->,bend right=15] (F1-2) edge [right] node
  18615. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18616. \path[->,bend right=15] (F1-3) edge [below] node
  18617. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18618. \path[->,bend right=15] (F1-4) edge [below] node
  18619. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18620. \path[->,bend left=15] (F1-5) edge [above] node
  18621. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18622. \path[->,bend left=10] (F1-6) edge [below] node
  18623. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18624. \path[->,bend left=15] (C3-2) edge [right] node
  18625. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18626. \path[->,bend right=15] (x86-2) edge [right] node
  18627. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18628. \path[->,bend right=15] (x86-2-1) edge [below] node
  18629. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18630. \path[->,bend right=15] (x86-2-2) edge [right] node
  18631. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18632. \path[->,bend left=15] (x86-3) edge [above] node
  18633. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18634. \path[->,bend left=15] (x86-4) edge [right] node
  18635. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18636. \end{tikzpicture}
  18637. \fi}
  18638. {\if\edition\pythonEd\pythonColor
  18639. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18640. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18641. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18642. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18643. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18644. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18645. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18646. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18647. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18648. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18649. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18650. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18651. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18652. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18653. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18654. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18655. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18656. \path[->,bend left=15] (Lfun) edge [above] node
  18657. {\ttfamily\footnotesize shrink} (Lfun-2);
  18658. \path[->,bend left=15] (Lfun-2) edge [above] node
  18659. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18660. \path[->,bend left=15] (Lfun-3) edge [above] node
  18661. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18662. \path[->,bend left=15] (Lfun-4) edge [left] node
  18663. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18664. \path[->,bend left=15] (Lfun-5) edge [below] node
  18665. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18666. \path[->,bend right=15] (Lfun-6) edge [above] node
  18667. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18668. \path[->,bend right=15] (Lfun-7) edge [above] node
  18669. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18670. \path[->,bend right=15] (F1-2) edge [right] node
  18671. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18672. \path[->,bend right=15] (F1-3) edge [below] node
  18673. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18674. \path[->,bend left=15] (F1-5) edge [above] node
  18675. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18676. \path[->,bend left=10] (F1-6) edge [below] node
  18677. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18678. \path[->,bend right=15] (C3-2) edge [right] node
  18679. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18680. \path[->,bend right=15] (x86-2) edge [below] node
  18681. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18682. \path[->,bend right=15] (x86-3) edge [below] node
  18683. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18684. \path[->,bend left=15] (x86-4) edge [above] node
  18685. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18686. \end{tikzpicture}
  18687. \fi}
  18688. \end{tcolorbox}
  18689. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18690. \label{fig:Ldyn-passes}
  18691. \end{figure}
  18692. % Further Reading
  18693. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18694. %% {\if\edition\pythonEd\pythonColor
  18695. %% \chapter{Objects}
  18696. %% \label{ch:Lobject}
  18697. %% \index{subject}{objects}
  18698. %% \index{subject}{classes}
  18699. %% \setcounter{footnote}{0}
  18700. %% \fi}
  18701. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18702. \chapter{Gradual Typing}
  18703. \label{ch:Lgrad}
  18704. \index{subject}{gradual typing}
  18705. \setcounter{footnote}{0}
  18706. This chapter studies the language \LangGrad{}, in which the programmer
  18707. can choose between static and dynamic type checking in different parts
  18708. of a program, thereby mixing the statically typed \LangLam{} language
  18709. with the dynamically typed \LangDyn{}. There are several approaches to
  18710. mixing static and dynamic typing, including multilanguage
  18711. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18712. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18713. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18714. programmer controls the amount of static versus dynamic checking by
  18715. adding or removing type annotations on parameters and
  18716. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18717. The definition of the concrete syntax of \LangGrad{} is shown in
  18718. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18719. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18720. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18721. annotations are optional, which is specified in the grammar using the
  18722. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18723. annotations are not optional, but we use the \CANYTY{} type when a type
  18724. annotation is absent.
  18725. %
  18726. Both the type checker and the interpreter for \LangGrad{} require some
  18727. interesting changes to enable gradual typing, which we discuss in the
  18728. next two sections.
  18729. \newcommand{\LgradGrammarRacket}{
  18730. \begin{array}{lcl}
  18731. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18732. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18733. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18734. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18735. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18736. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18737. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18738. \end{array}
  18739. }
  18740. \newcommand{\LgradASTRacket}{
  18741. \begin{array}{lcl}
  18742. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18743. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18744. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18745. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18746. \itm{op} &::=& \code{procedure-arity} \\
  18747. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18748. \end{array}
  18749. }
  18750. \newcommand{\LgradGrammarPython}{
  18751. \begin{array}{lcl}
  18752. \Type &::=& \key{Any}
  18753. \MID \key{int}
  18754. \MID \key{bool}
  18755. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18756. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18757. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18758. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18759. \MID \CARITY{\Exp} \\
  18760. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18761. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18762. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18763. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18764. \end{array}
  18765. }
  18766. \newcommand{\LgradASTPython}{
  18767. \begin{array}{lcl}
  18768. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18769. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18770. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18771. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18772. &\MID& \ARITY{\Exp} \\
  18773. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18774. \MID \RETURN{\Exp} \\
  18775. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18776. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18777. \end{array}
  18778. }
  18779. \begin{figure}[tbp]
  18780. \centering
  18781. \begin{tcolorbox}[colback=white]
  18782. \vspace{-5pt}
  18783. \small
  18784. {\if\edition\racketEd
  18785. \[
  18786. \begin{array}{l}
  18787. \gray{\LintGrammarRacket{}} \\ \hline
  18788. \gray{\LvarGrammarRacket{}} \\ \hline
  18789. \gray{\LifGrammarRacket{}} \\ \hline
  18790. \gray{\LwhileGrammarRacket} \\ \hline
  18791. \gray{\LtupGrammarRacket} \\ \hline
  18792. \LgradGrammarRacket \\
  18793. \begin{array}{lcl}
  18794. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18795. \end{array}
  18796. \end{array}
  18797. \]
  18798. \fi}
  18799. {\if\edition\pythonEd\pythonColor
  18800. \[
  18801. \begin{array}{l}
  18802. \gray{\LintGrammarPython{}} \\ \hline
  18803. \gray{\LvarGrammarPython{}} \\ \hline
  18804. \gray{\LifGrammarPython{}} \\ \hline
  18805. \gray{\LwhileGrammarPython} \\ \hline
  18806. \gray{\LtupGrammarPython} \\ \hline
  18807. \LgradGrammarPython \\
  18808. \begin{array}{lcl}
  18809. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18810. \end{array}
  18811. \end{array}
  18812. \]
  18813. \fi}
  18814. \end{tcolorbox}
  18815. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18816. \label{fig:Lgrad-concrete-syntax}
  18817. \end{figure}
  18818. \begin{figure}[tbp]
  18819. \centering
  18820. \begin{tcolorbox}[colback=white]
  18821. \small
  18822. {\if\edition\racketEd
  18823. \[
  18824. \begin{array}{l}
  18825. \gray{\LintOpAST} \\ \hline
  18826. \gray{\LvarASTRacket{}} \\ \hline
  18827. \gray{\LifASTRacket{}} \\ \hline
  18828. \gray{\LwhileASTRacket{}} \\ \hline
  18829. \gray{\LtupASTRacket{}} \\ \hline
  18830. \LgradASTRacket \\
  18831. \begin{array}{lcl}
  18832. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18833. \end{array}
  18834. \end{array}
  18835. \]
  18836. \fi}
  18837. {\if\edition\pythonEd\pythonColor
  18838. \[
  18839. \begin{array}{l}
  18840. \gray{\LintASTPython{}} \\ \hline
  18841. \gray{\LvarASTPython{}} \\ \hline
  18842. \gray{\LifASTPython{}} \\ \hline
  18843. \gray{\LwhileASTPython} \\ \hline
  18844. \gray{\LtupASTPython} \\ \hline
  18845. \LgradASTPython \\
  18846. \begin{array}{lcl}
  18847. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18848. \end{array}
  18849. \end{array}
  18850. \]
  18851. \fi}
  18852. \end{tcolorbox}
  18853. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18854. \label{fig:Lgrad-syntax}
  18855. \end{figure}
  18856. % TODO: more road map -Jeremy
  18857. %\clearpage
  18858. \section{Type Checking \LangGrad{}}
  18859. \label{sec:gradual-type-check}
  18860. We begin by discussing the type checking of a partially typed variant
  18861. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18862. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18863. statically typed, so there is nothing special happening there with
  18864. respect to type checking. On the other hand, the \code{inc} function
  18865. does not have type annotations, so the type checker assigns the type
  18866. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18867. \code{+} operator inside \code{inc}. It expects both arguments to have
  18868. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18869. a gradually typed language, such differences are allowed so long as
  18870. the types are \emph{consistent}; that is, they are equal except in
  18871. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18872. is consistent with every other type. Figure~\ref{fig:consistent}
  18873. shows the definition of the
  18874. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18875. %
  18876. So the type checker allows the \code{+} operator to be applied
  18877. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18878. %
  18879. Next consider the call to the \code{map} function shown in
  18880. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18881. tuple. The \code{inc} function has type
  18882. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18883. but parameter \code{f} of \code{map} has type
  18884. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18885. The type checker for \LangGrad{} accepts this call because the two types are
  18886. consistent.
  18887. \begin{figure}[hbtp]
  18888. % gradual_test_9.rkt
  18889. \begin{tcolorbox}[colback=white]
  18890. {\if\edition\racketEd
  18891. \begin{lstlisting}
  18892. (define (map [f : (Integer -> Integer)]
  18893. [v : (Vector Integer Integer)])
  18894. : (Vector Integer Integer)
  18895. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18896. (define (inc x) (+ x 1))
  18897. (vector-ref (map inc (vector 0 41)) 1)
  18898. \end{lstlisting}
  18899. \fi}
  18900. {\if\edition\pythonEd\pythonColor
  18901. \begin{lstlisting}
  18902. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18903. return f(v[0]), f(v[1])
  18904. def inc(x):
  18905. return x + 1
  18906. t = map(inc, (0, 41))
  18907. print(t[1])
  18908. \end{lstlisting}
  18909. \fi}
  18910. \end{tcolorbox}
  18911. \caption{A partially typed version of the \code{map} example.}
  18912. \label{fig:gradual-map}
  18913. \end{figure}
  18914. \begin{figure}[tbp]
  18915. \begin{tcolorbox}[colback=white]
  18916. {\if\edition\racketEd
  18917. \begin{lstlisting}
  18918. (define/public (consistent? t1 t2)
  18919. (match* (t1 t2)
  18920. [('Integer 'Integer) #t]
  18921. [('Boolean 'Boolean) #t]
  18922. [('Void 'Void) #t]
  18923. [('Any t2) #t]
  18924. [(t1 'Any) #t]
  18925. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18926. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18927. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18928. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18929. (consistent? rt1 rt2))]
  18930. [(other wise) #f]))
  18931. \end{lstlisting}
  18932. \fi}
  18933. {\if\edition\pythonEd\pythonColor
  18934. \begin{lstlisting}
  18935. def consistent(self, t1, t2):
  18936. match (t1, t2):
  18937. case (AnyType(), _):
  18938. return True
  18939. case (_, AnyType()):
  18940. return True
  18941. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18942. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18943. case (TupleType(ts1), TupleType(ts2)):
  18944. return all(map(self.consistent, ts1, ts2))
  18945. case (_, _):
  18946. return t1 == t2
  18947. \end{lstlisting}
  18948. \fi}
  18949. \vspace{-5pt}
  18950. \end{tcolorbox}
  18951. \caption{The consistency method on types.}
  18952. \label{fig:consistent}
  18953. \end{figure}
  18954. It is also helpful to consider how gradual typing handles programs with an
  18955. error, such as applying \code{map} to a function that sometimes
  18956. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18957. type checker for \LangGrad{} accepts this program because the type of
  18958. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18959. \code{map}; that is,
  18960. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18961. is consistent with
  18962. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18963. One might say that a gradual type checker is optimistic in that it
  18964. accepts programs that might execute without a runtime type error.
  18965. %
  18966. The definition of the type checker for \LangGrad{} is shown in
  18967. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18968. and \ref{fig:type-check-Lgradual-3}.
  18969. %% \begin{figure}[tp]
  18970. %% \centering
  18971. %% \fbox{
  18972. %% \begin{minipage}{0.96\textwidth}
  18973. %% \small
  18974. %% \[
  18975. %% \begin{array}{lcl}
  18976. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18977. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18978. %% \end{array}
  18979. %% \]
  18980. %% \end{minipage}
  18981. %% }
  18982. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18983. %% \label{fig:Lgrad-prime-syntax}
  18984. %% \end{figure}
  18985. \begin{figure}[tbp]
  18986. \begin{tcolorbox}[colback=white]
  18987. {\if\edition\racketEd
  18988. \begin{lstlisting}
  18989. (define (map [f : (Integer -> Integer)]
  18990. [v : (Vector Integer Integer)])
  18991. : (Vector Integer Integer)
  18992. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18993. (define (inc x) (+ x 1))
  18994. (define (true) #t)
  18995. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18996. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18997. \end{lstlisting}
  18998. \fi}
  18999. {\if\edition\pythonEd\pythonColor
  19000. \begin{lstlisting}
  19001. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19002. return f(v[0]), f(v[1])
  19003. def inc(x):
  19004. return x + 1
  19005. def true():
  19006. return True
  19007. def maybe_inc(x):
  19008. return inc(x) if input_int() == 0 else true()
  19009. t = map(maybe_inc, (0, 41))
  19010. print(t[1])
  19011. \end{lstlisting}
  19012. \fi}
  19013. \vspace{-5pt}
  19014. \end{tcolorbox}
  19015. \caption{A variant of the \code{map} example with an error.}
  19016. \label{fig:map-maybe_inc}
  19017. \end{figure}
  19018. Running this program with input \code{1} triggers an
  19019. error when the \code{maybe\_inc} function returns
  19020. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19021. performs checking at runtime to ensure the integrity of the static
  19022. types, such as the
  19023. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19024. annotation on
  19025. parameter \code{f} of \code{map}.
  19026. Here we give a preview of how the runtime checking is accomplished;
  19027. the following sections provide the details.
  19028. The runtime checking is carried out by a new \code{Cast} AST node that
  19029. is generated in a new pass named \code{cast\_insert}. The output of
  19030. \code{cast\_insert} is a program in the \LangCast{} language, which
  19031. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19032. %
  19033. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19034. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19035. inserted every time the type checker encounters two types that are
  19036. consistent but not equal. In the \code{inc} function, \code{x} is
  19037. cast to \INTTY{} and the result of the \code{+} is cast to
  19038. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19039. is cast from
  19040. \racket{\code{(Any -> Any)}}
  19041. \python{\code{Callable[[Any], Any]}}
  19042. to
  19043. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19044. %
  19045. In the next section we see how to interpret the \code{Cast} node.
  19046. \begin{figure}[btp]
  19047. \begin{tcolorbox}[colback=white]
  19048. {\if\edition\racketEd
  19049. \begin{lstlisting}
  19050. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19051. : (Vector Integer Integer)
  19052. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19053. (define (inc [x : Any]) : Any
  19054. (cast (+ (cast x Any Integer) 1) Integer Any))
  19055. (define (true) : Any (cast #t Boolean Any))
  19056. (define (maybe_inc [x : Any]) : Any
  19057. (if (eq? 0 (read)) (inc x) (true)))
  19058. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19059. (vector 0 41)) 0)
  19060. \end{lstlisting}
  19061. \fi}
  19062. {\if\edition\pythonEd\pythonColor
  19063. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19064. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19065. return f(v[0]), f(v[1])
  19066. def inc(x : Any) -> Any:
  19067. return Cast(Cast(x, Any, int) + 1, int, Any)
  19068. def true() -> Any:
  19069. return Cast(True, bool, Any)
  19070. def maybe_inc(x : Any) -> Any:
  19071. return inc(x) if input_int() == 0 else true()
  19072. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19073. (0, 41))
  19074. print(t[1])
  19075. \end{lstlisting}
  19076. \fi}
  19077. \vspace{-5pt}
  19078. \end{tcolorbox}
  19079. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19080. and \code{maybe\_inc} example.}
  19081. \label{fig:map-cast}
  19082. \end{figure}
  19083. {\if\edition\pythonEd\pythonColor
  19084. \begin{figure}[tbp]
  19085. \begin{tcolorbox}[colback=white]
  19086. \begin{lstlisting}
  19087. class TypeCheckLgrad(TypeCheckLlambda):
  19088. def type_check_exp(self, e, env) -> Type:
  19089. match e:
  19090. case Name(id):
  19091. return env[id]
  19092. case Constant(value) if isinstance(value, bool):
  19093. return BoolType()
  19094. case Constant(value) if isinstance(value, int):
  19095. return IntType()
  19096. case Call(Name('input_int'), []):
  19097. return IntType()
  19098. case BinOp(left, op, right):
  19099. left_type = self.type_check_exp(left, env)
  19100. self.check_consistent(left_type, IntType(), left)
  19101. right_type = self.type_check_exp(right, env)
  19102. self.check_consistent(right_type, IntType(), right)
  19103. return IntType()
  19104. case IfExp(test, body, orelse):
  19105. test_t = self.type_check_exp(test, env)
  19106. self.check_consistent(test_t, BoolType(), test)
  19107. body_t = self.type_check_exp(body, env)
  19108. orelse_t = self.type_check_exp(orelse, env)
  19109. self.check_consistent(body_t, orelse_t, e)
  19110. return self.join_types(body_t, orelse_t)
  19111. case Call(func, args):
  19112. func_t = self.type_check_exp(func, env)
  19113. args_t = [self.type_check_exp(arg, env) for arg in args]
  19114. match func_t:
  19115. case FunctionType(params_t, return_t) \
  19116. if len(params_t) == len(args_t):
  19117. for (arg_t, param_t) in zip(args_t, params_t):
  19118. self.check_consistent(param_t, arg_t, e)
  19119. return return_t
  19120. case AnyType():
  19121. return AnyType()
  19122. case _:
  19123. raise Exception('type_check_exp: in call, unexpected '
  19124. + repr(func_t))
  19125. ...
  19126. case _:
  19127. raise Exception('type_check_exp: unexpected ' + repr(e))
  19128. \end{lstlisting}
  19129. \end{tcolorbox}
  19130. \caption{Type checking expressions in the \LangGrad{} language.}
  19131. \label{fig:type-check-Lgradual-1}
  19132. \end{figure}
  19133. \begin{figure}[tbp]
  19134. \begin{tcolorbox}[colback=white]
  19135. \begin{lstlisting}
  19136. def check_exp(self, e, expected_ty, env):
  19137. match e:
  19138. case Lambda(params, body):
  19139. match expected_ty:
  19140. case FunctionType(params_t, return_t):
  19141. new_env = env.copy().update(zip(params, params_t))
  19142. e.has_type = expected_ty
  19143. body_ty = self.type_check_exp(body, new_env)
  19144. self.check_consistent(body_ty, return_t)
  19145. case AnyType():
  19146. new_env = env.copy().update((p, AnyType()) for p in params)
  19147. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19148. body_ty = self.type_check_exp(body, new_env)
  19149. case _:
  19150. raise Exception('lambda is not of type ' + str(expected_ty))
  19151. case _:
  19152. e_ty = self.type_check_exp(e, env)
  19153. self.check_consistent(e_ty, expected_ty, e)
  19154. \end{lstlisting}
  19155. \end{tcolorbox}
  19156. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19157. \label{fig:type-check-Lgradual-2}
  19158. \end{figure}
  19159. \begin{figure}[tbp]
  19160. \begin{tcolorbox}[colback=white]
  19161. \begin{lstlisting}
  19162. def type_check_stmt(self, s, env, return_type):
  19163. match s:
  19164. case Assign([Name(id)], value):
  19165. value_ty = self.type_check_exp(value, env)
  19166. if id in env:
  19167. self.check_consistent(env[id], value_ty, value)
  19168. else:
  19169. env[id] = value_ty
  19170. ...
  19171. case _:
  19172. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19173. def type_check_stmts(self, ss, env, return_type):
  19174. for s in ss:
  19175. self.type_check_stmt(s, env, return_type)
  19176. \end{lstlisting}
  19177. \end{tcolorbox}
  19178. \caption{Type checking statements in the \LangGrad{} language.}
  19179. \label{fig:type-check-Lgradual-3}
  19180. \end{figure}
  19181. \clearpage
  19182. \begin{figure}[tbp]
  19183. \begin{tcolorbox}[colback=white]
  19184. \begin{lstlisting}
  19185. def join_types(self, t1, t2):
  19186. match (t1, t2):
  19187. case (AnyType(), _):
  19188. return t2
  19189. case (_, AnyType()):
  19190. return t1
  19191. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19192. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19193. self.join_types(rt1,rt2))
  19194. case (TupleType(ts1), TupleType(ts2)):
  19195. return TupleType(list(map(self.join_types, ts1, ts2)))
  19196. case (_, _):
  19197. return t1
  19198. def check_consistent(self, t1, t2, e):
  19199. if not self.consistent(t1, t2):
  19200. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19201. + repr(t2) + ' in ' + repr(e))
  19202. \end{lstlisting}
  19203. \end{tcolorbox}
  19204. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19205. \label{fig:type-check-Lgradual-aux}
  19206. \end{figure}
  19207. \fi}
  19208. {\if\edition\racketEd
  19209. \begin{figure}[tbp]
  19210. \begin{tcolorbox}[colback=white]
  19211. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19212. (define/override (type-check-exp env)
  19213. (lambda (e)
  19214. (define recur (type-check-exp env))
  19215. (match e
  19216. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19217. (define-values (new-es ts)
  19218. (for/lists (exprs types) ([e es])
  19219. (recur e)))
  19220. (define t-ret (type-check-op op ts e))
  19221. (values (Prim op new-es) t-ret)]
  19222. [(Prim 'eq? (list e1 e2))
  19223. (define-values (e1^ t1) (recur e1))
  19224. (define-values (e2^ t2) (recur e2))
  19225. (check-consistent? t1 t2 e)
  19226. (define T (meet t1 t2))
  19227. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19228. [(Prim 'and (list e1 e2))
  19229. (recur (If e1 e2 (Bool #f)))]
  19230. [(Prim 'or (list e1 e2))
  19231. (define tmp (gensym 'tmp))
  19232. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19233. [(If 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? T1 'Boolean e)
  19238. (check-consistent? T2 T3 e)
  19239. (define Tif (meet T2 T3))
  19240. (values (If e1^ e2^ e3^) Tif)]
  19241. [(SetBang x e1)
  19242. (define-values (e1^ T1) (recur e1))
  19243. (define varT (dict-ref env x))
  19244. (check-consistent? T1 varT e)
  19245. (values (SetBang x e1^) 'Void)]
  19246. [(WhileLoop e1 e2)
  19247. (define-values (e1^ T1) (recur e1))
  19248. (check-consistent? T1 'Boolean e)
  19249. (define-values (e2^ T2) ((type-check-exp env) e2))
  19250. (values (WhileLoop e1^ e2^) 'Void)]
  19251. [(Prim 'vector-length (list e1))
  19252. (define-values (e1^ t) (recur e1))
  19253. (match t
  19254. [`(Vector ,ts ...)
  19255. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19256. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19257. \end{lstlisting}
  19258. \end{tcolorbox}
  19259. \caption{Type checker for the \LangGrad{} language, part 1.}
  19260. \label{fig:type-check-Lgradual-1}
  19261. \end{figure}
  19262. \begin{figure}[tbp]
  19263. \begin{tcolorbox}[colback=white]
  19264. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19265. [(Prim 'vector-ref (list e1 e2))
  19266. (define-values (e1^ t1) (recur e1))
  19267. (define-values (e2^ t2) (recur e2))
  19268. (check-consistent? t2 'Integer e)
  19269. (match t1
  19270. [`(Vector ,ts ...)
  19271. (match e2^
  19272. [(Int i)
  19273. (unless (and (0 . <= . i) (i . < . (length ts)))
  19274. (error 'type-check "invalid index ~a in ~a" i e))
  19275. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19276. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19277. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19278. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19279. [(Prim 'vector-set! (list e1 e2 e3) )
  19280. (define-values (e1^ t1) (recur e1))
  19281. (define-values (e2^ t2) (recur e2))
  19282. (define-values (e3^ t3) (recur e3))
  19283. (check-consistent? t2 'Integer e)
  19284. (match t1
  19285. [`(Vector ,ts ...)
  19286. (match e2^
  19287. [(Int i)
  19288. (unless (and (0 . <= . i) (i . < . (length ts)))
  19289. (error 'type-check "invalid index ~a in ~a" i e))
  19290. (check-consistent? (list-ref ts i) t3 e)
  19291. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19292. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19293. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19294. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19295. [(Apply e1 e2s)
  19296. (define-values (e1^ T1) (recur e1))
  19297. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19298. (match T1
  19299. [`(,T1ps ... -> ,T1rt)
  19300. (for ([T2 T2s] [Tp T1ps])
  19301. (check-consistent? T2 Tp e))
  19302. (values (Apply e1^ e2s^) T1rt)]
  19303. [`Any (values (Apply e1^ e2s^) 'Any)]
  19304. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19305. [(Lambda params Tr e1)
  19306. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19307. (match p
  19308. [`[,x : ,T] (values x T)]
  19309. [(? symbol? x) (values x 'Any)])))
  19310. (define-values (e1^ T1)
  19311. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19312. (check-consistent? Tr T1 e)
  19313. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19314. `(,@Ts -> ,Tr))]
  19315. [else ((super type-check-exp env) e)]
  19316. )))
  19317. \end{lstlisting}
  19318. \end{tcolorbox}
  19319. \caption{Type checker for the \LangGrad{} language, part 2.}
  19320. \label{fig:type-check-Lgradual-2}
  19321. \end{figure}
  19322. \begin{figure}[tbp]
  19323. \begin{tcolorbox}[colback=white]
  19324. \begin{lstlisting}
  19325. (define/override (type-check-def env)
  19326. (lambda (e)
  19327. (match e
  19328. [(Def f params rt info body)
  19329. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19330. (match p
  19331. [`[,x : ,T] (values x T)]
  19332. [(? symbol? x) (values x 'Any)])))
  19333. (define new-env (append (map cons xs ps) env))
  19334. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19335. (check-consistent? ty^ rt e)
  19336. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19337. [else (error 'type-check "ill-formed function definition ~a" e)]
  19338. )))
  19339. (define/override (type-check-program e)
  19340. (match e
  19341. [(Program info body)
  19342. (define-values (body^ ty) ((type-check-exp '()) body))
  19343. (check-consistent? ty 'Integer e)
  19344. (ProgramDefsExp info '() body^)]
  19345. [(ProgramDefsExp info ds body)
  19346. (define new-env (for/list ([d ds])
  19347. (cons (Def-name d) (fun-def-type d))))
  19348. (define ds^ (for/list ([d ds])
  19349. ((type-check-def new-env) d)))
  19350. (define-values (body^ ty) ((type-check-exp new-env) body))
  19351. (check-consistent? ty 'Integer e)
  19352. (ProgramDefsExp info ds^ body^)]
  19353. [else (super type-check-program e)]))
  19354. \end{lstlisting}
  19355. \end{tcolorbox}
  19356. \caption{Type checker for the \LangGrad{} language, part 3.}
  19357. \label{fig:type-check-Lgradual-3}
  19358. \end{figure}
  19359. \begin{figure}[tbp]
  19360. \begin{tcolorbox}[colback=white]
  19361. \begin{lstlisting}
  19362. (define/public (join t1 t2)
  19363. (match* (t1 t2)
  19364. [('Integer 'Integer) 'Integer]
  19365. [('Boolean 'Boolean) 'Boolean]
  19366. [('Void 'Void) 'Void]
  19367. [('Any t2) t2]
  19368. [(t1 'Any) t1]
  19369. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19370. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19371. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19372. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19373. -> ,(join rt1 rt2))]))
  19374. (define/public (meet t1 t2)
  19375. (match* (t1 t2)
  19376. [('Integer 'Integer) 'Integer]
  19377. [('Boolean 'Boolean) 'Boolean]
  19378. [('Void 'Void) 'Void]
  19379. [('Any t2) 'Any]
  19380. [(t1 'Any) 'Any]
  19381. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19382. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19383. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19384. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19385. -> ,(meet rt1 rt2))]))
  19386. (define/public (check-consistent? t1 t2 e)
  19387. (unless (consistent? t1 t2)
  19388. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19389. (define explicit-prim-ops
  19390. (set-union
  19391. (type-predicates)
  19392. (set 'procedure-arity 'eq? 'not 'and 'or
  19393. 'vector 'vector-length 'vector-ref 'vector-set!
  19394. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19395. (define/override (fun-def-type d)
  19396. (match d
  19397. [(Def f params rt info body)
  19398. (define ps
  19399. (for/list ([p params])
  19400. (match p
  19401. [`[,x : ,T] T]
  19402. [(? symbol?) 'Any]
  19403. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19404. `(,@ps -> ,rt)]
  19405. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19406. \end{lstlisting}
  19407. \end{tcolorbox}
  19408. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19409. \label{fig:type-check-Lgradual-aux}
  19410. \end{figure}
  19411. \fi}
  19412. \section{Interpreting \LangCast{} }
  19413. \label{sec:interp-casts}
  19414. The runtime behavior of casts involving simple types such as
  19415. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19416. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19417. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19418. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19419. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19420. operator, by checking the value's tag and either retrieving
  19421. the underlying integer or signaling an error if the tag is not the
  19422. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19423. %
  19424. Things get more interesting with casts involving
  19425. \racket{function and tuple types}\python{function, tuple, and array types}.
  19426. Consider the cast of the function \code{maybe\_inc} from
  19427. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19428. to
  19429. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19430. shown in figure~\ref{fig:map-maybe_inc}.
  19431. When the \code{maybe\_inc} function flows through
  19432. this cast at runtime, we don't know whether it will return
  19433. an integer, because that depends on the input from the user.
  19434. The \LangCast{} interpreter therefore delays the checking
  19435. of the cast until the function is applied. To do so it
  19436. wraps \code{maybe\_inc} in a new function that casts its parameter
  19437. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19438. casts the return value from \CANYTY{} to \INTTY{}.
  19439. {\if\edition\pythonEd\pythonColor
  19440. %
  19441. There are further complications regarding casts on mutable data,
  19442. such as the \code{list} type introduced in
  19443. the challenge assignment of section~\ref{sec:arrays}.
  19444. %
  19445. \fi}
  19446. %
  19447. Consider the example presented in figure~\ref{fig:map-bang} that
  19448. defines a partially typed version of \code{map} whose parameter
  19449. \code{v} has type
  19450. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19451. and that updates \code{v} in place
  19452. instead of returning a new tuple. We name this function
  19453. \code{map\_inplace}. We apply \code{map\_inplace} to
  19454. \racket{a tuple}\python{an array} of integers, so the type checker
  19455. inserts a cast from
  19456. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19457. to
  19458. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19459. A naive way for the \LangCast{} interpreter to cast between
  19460. \racket{tuple}\python{array} types would be to build a new
  19461. \racket{tuple}\python{array} whose elements are the result
  19462. of casting each of the original elements to the target
  19463. type. However, this approach is not valid for mutable data structures.
  19464. In the example of figure~\ref{fig:map-bang},
  19465. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19466. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19467. the original one.
  19468. Instead the interpreter needs to create a new kind of value, a
  19469. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19470. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19471. and then applies a
  19472. cast to the resulting value. On a write, the proxy casts the argument
  19473. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19474. \racket{
  19475. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19476. \code{0} from \INTTY{} to \CANYTY{}.
  19477. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19478. from \CANYTY{} to \INTTY{}.
  19479. }
  19480. \python{
  19481. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19482. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19483. For the subscript on the left of the assignment,
  19484. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19485. }
  19486. Finally we consider casts between the \CANYTY{} type and higher-order types
  19487. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19488. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19489. have a type annotation, so it is given type \CANYTY{}. In the call to
  19490. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19491. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19492. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19493. \code{Inject}, but that doesn't work because
  19494. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19495. a flat type. Instead, we must first cast to
  19496. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19497. and then inject to \CANYTY{}.
  19498. \begin{figure}[tbp]
  19499. \begin{tcolorbox}[colback=white]
  19500. % gradual_test_11.rkt
  19501. {\if\edition\racketEd
  19502. \begin{lstlisting}
  19503. (define (map_inplace [f : (Any -> Any)]
  19504. [v : (Vector Any Any)]) : Void
  19505. (begin
  19506. (vector-set! v 0 (f (vector-ref v 0)))
  19507. (vector-set! v 1 (f (vector-ref v 1)))))
  19508. (define (inc x) (+ x 1))
  19509. (let ([v (vector 0 41)])
  19510. (begin (map_inplace inc v) (vector-ref v 1)))
  19511. \end{lstlisting}
  19512. \fi}
  19513. {\if\edition\pythonEd\pythonColor
  19514. \begin{lstlisting}
  19515. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19516. i = 0
  19517. while i != len(v):
  19518. v[i] = f(v[i])
  19519. i = i + 1
  19520. def inc(x : int) -> int:
  19521. return x + 1
  19522. v = [0, 41]
  19523. map_inplace(inc, v)
  19524. print(v[1])
  19525. \end{lstlisting}
  19526. \fi}
  19527. \end{tcolorbox}
  19528. \caption{An example involving casts on arrays.}
  19529. \label{fig:map-bang}
  19530. \end{figure}
  19531. \begin{figure}[btp]
  19532. \begin{tcolorbox}[colback=white]
  19533. {\if\edition\racketEd
  19534. \begin{lstlisting}
  19535. (define (map_inplace [f : (Any -> Any)] v) : Void
  19536. (begin
  19537. (vector-set! v 0 (f (vector-ref v 0)))
  19538. (vector-set! v 1 (f (vector-ref v 1)))))
  19539. (define (inc x) (+ x 1))
  19540. (let ([v (vector 0 41)])
  19541. (begin (map_inplace inc v) (vector-ref v 1)))
  19542. \end{lstlisting}
  19543. \fi}
  19544. {\if\edition\pythonEd\pythonColor
  19545. \begin{lstlisting}
  19546. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19547. i = 0
  19548. while i != len(v):
  19549. v[i] = f(v[i])
  19550. i = i + 1
  19551. def inc(x):
  19552. return x + 1
  19553. v = [0, 41]
  19554. map_inplace(inc, v)
  19555. print(v[1])
  19556. \end{lstlisting}
  19557. \fi}
  19558. \end{tcolorbox}
  19559. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19560. \label{fig:map-any}
  19561. \end{figure}
  19562. \begin{figure}[tbp]
  19563. \begin{tcolorbox}[colback=white]
  19564. {\if\edition\racketEd
  19565. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19566. (define/public (apply_cast v s t)
  19567. (match* (s t)
  19568. [(t1 t2) #:when (equal? t1 t2) v]
  19569. [('Any t2)
  19570. (match t2
  19571. [`(,ts ... -> ,rt)
  19572. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19573. (define v^ (apply-project v any->any))
  19574. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19575. [`(Vector ,ts ...)
  19576. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19577. (define v^ (apply-project v vec-any))
  19578. (apply_cast v^ vec-any `(Vector ,@ts))]
  19579. [else (apply-project v t2)])]
  19580. [(t1 'Any)
  19581. (match t1
  19582. [`(,ts ... -> ,rt)
  19583. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19584. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19585. (apply-inject v^ (any-tag any->any))]
  19586. [`(Vector ,ts ...)
  19587. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19588. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19589. (apply-inject v^ (any-tag vec-any))]
  19590. [else (apply-inject v (any-tag t1))])]
  19591. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19592. (define x (gensym 'x))
  19593. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19594. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19595. (define cast-writes
  19596. (for/list ([t1 ts1] [t2 ts2])
  19597. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19598. `(vector-proxy ,(vector v (apply vector cast-reads)
  19599. (apply vector cast-writes)))]
  19600. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19601. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19602. `(function ,xs ,(Cast
  19603. (Apply (Value v)
  19604. (for/list ([x xs][t1 ts1][t2 ts2])
  19605. (Cast (Var x) t2 t1)))
  19606. rt1 rt2) ())]
  19607. ))
  19608. \end{lstlisting}
  19609. \fi}
  19610. {\if\edition\pythonEd\pythonColor
  19611. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19612. def apply_cast(self, value, src, tgt):
  19613. match (src, tgt):
  19614. case (AnyType(), FunctionType(ps2, rt2)):
  19615. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19616. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19617. case (AnyType(), TupleType(ts2)):
  19618. anytup = TupleType([AnyType() for t1 in ts2])
  19619. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19620. case (AnyType(), ListType(t2)):
  19621. anylist = ListType([AnyType() for t1 in ts2])
  19622. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19623. case (AnyType(), AnyType()):
  19624. return value
  19625. case (AnyType(), _):
  19626. return self.apply_project(value, tgt)
  19627. case (FunctionType(ps1,rt1), AnyType()):
  19628. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19629. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19630. case (TupleType(ts1), AnyType()):
  19631. anytup = TupleType([AnyType() for t1 in ts1])
  19632. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19633. case (ListType(t1), AnyType()):
  19634. anylist = ListType(AnyType())
  19635. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19636. case (_, AnyType()):
  19637. return self.apply_inject(value, src)
  19638. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19639. params = [generate_name('x') for p in ps2]
  19640. args = [Cast(Name(x), t2, t1)
  19641. for (x,t1,t2) in zip(params, ps1, ps2)]
  19642. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19643. return Function('cast', params, [Return(body)], {})
  19644. case (TupleType(ts1), TupleType(ts2)):
  19645. x = generate_name('x')
  19646. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19647. for (t1,t2) in zip(ts1,ts2)]
  19648. return ProxiedTuple(value, reads)
  19649. case (ListType(t1), ListType(t2)):
  19650. x = generate_name('x')
  19651. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19652. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19653. return ProxiedList(value, read, write)
  19654. case (t1, t2) if t1 == t2:
  19655. return value
  19656. case (t1, t2):
  19657. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19658. def apply_inject(self, value, src):
  19659. return Tagged(value, self.type_to_tag(src))
  19660. def apply_project(self, value, tgt):
  19661. match value:
  19662. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19663. return val
  19664. case _:
  19665. raise Exception('apply_project, unexpected ' + repr(value))
  19666. \end{lstlisting}
  19667. \fi}
  19668. \end{tcolorbox}
  19669. \caption{The \code{apply\_cast} auxiliary method.}
  19670. \label{fig:apply_cast}
  19671. \end{figure}
  19672. The \LangCast{} interpreter uses an auxiliary function named
  19673. \code{apply\_cast} to cast a value from a source type to a target type,
  19674. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19675. the kinds of casts that we've discussed in this section.
  19676. %
  19677. The definition of the interpreter for \LangCast{} is shown in
  19678. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19679. dispatching to \code{apply\_cast}.
  19680. \racket{To handle the addition of tuple
  19681. proxies, we update the tuple primitives in \code{interp-op} using the
  19682. functions given in figure~\ref{fig:guarded-tuple}.}
  19683. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19684. \begin{figure}[tbp]
  19685. \begin{tcolorbox}[colback=white]
  19686. {\if\edition\racketEd
  19687. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19688. (define interp-Lcast-class
  19689. (class interp-Llambda-class
  19690. (super-new)
  19691. (inherit apply-fun apply-inject apply-project)
  19692. (define/override (interp-op op)
  19693. (match op
  19694. ['vector-length guarded-vector-length]
  19695. ['vector-ref guarded-vector-ref]
  19696. ['vector-set! guarded-vector-set!]
  19697. ['any-vector-ref (lambda (v i)
  19698. (match v [`(tagged ,v^ ,tg)
  19699. (guarded-vector-ref v^ i)]))]
  19700. ['any-vector-set! (lambda (v i a)
  19701. (match v [`(tagged ,v^ ,tg)
  19702. (guarded-vector-set! v^ i a)]))]
  19703. ['any-vector-length (lambda (v)
  19704. (match v [`(tagged ,v^ ,tg)
  19705. (guarded-vector-length v^)]))]
  19706. [else (super interp-op op)]
  19707. ))
  19708. (define/override ((interp-exp env) e)
  19709. (define (recur e) ((interp-exp env) e))
  19710. (match e
  19711. [(Value v) v]
  19712. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19713. [else ((super interp-exp env) e)]))
  19714. ))
  19715. (define (interp-Lcast p)
  19716. (send (new interp-Lcast-class) interp-program p))
  19717. \end{lstlisting}
  19718. \fi}
  19719. {\if\edition\pythonEd\pythonColor
  19720. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19721. class InterpLcast(InterpLany):
  19722. def interp_exp(self, e, env):
  19723. match e:
  19724. case Cast(value, src, tgt):
  19725. v = self.interp_exp(value, env)
  19726. return self.apply_cast(v, src, tgt)
  19727. case ValueExp(value):
  19728. return value
  19729. ...
  19730. case _:
  19731. return super().interp_exp(e, env)
  19732. \end{lstlisting}
  19733. \fi}
  19734. \end{tcolorbox}
  19735. \caption{The interpreter for \LangCast{}.}
  19736. \label{fig:interp-Lcast}
  19737. \end{figure}
  19738. {\if\edition\racketEd
  19739. \begin{figure}[tbp]
  19740. \begin{tcolorbox}[colback=white]
  19741. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19742. (define (guarded-vector-ref vec i)
  19743. (match vec
  19744. [`(vector-proxy ,proxy)
  19745. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19746. (define rd (vector-ref (vector-ref proxy 1) i))
  19747. (apply-fun rd (list val) 'guarded-vector-ref)]
  19748. [else (vector-ref vec i)]))
  19749. (define (guarded-vector-set! vec i arg)
  19750. (match vec
  19751. [`(vector-proxy ,proxy)
  19752. (define wr (vector-ref (vector-ref proxy 2) i))
  19753. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19754. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19755. [else (vector-set! vec i arg)]))
  19756. (define (guarded-vector-length vec)
  19757. (match vec
  19758. [`(vector-proxy ,proxy)
  19759. (guarded-vector-length (vector-ref proxy 0))]
  19760. [else (vector-length vec)]))
  19761. \end{lstlisting}
  19762. %% {\if\edition\pythonEd\pythonColor
  19763. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19764. %% UNDER CONSTRUCTION
  19765. %% \end{lstlisting}
  19766. %% \fi}
  19767. \end{tcolorbox}
  19768. \caption{The \code{guarded-vector} auxiliary functions.}
  19769. \label{fig:guarded-tuple}
  19770. \end{figure}
  19771. \fi}
  19772. {\if\edition\pythonEd\pythonColor
  19773. \section{Overload Resolution }
  19774. \label{sec:gradual-resolution}
  19775. Recall that when we added support for arrays in
  19776. section~\ref{sec:arrays}, the syntax for the array operations were the
  19777. same as for tuple operations (for example, accessing an element and
  19778. getting the length). So we performed overload resolution, with a pass
  19779. named \code{resolve}, to separate the array and tuple operations. In
  19780. particular, we introduced the primitives \code{array\_load},
  19781. \code{array\_store}, and \code{array\_len}.
  19782. For gradual typing, we further overload these operators to work on
  19783. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19784. updated with new cases for the \CANYTY{} type, translating the element
  19785. access and length operations to the primitives \code{any\_load},
  19786. \code{any\_store}, and \code{any\_len}.
  19787. \fi}
  19788. \section{Cast Insertion }
  19789. \label{sec:gradual-insert-casts}
  19790. In our discussion of type checking of \LangGrad{}, we mentioned how
  19791. the runtime aspect of type checking is carried out by the \code{Cast}
  19792. AST node, which is added to the program by a new pass named
  19793. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19794. language. We now discuss the details of this pass.
  19795. The \code{cast\_insert} pass is closely related to the type checker
  19796. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19797. In particular, the type checker allows implicit casts between
  19798. consistent types. The job of the \code{cast\_insert} pass is to make
  19799. those casts explicit. It does so by inserting
  19800. \code{Cast} nodes into the AST.
  19801. %
  19802. For the most part, the implicit casts occur in places where the type
  19803. checker checks two types for consistency. Consider the case for
  19804. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19805. checker requires that the type of the left operand is consistent with
  19806. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19807. \code{Cast} around the left operand, converting from its type to
  19808. \INTTY{}. The story is similar for the right operand. It is not always
  19809. necessary to insert a cast, for example, if the left operand already has type
  19810. \INTTY{} then there is no need for a \code{Cast}.
  19811. Some of the implicit casts are not as straightforward. One such case
  19812. arises with the
  19813. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19814. see that the type checker requires that the two branches have
  19815. consistent types and that type of the conditional expression is the
  19816. meet of the branches' types. In the target language \LangCast{}, both
  19817. branches will need to have the same type, and that type
  19818. will be the type of the conditional expression. Thus, each branch requires
  19819. a \code{Cast} to convert from its type to the meet of the branches' types.
  19820. The case for the function call exhibits another interesting situation. If
  19821. the function expression is of type \CANYTY{}, then it needs to be cast
  19822. to a function type so that it can be used in a function call in
  19823. \LangCast{}. Which function type should it be cast to? The parameter
  19824. and return types are unknown, so we can simply use \CANYTY{} for all
  19825. of them. Furthermore, in \LangCast{} the argument types will need to
  19826. exactly match the parameter types, so we must cast all the arguments
  19827. to type \CANYTY{} (if they are not already of that type).
  19828. {\if\edition\racketEd
  19829. %
  19830. Likewise, the cases for the tuple operators \code{vector-length},
  19831. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19832. where the tuple expression is of type \CANYTY{}. Instead of
  19833. handling these situations with casts, we recommend translating
  19834. the special-purpose variants of the tuple operators that handle
  19835. tuples of type \CANYTY{}: \code{any-vector-length},
  19836. \code{any-vector-ref}, and \code{any-vector-set!}.
  19837. %
  19838. \fi}
  19839. \section{Lower Casts }
  19840. \label{sec:lower_casts}
  19841. The next step in the journey toward x86 is the \code{lower\_casts}
  19842. pass that translates the casts in \LangCast{} to the lower-level
  19843. \code{Inject} and \code{Project} operators and new operators for
  19844. proxies, extending the \LangLam{} language to \LangProxy{}.
  19845. The \LangProxy{} language can also be described as an extension of
  19846. \LangAny{}, with the addition of proxies. We recommend creating an
  19847. auxiliary function named \code{lower\_cast} that takes an expression
  19848. (in \LangCast{}), a source type, and a target type and translates it
  19849. to an expression in \LangProxy{}.
  19850. The \code{lower\_cast} function can follow a code structure similar to
  19851. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19852. the interpreter for \LangCast{}, because it must handle the same cases
  19853. as \code{apply\_cast} and it needs to mimic the behavior of
  19854. \code{apply\_cast}. The most interesting cases concern
  19855. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19856. {\if\edition\racketEd
  19857. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19858. type to another tuple type is accomplished by creating a proxy that
  19859. intercepts the operations on the underlying tuple. Here we make the
  19860. creation of the proxy explicit with the \code{vector-proxy} AST
  19861. node. It takes three arguments: the first is an expression for the
  19862. tuple, the second is a tuple of functions for casting an element that is
  19863. being read from the tuple, and the third is a tuple of functions for
  19864. casting an element that is being written to the array. You can create
  19865. the functions for reading and writing using lambda expressions. Also,
  19866. as we show in the next section, we need to differentiate these tuples
  19867. of functions from the user-created ones, so we recommend using a new
  19868. AST node named \code{raw-vector} instead of \code{vector}.
  19869. %
  19870. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19871. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19872. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19873. \fi}
  19874. {\if\edition\pythonEd\pythonColor
  19875. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19876. type to another array type is accomplished by creating a proxy that
  19877. intercepts the operations on the underlying array. Here we make the
  19878. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19879. takes fives arguments: the first is an expression for the array, the
  19880. second is a function for casting an element that is being read from
  19881. the array, the third is a function for casting an element that is
  19882. being written to the array, the fourth is the type of the underlying
  19883. array, and the fifth is the type of the proxied array. You can create
  19884. the functions for reading and writing using lambda expressions.
  19885. A cast between two tuple types can be handled in a similar manner. We
  19886. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19887. immutable, so there is no need for a function to cast the value during
  19888. a write. Because there is a separate element type for each slot in
  19889. the tuple, we need more than one function for casting during a read:
  19890. we need a tuple of functions.
  19891. %
  19892. Also, as we show in the next section, we need to differentiate these
  19893. tuples from the user-created ones, so we recommend using a new AST
  19894. node named \code{RawTuple} instead of \code{Tuple} to create the
  19895. tuples of functions.
  19896. %
  19897. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19898. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19899. that involves casting an array of integers to an array of \CANYTY{}.
  19900. \fi}
  19901. \begin{figure}[tbp]
  19902. \begin{tcolorbox}[colback=white]
  19903. {\if\edition\racketEd
  19904. \begin{lstlisting}
  19905. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19906. (begin
  19907. (vector-set! v 0 (f (vector-ref v 0)))
  19908. (vector-set! v 1 (f (vector-ref v 1)))))
  19909. (define (inc [x : Any]) : Any
  19910. (inject (+ (project x Integer) 1) Integer))
  19911. (let ([v (vector 0 41)])
  19912. (begin
  19913. (map_inplace inc (vector-proxy v
  19914. (raw-vector (lambda: ([x9 : Integer]) : Any
  19915. (inject x9 Integer))
  19916. (lambda: ([x9 : Integer]) : Any
  19917. (inject x9 Integer)))
  19918. (raw-vector (lambda: ([x9 : Any]) : Integer
  19919. (project x9 Integer))
  19920. (lambda: ([x9 : Any]) : Integer
  19921. (project x9 Integer)))))
  19922. (vector-ref v 1)))
  19923. \end{lstlisting}
  19924. \fi}
  19925. {\if\edition\pythonEd\pythonColor
  19926. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19927. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19928. i = 0
  19929. while i != array_len(v):
  19930. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19931. i = (i + 1)
  19932. def inc(x : int) -> int:
  19933. return (x + 1)
  19934. def main() -> int:
  19935. v = [0, 41]
  19936. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19937. print(array_load(v, 1))
  19938. return 0
  19939. \end{lstlisting}
  19940. \fi}
  19941. \end{tcolorbox}
  19942. \caption{Output of \code{lower\_casts} on the example shown in
  19943. figure~\ref{fig:map-bang}.}
  19944. \label{fig:map-bang-lower-cast}
  19945. \end{figure}
  19946. A cast from one function type to another function type is accomplished
  19947. by generating a \code{lambda} whose parameter and return types match
  19948. the target function type. The body of the \code{lambda} should cast
  19949. the parameters from the target type to the source type. (Yes,
  19950. backward! Functions are contravariant\index{subject}{contravariant}
  19951. in the parameters.) Afterward, call the underlying function and then
  19952. cast the result from the source return type to the target return type.
  19953. Figure~\ref{fig:map-lower-cast} shows the output of the
  19954. \code{lower\_casts} pass on the \code{map} example given in
  19955. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19956. call to \code{map} is wrapped in a \code{lambda}.
  19957. \begin{figure}[tbp]
  19958. \begin{tcolorbox}[colback=white]
  19959. {\if\edition\racketEd
  19960. \begin{lstlisting}
  19961. (define (map [f : (Integer -> Integer)]
  19962. [v : (Vector Integer Integer)])
  19963. : (Vector Integer Integer)
  19964. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19965. (define (inc [x : Any]) : Any
  19966. (inject (+ (project x Integer) 1) Integer))
  19967. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19968. (project (inc (inject x9 Integer)) Integer))
  19969. (vector 0 41)) 1)
  19970. \end{lstlisting}
  19971. \fi}
  19972. {\if\edition\pythonEd\pythonColor
  19973. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19974. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19975. return (f(v[0]), f(v[1]),)
  19976. def inc(x : any) -> any:
  19977. return inject((project(x, int) + 1), int)
  19978. def main() -> int:
  19979. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19980. print(t[1])
  19981. return 0
  19982. \end{lstlisting}
  19983. \fi}
  19984. \end{tcolorbox}
  19985. \caption{Output of \code{lower\_casts} on the example shown in
  19986. figure~\ref{fig:gradual-map}.}
  19987. \label{fig:map-lower-cast}
  19988. \end{figure}
  19989. %\pagebreak
  19990. \section{Differentiate Proxies }
  19991. \label{sec:differentiate-proxies}
  19992. So far, the responsibility of differentiating tuples and tuple proxies
  19993. has been the job of the interpreter.
  19994. %
  19995. \racket{For example, the interpreter for \LangCast{} implements
  19996. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19997. figure~\ref{fig:guarded-tuple}.}
  19998. %
  19999. In the \code{differentiate\_proxies} pass we shift this responsibility
  20000. to the generated code.
  20001. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20002. we used the type \TUPLETYPENAME{} for both
  20003. real tuples and tuple proxies.
  20004. \python{Similarly, we use the type \code{list} for both arrays and
  20005. array proxies.}
  20006. In \LangPVec{} we return the
  20007. \TUPLETYPENAME{} type to its original
  20008. meaning, as the type of just tuples, and we introduce a new type,
  20009. \PTUPLETYNAME{}, whose values
  20010. can be either real tuples or tuple
  20011. proxies.
  20012. %
  20013. {\if\edition\pythonEd\pythonColor
  20014. Likewise, we return the
  20015. \ARRAYTYPENAME{} type to its original
  20016. meaning, as the type of arrays, and we introduce a new type,
  20017. \PARRAYTYNAME{}, whose values
  20018. can be either arrays or array proxies.
  20019. These new types come with a suite of new primitive operations.
  20020. \fi}
  20021. {\if\edition\racketEd
  20022. A tuple proxy is represented by a tuple containing three things: (1) the
  20023. underlying tuple, (2) a tuple of functions for casting elements that
  20024. are read from the tuple, and (3) a tuple of functions for casting
  20025. values to be written to the tuple. So, we define the following
  20026. abbreviation for the type of a tuple proxy:
  20027. \[
  20028. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20029. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20030. \]
  20031. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20032. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20033. %
  20034. Next we describe each of the new primitive operations.
  20035. \begin{description}
  20036. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20037. (\key{PVector} $T \ldots$)]\ \\
  20038. %
  20039. This operation brands a vector as a value of the \code{PVector} type.
  20040. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20041. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20042. %
  20043. This operation brands a vector proxy as value of the \code{PVector} type.
  20044. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20045. \BOOLTY{}] \ \\
  20046. %
  20047. This returns true if the value is a tuple proxy and false if it is a
  20048. real tuple.
  20049. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20050. (\key{Vector} $T \ldots$)]\ \\
  20051. %
  20052. Assuming that the input is a tuple, this operation returns the
  20053. tuple.
  20054. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20055. $\to$ \INTTY{}]\ \\
  20056. %
  20057. Given a tuple proxy, this operation returns the length of the tuple.
  20058. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20059. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20060. %
  20061. Given a tuple proxy, this operation returns the $i$th element of the
  20062. tuple.
  20063. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20064. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20065. Given a tuple proxy, this operation writes a value to the $i$th element
  20066. of the tuple.
  20067. \end{description}
  20068. \fi}
  20069. {\if\edition\pythonEd\pythonColor
  20070. %
  20071. A tuple proxy is represented by a tuple containing (1) the underlying
  20072. tuple and (2) a tuple of functions for casting elements that are read
  20073. from the tuple. The \LangPVec{} language includes the following AST
  20074. classes and primitive functions.
  20075. \begin{description}
  20076. \item[\code{InjectTuple}] \ \\
  20077. %
  20078. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20079. \item[\code{InjectTupleProxy}]\ \\
  20080. %
  20081. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20082. \item[\code{is\_tuple\_proxy}]\ \\
  20083. %
  20084. This primitive returns true if the value is a tuple proxy and false
  20085. if it is a tuple.
  20086. \item[\code{project\_tuple}]\ \\
  20087. %
  20088. Converts a tuple that is branded as \PTUPLETYNAME{}
  20089. back to a tuple.
  20090. \item[\code{proxy\_tuple\_len}]\ \\
  20091. %
  20092. Given a tuple proxy, returns the length of the underlying tuple.
  20093. \item[\code{proxy\_tuple\_load}]\ \\
  20094. %
  20095. Given a tuple proxy, returns the $i$th element of the underlying
  20096. tuple.
  20097. \end{description}
  20098. An array proxy is represented by a tuple containing (1) the underlying
  20099. array, (2) a function for casting elements that are read from the
  20100. array, and (3) a function for casting elements that are written to the
  20101. array. The \LangPVec{} language includes the following AST classes
  20102. and primitive functions.
  20103. \begin{description}
  20104. \item[\code{InjectList}]\ \\
  20105. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20106. \item[\code{InjectListProxy}]\ \\
  20107. %
  20108. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20109. \item[\code{is\_array\_proxy}]\ \\
  20110. %
  20111. Returns true if the value is an array proxy and false if it is an
  20112. array.
  20113. \item[\code{project\_array}]\ \\
  20114. %
  20115. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20116. array.
  20117. \item[\code{proxy\_array\_len}]\ \\
  20118. %
  20119. Given an array proxy, returns the length of the underlying array.
  20120. \item[\code{proxy\_array\_load}]\ \\
  20121. %
  20122. Given an array proxy, returns the $i$th element of the underlying
  20123. array.
  20124. \item[\code{proxy\_array\_store}]\ \\
  20125. %
  20126. Given an array proxy, writes a value to the $i$th element of the
  20127. underlying array.
  20128. \end{description}
  20129. \fi}
  20130. Now we discuss the translation that differentiates tuples and arrays
  20131. from proxies. First, every type annotation in the program is
  20132. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20133. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20134. places. For example, we wrap every tuple creation with an
  20135. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20136. %
  20137. {\if\edition\racketEd
  20138. \begin{minipage}{0.96\textwidth}
  20139. \begin{lstlisting}
  20140. (vector |$e_1 \ldots e_n$|)
  20141. |$\Rightarrow$|
  20142. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20143. \end{lstlisting}
  20144. \end{minipage}
  20145. \fi}
  20146. {\if\edition\pythonEd\pythonColor
  20147. \begin{lstlisting}
  20148. Tuple(|$e_1, \ldots, e_n$|)
  20149. |$\Rightarrow$|
  20150. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20151. \end{lstlisting}
  20152. \fi}
  20153. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20154. AST node that we introduced in the previous
  20155. section does not get injected.
  20156. {\if\edition\racketEd
  20157. \begin{lstlisting}
  20158. (raw-vector |$e_1 \ldots e_n$|)
  20159. |$\Rightarrow$|
  20160. (vector |$e'_1 \ldots e'_n$|)
  20161. \end{lstlisting}
  20162. \fi}
  20163. {\if\edition\pythonEd\pythonColor
  20164. \begin{lstlisting}
  20165. RawTuple(|$e_1, \ldots, e_n$|)
  20166. |$\Rightarrow$|
  20167. Tuple(|$e'_1, \ldots, e'_n$|)
  20168. \end{lstlisting}
  20169. \fi}
  20170. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20171. translates as follows:
  20172. %
  20173. {\if\edition\racketEd
  20174. \begin{lstlisting}
  20175. (vector-proxy |$e_1~e_2~e_3$|)
  20176. |$\Rightarrow$|
  20177. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20178. \end{lstlisting}
  20179. \fi}
  20180. {\if\edition\pythonEd\pythonColor
  20181. \begin{lstlisting}
  20182. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20183. |$\Rightarrow$|
  20184. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20185. \end{lstlisting}
  20186. \fi}
  20187. We translate the element access operations into conditional
  20188. expressions that check whether the value is a proxy and then dispatch
  20189. to either the appropriate proxy tuple operation or the regular tuple
  20190. operation.
  20191. {\if\edition\racketEd
  20192. \begin{lstlisting}
  20193. (vector-ref |$e_1$| |$i$|)
  20194. |$\Rightarrow$|
  20195. (let ([|$v~e_1$|])
  20196. (if (proxy? |$v$|)
  20197. (proxy-vector-ref |$v$| |$i$|)
  20198. (vector-ref (project-vector |$v$|) |$i$|)
  20199. \end{lstlisting}
  20200. \fi}
  20201. %
  20202. Note that in the branch for a tuple, we must apply
  20203. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20204. from the tuple.
  20205. The translation of array operations is similar to the ones for tuples.
  20206. \section{Reveal Casts }
  20207. \label{sec:reveal-casts-gradual}
  20208. {\if\edition\racketEd
  20209. Recall that the \code{reveal\_casts} pass
  20210. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20211. \code{Inject} and \code{Project} into lower-level operations.
  20212. %
  20213. In particular, \code{Project} turns into a conditional expression that
  20214. inspects the tag and retrieves the underlying value. Here we need to
  20215. augment the translation of \code{Project} to handle the situation in which
  20216. the target type is \code{PVector}. Instead of using
  20217. \code{vector-length} we need to use \code{proxy-vector-length}.
  20218. \begin{lstlisting}
  20219. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20220. |$\Rightarrow$|
  20221. (let |$\itm{tmp}$| |$e'$|
  20222. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20223. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20224. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20225. (exit)))
  20226. \end{lstlisting}
  20227. \fi}
  20228. %
  20229. {\if\edition\pythonEd\pythonColor
  20230. Recall that the $\itm{tagof}$ function determines the bits used to
  20231. identify values of different types, and it is used in the \code{reveal\_casts}
  20232. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20233. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20234. decimal), just like the tuple and array types.
  20235. \fi}
  20236. %
  20237. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20238. \pagebreak
  20239. \section{Closure Conversion }
  20240. \label{sec:closure-conversion-gradual}
  20241. The auxiliary function that translates type annotations needs to be
  20242. updated to handle the \PTUPLETYNAME{}
  20243. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20244. %
  20245. Otherwise, the only other changes are adding cases that copy the new
  20246. AST nodes.
  20247. \section{Select Instructions }
  20248. \label{sec:select-instructions-gradual}
  20249. \index{subject}{select instructions}
  20250. Recall that the \code{select\_instructions} pass is responsible for
  20251. lowering the primitive operations into x86 instructions. So, we need
  20252. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20253. to x86. To do so, the first question we need to answer is how to
  20254. differentiate between tuple and tuple proxies\python{, and likewise for
  20255. arrays and array proxies}. We need just one bit to accomplish this;
  20256. we use the bit in position $63$ of the 64-bit tag at the front of
  20257. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20258. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20259. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20260. it that way.
  20261. {\if\edition\racketEd
  20262. \begin{lstlisting}
  20263. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20264. |$\Rightarrow$|
  20265. movq |$e'_1$|, |$\itm{lhs'}$|
  20266. \end{lstlisting}
  20267. \fi}
  20268. {\if\edition\pythonEd\pythonColor
  20269. \begin{lstlisting}
  20270. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20271. |$\Rightarrow$|
  20272. movq |$e'_1$|, |$\itm{lhs'}$|
  20273. \end{lstlisting}
  20274. \fi}
  20275. \python{The translation for \code{InjectList} is also a move instruction.}
  20276. \noindent On the other hand,
  20277. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20278. $63$ to $1$.
  20279. %
  20280. {\if\edition\racketEd
  20281. \begin{lstlisting}
  20282. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20283. |$\Rightarrow$|
  20284. movq |$e'_1$|, %r11
  20285. movq |$(1 << 63)$|, %rax
  20286. orq 0(%r11), %rax
  20287. movq %rax, 0(%r11)
  20288. movq %r11, |$\itm{lhs'}$|
  20289. \end{lstlisting}
  20290. \fi}
  20291. {\if\edition\pythonEd\pythonColor
  20292. \begin{lstlisting}
  20293. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20294. |$\Rightarrow$|
  20295. movq |$e'_1$|, %r11
  20296. movq |$(1 << 63)$|, %rax
  20297. orq 0(%r11), %rax
  20298. movq %rax, 0(%r11)
  20299. movq %r11, |$\itm{lhs'}$|
  20300. \end{lstlisting}
  20301. \fi}
  20302. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20303. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20304. The \racket{\code{proxy?} operation consumes}%
  20305. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20306. consume}
  20307. the information so carefully stashed away by the injections. It
  20308. isolates bit $63$ to tell whether the value is a proxy.
  20309. %
  20310. {\if\edition\racketEd
  20311. \begin{lstlisting}
  20312. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20313. |$\Rightarrow$|
  20314. movq |$e_1'$|, %r11
  20315. movq 0(%r11), %rax
  20316. sarq $63, %rax
  20317. andq $1, %rax
  20318. movq %rax, |$\itm{lhs'}$|
  20319. \end{lstlisting}
  20320. \fi}%
  20321. %
  20322. {\if\edition\pythonEd\pythonColor
  20323. \begin{lstlisting}
  20324. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20325. |$\Rightarrow$|
  20326. movq |$e_1'$|, %r11
  20327. movq 0(%r11), %rax
  20328. sarq $63, %rax
  20329. andq $1, %rax
  20330. movq %rax, |$\itm{lhs'}$|
  20331. \end{lstlisting}
  20332. \fi}%
  20333. %
  20334. The \racket{\code{project-vector} operation is}
  20335. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20336. straightforward to translate, so we leave that to the reader.
  20337. Regarding the element access operations for tuples\python{ and arrays}, the
  20338. runtime provides procedures that implement them (they are recursive
  20339. functions!), so here we simply need to translate these tuple
  20340. operations into the appropriate function call. For example, here is
  20341. the translation for
  20342. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20343. {\if\edition\racketEd
  20344. \begin{minipage}{0.96\textwidth}
  20345. \begin{lstlisting}
  20346. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20347. |$\Rightarrow$|
  20348. movq |$e_1'$|, %rdi
  20349. movq |$e_2'$|, %rsi
  20350. callq proxy_vector_ref
  20351. movq %rax, |$\itm{lhs'}$|
  20352. \end{lstlisting}
  20353. \end{minipage}
  20354. \fi}
  20355. {\if\edition\pythonEd\pythonColor
  20356. \begin{lstlisting}
  20357. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20358. |$\Rightarrow$|
  20359. movq |$e_1'$|, %rdi
  20360. movq |$e_2'$|, %rsi
  20361. callq proxy_vector_ref
  20362. movq %rax, |$\itm{lhs'}$|
  20363. \end{lstlisting}
  20364. \fi}
  20365. {\if\edition\pythonEd\pythonColor
  20366. % TODO: revisit the names vecof for python -Jeremy
  20367. We translate
  20368. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20369. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20370. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20371. \fi}
  20372. We have another batch of operations to deal with: those for the
  20373. \CANYTY{} type. Recall that we generate an
  20374. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20375. there is a element access on something of type \CANYTY{}, and
  20376. similarly for
  20377. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20378. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20379. section~\ref{sec:select-Lany} we selected instructions for these
  20380. operations on the basis of the idea that the underlying value was a tuple or
  20381. array. But in the current setting, the underlying value is of type
  20382. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20383. functions to deal with this:
  20384. \code{proxy\_vector\_ref},
  20385. \code{proxy\_vector\_set}, and
  20386. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20387. to determine whether the value is a proxy, and then
  20388. dispatches to the the appropriate code.
  20389. %
  20390. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20391. can be translated as follows.
  20392. We begin by projecting the underlying value out of the tagged value and
  20393. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20394. {\if\edition\racketEd
  20395. \begin{lstlisting}
  20396. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20397. |$\Rightarrow$|
  20398. movq |$\neg 111$|, %rdi
  20399. andq |$e_1'$|, %rdi
  20400. movq |$e_2'$|, %rsi
  20401. callq proxy_vector_ref
  20402. movq %rax, |$\itm{lhs'}$|
  20403. \end{lstlisting}
  20404. \fi}
  20405. {\if\edition\pythonEd\pythonColor
  20406. \begin{lstlisting}
  20407. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20408. |$\Rightarrow$|
  20409. movq |$\neg 111$|, %rdi
  20410. andq |$e_1'$|, %rdi
  20411. movq |$e_2'$|, %rsi
  20412. callq proxy_vector_ref
  20413. movq %rax, |$\itm{lhs'}$|
  20414. \end{lstlisting}
  20415. \fi}
  20416. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20417. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20418. are translated in a similar way. Alternatively, you could generate
  20419. instructions to open-code
  20420. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20421. and \code{proxy\_vector\_length} functions.
  20422. \begin{exercise}\normalfont\normalsize
  20423. Implement a compiler for the gradually typed \LangGrad{} language by
  20424. extending and adapting your compiler for \LangLam{}. Create ten new
  20425. partially typed test programs. In addition to testing with these
  20426. new programs, test your compiler on all the tests for \LangLam{}
  20427. and for \LangDyn{}.
  20428. %
  20429. \racket{Sometimes you may get a type-checking error on the
  20430. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20431. the \CANYTY{} type around each subexpression that has caused a type
  20432. error. Although \LangDyn{} does not have explicit casts, you can
  20433. induce one by wrapping the subexpression \code{e} with a call to
  20434. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20435. %
  20436. \python{Sometimes you may get a type-checking error on the
  20437. \LangDyn{} programs, but you can adapt them by inserting a
  20438. temporary variable of type \CANYTY{} that is initialized with the
  20439. troublesome expression.}
  20440. \end{exercise}
  20441. \begin{figure}[t]
  20442. \begin{tcolorbox}[colback=white]
  20443. {\if\edition\racketEd
  20444. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20445. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20446. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20447. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20448. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20449. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20450. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20451. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20452. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20453. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20454. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20455. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20456. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20457. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20458. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20459. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20460. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20461. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20462. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20463. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20464. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20465. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20466. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20467. \path[->,bend left=15] (Lgradual) edge [above] node
  20468. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20469. \path[->,bend left=15] (Lgradual2) edge [above] node
  20470. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20471. \path[->,bend left=15] (Lgradual3) edge [above] node
  20472. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20473. \path[->,bend left=15] (Lgradual4) edge [left] node
  20474. {\ttfamily\footnotesize shrink} (Lgradualr);
  20475. \path[->,bend left=15] (Lgradualr) edge [above] node
  20476. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20477. \path[->,bend right=15] (Lgradualp) edge [above] node
  20478. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20479. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20480. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20481. \path[->,bend right=15] (Llambdapp) edge [above] node
  20482. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20483. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20484. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20485. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20486. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20487. \path[->,bend left=15] (F1-2) edge [above] node
  20488. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20489. \path[->,bend left=15] (F1-3) edge [left] node
  20490. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20491. \path[->,bend left=15] (F1-4) edge [below] node
  20492. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20493. \path[->,bend right=15] (F1-5) edge [above] node
  20494. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20495. \path[->,bend right=15] (F1-6) edge [above] node
  20496. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20497. \path[->,bend right=15] (C3-2) edge [right] node
  20498. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20499. \path[->,bend right=15] (x86-2) edge [right] node
  20500. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20501. \path[->,bend right=15] (x86-2-1) edge [below] node
  20502. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20503. \path[->,bend right=15] (x86-2-2) edge [right] node
  20504. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20505. \path[->,bend left=15] (x86-3) edge [above] node
  20506. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20507. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20508. \end{tikzpicture}
  20509. \fi}
  20510. {\if\edition\pythonEd\pythonColor
  20511. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20512. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20513. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20514. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20515. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20516. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20517. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20518. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20519. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20520. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20521. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20522. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20523. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20524. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20525. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20526. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20527. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20528. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20529. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20530. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20531. \path[->,bend left=15] (Lgradual) edge [above] node
  20532. {\ttfamily\footnotesize shrink} (Lgradual2);
  20533. \path[->,bend left=15] (Lgradual2) edge [above] node
  20534. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20535. \path[->,bend left=15] (Lgradual3) edge [above] node
  20536. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20537. \path[->,bend left=15] (Lgradual4) edge [left] node
  20538. {\ttfamily\footnotesize resolve} (Lgradualr);
  20539. \path[->,bend left=15] (Lgradualr) edge [below] node
  20540. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20541. \path[->,bend right=15] (Lgradualp) edge [above] node
  20542. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20543. \path[->,bend right=15] (Llambdapp) edge [above] node
  20544. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20545. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20546. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20547. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20548. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20549. \path[->,bend left=15] (F1-1) edge [above] node
  20550. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20551. \path[->,bend left=15] (F1-2) edge [above] node
  20552. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20553. \path[->,bend left=15] (F1-3) edge [right] node
  20554. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20555. \path[->,bend right=15] (F1-5) edge [above] node
  20556. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20557. \path[->,bend right=15] (F1-6) edge [above] node
  20558. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20559. \path[->,bend right=15] (C3-2) edge [right] node
  20560. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20561. \path[->,bend right=15] (x86-2) edge [below] node
  20562. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20563. \path[->,bend right=15] (x86-3) edge [below] node
  20564. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20565. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20566. \end{tikzpicture}
  20567. \fi}
  20568. \end{tcolorbox}
  20569. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20570. \label{fig:Lgradual-passes}
  20571. \end{figure}
  20572. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20573. needed for the compilation of \LangGrad{}.
  20574. \section{Further Reading}
  20575. This chapter just scratches the surface of gradual typing. The basic
  20576. approach described here is missing two key ingredients that one would
  20577. want in an implementation of gradual typing: blame
  20578. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20579. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20580. problem addressed by blame tracking is that when a cast on a
  20581. higher-order value fails, it often does so at a point in the program
  20582. that is far removed from the original cast. Blame tracking is a
  20583. technique for propagating extra information through casts and proxies
  20584. so that when a cast fails, the error message can point back to the
  20585. original location of the cast in the source program.
  20586. The problem addressed by space-efficient casts also relates to
  20587. higher-order casts. It turns out that in partially typed programs, a
  20588. function or tuple can flow through a great many casts at runtime. With
  20589. the approach described in this chapter, each cast adds another
  20590. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20591. considerable space, but it also makes the function calls and tuple
  20592. operations slow. For example, a partially typed version of quicksort
  20593. could, in the worst case, build a chain of proxies of length $O(n)$
  20594. around the tuple, changing the overall time complexity of the
  20595. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20596. solution to this problem by representing casts using the coercion
  20597. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20598. long chains of proxies by compressing them into a concise normal
  20599. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20600. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20601. the Grift compiler:
  20602. \begin{center}
  20603. \url{https://github.com/Gradual-Typing/Grift}
  20604. \end{center}
  20605. There are also interesting interactions between gradual typing and
  20606. other language features, such as generics, information-flow types, and
  20607. type inference, to name a few. We recommend to the reader the
  20608. online gradual typing bibliography for more material:
  20609. \begin{center}
  20610. \url{http://samth.github.io/gradual-typing-bib/}
  20611. \end{center}
  20612. % TODO: challenge problem:
  20613. % type analysis and type specialization?
  20614. % coercions?
  20615. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20616. \chapter{Generics}
  20617. \label{ch:Lpoly}
  20618. \setcounter{footnote}{0}
  20619. This chapter studies the compilation of
  20620. generics\index{subject}{generics} (aka parametric
  20621. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20622. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20623. enable programmers to make code more reusable by parameterizing
  20624. functions and data structures with respect to the types on which they
  20625. operate. For example, figure~\ref{fig:map-poly} revisits the
  20626. \code{map} example and this time gives it a more fitting type. This
  20627. \code{map} function is parameterized with respect to the element type
  20628. of the tuple. The type of \code{map} is the following generic type
  20629. specified by the \code{All} type with parameter \code{T}:
  20630. {\if\edition\racketEd
  20631. \begin{lstlisting}
  20632. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20633. \end{lstlisting}
  20634. \fi}
  20635. {\if\edition\pythonEd\pythonColor
  20636. \begin{lstlisting}
  20637. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20638. \end{lstlisting}
  20639. \fi}
  20640. %
  20641. The idea is that \code{map} can be used at \emph{all} choices of a
  20642. type for parameter \code{T}. In the example shown in
  20643. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20644. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20645. \code{T}, but we could have just as well applied \code{map} to a tuple
  20646. of Booleans.
  20647. %
  20648. A \emph{monomorphic} function is simply one that is not generic.
  20649. %
  20650. We use the term \emph{instantiation} for the process (within the
  20651. language implementation) of turning a generic function into a
  20652. monomorphic one, where the type parameters have been replaced by
  20653. types.
  20654. {\if\edition\pythonEd\pythonColor
  20655. %
  20656. In Python, when writing a generic function such as \code{map}, one
  20657. does not explicitly write its generic type (using \code{All}).
  20658. Instead, that the function is generic is implied by the use of type
  20659. variables (such as \code{T}) in the type annotations of its
  20660. parameters.
  20661. %
  20662. \fi}
  20663. \begin{figure}[tbp]
  20664. % poly_test_2.rkt
  20665. \begin{tcolorbox}[colback=white]
  20666. {\if\edition\racketEd
  20667. \begin{lstlisting}
  20668. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20669. (define (map f v)
  20670. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20671. (define (inc [x : Integer]) : Integer (+ x 1))
  20672. (vector-ref (map inc (vector 0 41)) 1)
  20673. \end{lstlisting}
  20674. \fi}
  20675. {\if\edition\pythonEd\pythonColor
  20676. \begin{lstlisting}
  20677. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20678. return (f(tup[0]), f(tup[1]))
  20679. def add1(x : int) -> int:
  20680. return x + 1
  20681. t = map(add1, (0, 41))
  20682. print(t[1])
  20683. \end{lstlisting}
  20684. \fi}
  20685. \end{tcolorbox}
  20686. \caption{A generic version of the \code{map} function.}
  20687. \label{fig:map-poly}
  20688. \end{figure}
  20689. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20690. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20691. shows the definition of the abstract syntax.
  20692. %
  20693. {\if\edition\racketEd
  20694. We add a second form for function definitions in which a type
  20695. declaration comes before the \code{define}. In the abstract syntax,
  20696. the return type in the \code{Def} is \CANYTY{}, but that should be
  20697. ignored in favor of the return type in the type declaration. (The
  20698. \CANYTY{} comes from using the same parser as discussed in
  20699. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20700. enables the use of an \code{All} type for a function, thereby making
  20701. it generic.
  20702. \fi}
  20703. %
  20704. The grammar for types is extended to include the type of a generic
  20705. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20706. abstract syntax)}.
  20707. \newcommand{\LpolyGrammarRacket}{
  20708. \begin{array}{lcl}
  20709. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20710. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20711. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20712. \end{array}
  20713. }
  20714. \newcommand{\LpolyASTRacket}{
  20715. \begin{array}{lcl}
  20716. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20717. \Def &::=& \DECL{\Var}{\Type} \\
  20718. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20719. \end{array}
  20720. }
  20721. \newcommand{\LpolyGrammarPython}{
  20722. \begin{array}{lcl}
  20723. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20724. \end{array}
  20725. }
  20726. \newcommand{\LpolyASTPython}{
  20727. \begin{array}{lcl}
  20728. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20729. \MID \key{GenericVar}\LP\Var\RP
  20730. \end{array}
  20731. }
  20732. \begin{figure}[tp]
  20733. \centering
  20734. \begin{tcolorbox}[colback=white]
  20735. \footnotesize
  20736. {\if\edition\racketEd
  20737. \[
  20738. \begin{array}{l}
  20739. \gray{\LintGrammarRacket{}} \\ \hline
  20740. \gray{\LvarGrammarRacket{}} \\ \hline
  20741. \gray{\LifGrammarRacket{}} \\ \hline
  20742. \gray{\LwhileGrammarRacket} \\ \hline
  20743. \gray{\LtupGrammarRacket} \\ \hline
  20744. \gray{\LfunGrammarRacket} \\ \hline
  20745. \gray{\LlambdaGrammarRacket} \\ \hline
  20746. \LpolyGrammarRacket \\
  20747. \begin{array}{lcl}
  20748. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20749. \end{array}
  20750. \end{array}
  20751. \]
  20752. \fi}
  20753. {\if\edition\pythonEd\pythonColor
  20754. \[
  20755. \begin{array}{l}
  20756. \gray{\LintGrammarPython{}} \\ \hline
  20757. \gray{\LvarGrammarPython{}} \\ \hline
  20758. \gray{\LifGrammarPython{}} \\ \hline
  20759. \gray{\LwhileGrammarPython} \\ \hline
  20760. \gray{\LtupGrammarPython} \\ \hline
  20761. \gray{\LfunGrammarPython} \\ \hline
  20762. \gray{\LlambdaGrammarPython} \\\hline
  20763. \LpolyGrammarPython \\
  20764. \begin{array}{lcl}
  20765. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20766. \end{array}
  20767. \end{array}
  20768. \]
  20769. \fi}
  20770. \end{tcolorbox}
  20771. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20772. (figure~\ref{fig:Llam-concrete-syntax}).}
  20773. \label{fig:Lpoly-concrete-syntax}
  20774. \end{figure}
  20775. \begin{figure}[tp]
  20776. \centering
  20777. \begin{tcolorbox}[colback=white]
  20778. \footnotesize
  20779. {\if\edition\racketEd
  20780. \[
  20781. \begin{array}{l}
  20782. \gray{\LintOpAST} \\ \hline
  20783. \gray{\LvarASTRacket{}} \\ \hline
  20784. \gray{\LifASTRacket{}} \\ \hline
  20785. \gray{\LwhileASTRacket{}} \\ \hline
  20786. \gray{\LtupASTRacket{}} \\ \hline
  20787. \gray{\LfunASTRacket} \\ \hline
  20788. \gray{\LlambdaASTRacket} \\ \hline
  20789. \LpolyASTRacket \\
  20790. \begin{array}{lcl}
  20791. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20792. \end{array}
  20793. \end{array}
  20794. \]
  20795. \fi}
  20796. {\if\edition\pythonEd\pythonColor
  20797. \[
  20798. \begin{array}{l}
  20799. \gray{\LintASTPython} \\ \hline
  20800. \gray{\LvarASTPython{}} \\ \hline
  20801. \gray{\LifASTPython{}} \\ \hline
  20802. \gray{\LwhileASTPython{}} \\ \hline
  20803. \gray{\LtupASTPython{}} \\ \hline
  20804. \gray{\LfunASTPython} \\ \hline
  20805. \gray{\LlambdaASTPython} \\ \hline
  20806. \LpolyASTPython \\
  20807. \begin{array}{lcl}
  20808. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20809. \end{array}
  20810. \end{array}
  20811. \]
  20812. \fi}
  20813. \end{tcolorbox}
  20814. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20815. (figure~\ref{fig:Llam-syntax}).}
  20816. \label{fig:Lpoly-syntax}
  20817. \end{figure}
  20818. By including the \code{All} type in the $\Type$ nonterminal of the
  20819. grammar we choose to make generics first class, which has interesting
  20820. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20821. not include syntax for the \code{All} type. It is inferred for functions whose
  20822. type annotations contain type variables.} Many languages with generics, such as
  20823. C++~\citep{stroustrup88:_param_types} and Standard
  20824. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20825. may be helpful to see an example of first-class generics in action. In
  20826. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20827. whose parameter is a generic function. Indeed, because the grammar for
  20828. $\Type$ includes the \code{All} type, a generic function may also be
  20829. returned from a function or stored inside a tuple. The body of
  20830. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20831. and also to an integer, which would not be possible if \code{f} were
  20832. not generic.
  20833. \begin{figure}[tbp]
  20834. \begin{tcolorbox}[colback=white]
  20835. {\if\edition\racketEd
  20836. \begin{lstlisting}
  20837. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20838. (define (apply_twice f)
  20839. (if (f #t) (f 42) (f 777)))
  20840. (: id (All (T) (T -> T)))
  20841. (define (id x) x)
  20842. (apply_twice id)
  20843. \end{lstlisting}
  20844. \fi}
  20845. {\if\edition\pythonEd\pythonColor
  20846. \begin{lstlisting}
  20847. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20848. if f(True):
  20849. return f(42)
  20850. else:
  20851. return f(777)
  20852. def id(x: T) -> T:
  20853. return x
  20854. print(apply_twice(id))
  20855. \end{lstlisting}
  20856. \fi}
  20857. \end{tcolorbox}
  20858. \caption{An example illustrating first-class generics.}
  20859. \label{fig:apply-twice}
  20860. \end{figure}
  20861. The type checker for \LangPoly{} shown in
  20862. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20863. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20864. {\if\edition\pythonEd\pythonColor
  20865. %
  20866. Regarding function definitions, if the type annotations on its
  20867. parameters contain generic variables, then the function is generic and
  20868. therefore its type is an \code{All} type wrapped around a function
  20869. type. Otherwise the function is monomorphic and its type is simply
  20870. a function type.
  20871. %
  20872. \fi}
  20873. The type checking of a function application is extended to handle the
  20874. case in which the operator expression is a generic function. In that case
  20875. the type arguments are deduced by matching the types of the parameters
  20876. with the types of the arguments.
  20877. %
  20878. The \code{match\_types} auxiliary function
  20879. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20880. recursively descending through a parameter type \code{param\_ty} and
  20881. the corresponding argument type \code{arg\_ty}, making sure that they
  20882. are equal except when there is a type parameter in the parameter
  20883. type. Upon encountering a type parameter for the first time, the
  20884. algorithm deduces an association of the type parameter to the
  20885. corresponding part of the argument type. If it is not the first time
  20886. that the type parameter has been encountered, the algorithm looks up
  20887. its deduced type and makes sure that it is equal to the corresponding
  20888. part of the argument type. The return type of the application is the
  20889. return type of the generic function with the type parameters
  20890. replaced by the deduced type arguments, using the
  20891. \code{substitute\_type} auxiliary function, which is also listed in
  20892. figure~\ref{fig:type-check-Lpoly-aux}.
  20893. The type checker extends type equality to handle the \code{All} type.
  20894. This is not quite as simple as for other types, such as function and
  20895. tuple types, because two \code{All} types can be syntactically
  20896. different even though they are equivalent. For example,
  20897. \begin{center}
  20898. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20899. \end{center}
  20900. is equivalent to
  20901. \begin{center}
  20902. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20903. \end{center}
  20904. Two generic types are equal if they differ only in
  20905. the choice of the names of the type parameters. The definition of type
  20906. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20907. parameters in one type to match the type parameters of the other type.
  20908. {\if\edition\racketEd
  20909. %
  20910. The type checker also ensures that only defined type variables appear
  20911. in type annotations. The \code{check\_well\_formed} function for which
  20912. the definition is shown in figure~\ref{fig:well-formed-types}
  20913. recursively inspects a type, making sure that each type variable has
  20914. been defined.
  20915. %
  20916. \fi}
  20917. \begin{figure}[tbp]
  20918. \begin{tcolorbox}[colback=white]
  20919. {\if\edition\racketEd
  20920. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20921. (define type-check-poly-class
  20922. (class type-check-Llambda-class
  20923. (super-new)
  20924. (inherit check-type-equal?)
  20925. (define/override (type-check-apply env e1 es)
  20926. (define-values (e^ ty) ((type-check-exp env) e1))
  20927. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20928. ((type-check-exp env) e)))
  20929. (match ty
  20930. [`(,ty^* ... -> ,rt)
  20931. (for ([arg-ty ty*] [param-ty ty^*])
  20932. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20933. (values e^ es^ rt)]
  20934. [`(All ,xs (,tys ... -> ,rt))
  20935. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20936. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20937. (match_types env^^ param-ty arg-ty)))
  20938. (define targs
  20939. (for/list ([x xs])
  20940. (match (dict-ref env^^ x (lambda () #f))
  20941. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20942. x (Apply e1 es))]
  20943. [ty ty])))
  20944. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20945. [else (error 'type-check "expected a function, not ~a" ty)]))
  20946. (define/override ((type-check-exp env) e)
  20947. (match e
  20948. [(Lambda `([,xs : ,Ts] ...) rT body)
  20949. (for ([T Ts]) ((check_well_formed env) T))
  20950. ((check_well_formed env) rT)
  20951. ((super type-check-exp env) e)]
  20952. [(HasType e1 ty)
  20953. ((check_well_formed env) ty)
  20954. ((super type-check-exp env) e)]
  20955. [else ((super type-check-exp env) e)]))
  20956. (define/override ((type-check-def env) d)
  20957. (verbose 'type-check "poly/def" d)
  20958. (match d
  20959. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20960. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20961. (for ([p ps]) ((check_well_formed ts-env) p))
  20962. ((check_well_formed ts-env) rt)
  20963. (define new-env (append ts-env (map cons xs ps) env))
  20964. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20965. (check-type-equal? ty^ rt body)
  20966. (Generic ts (Def f p:t* rt info body^))]
  20967. [else ((super type-check-def env) d)]))
  20968. (define/override (type-check-program p)
  20969. (match p
  20970. [(Program info body)
  20971. (type-check-program (ProgramDefsExp info '() body))]
  20972. [(ProgramDefsExp info ds body)
  20973. (define ds^ (combine-decls-defs ds))
  20974. (define new-env (for/list ([d ds^])
  20975. (cons (def-name d) (fun-def-type d))))
  20976. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20977. (define-values (body^ ty) ((type-check-exp new-env) body))
  20978. (check-type-equal? ty 'Integer body)
  20979. (ProgramDefsExp info ds^^ body^)]))
  20980. ))
  20981. \end{lstlisting}
  20982. \fi}
  20983. {\if\edition\pythonEd\pythonColor
  20984. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20985. def type_check_exp(self, e, env):
  20986. match e:
  20987. case Call(Name(f), args) if f in builtin_functions:
  20988. return super().type_check_exp(e, env)
  20989. case Call(func, args):
  20990. func_t = self.type_check_exp(func, env)
  20991. func.has_type = func_t
  20992. match func_t:
  20993. case AllType(ps, FunctionType(p_tys, rt)):
  20994. for arg in args:
  20995. arg.has_type = self.type_check_exp(arg, env)
  20996. arg_tys = [arg.has_type for arg in args]
  20997. deduced = {}
  20998. for (p, a) in zip(p_tys, arg_tys):
  20999. self.match_types(p, a, deduced, e)
  21000. return self.substitute_type(rt, deduced)
  21001. case _:
  21002. return super().type_check_exp(e, env)
  21003. case _:
  21004. return super().type_check_exp(e, env)
  21005. def type_check(self, p):
  21006. match p:
  21007. case Module(body):
  21008. env = {}
  21009. for s in body:
  21010. match s:
  21011. case FunctionDef(name, params, bod, dl, returns, comment):
  21012. params_t = [t for (x,t) in params]
  21013. ty_params = set()
  21014. for t in params_t:
  21015. ty_params |$\mid$|= self.generic_variables(t)
  21016. ty = FunctionType(params_t, returns)
  21017. if len(ty_params) > 0:
  21018. ty = AllType(list(ty_params), ty)
  21019. env[name] = ty
  21020. self.check_stmts(body, IntType(), env)
  21021. case _:
  21022. raise Exception('type_check: unexpected ' + repr(p))
  21023. \end{lstlisting}
  21024. \fi}
  21025. \end{tcolorbox}
  21026. \caption{Type checker for the \LangPoly{} language.}
  21027. \label{fig:type-check-Lpoly}
  21028. \end{figure}
  21029. \begin{figure}[tbp]
  21030. \begin{tcolorbox}[colback=white]
  21031. {\if\edition\racketEd
  21032. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21033. (define/override (type-equal? t1 t2)
  21034. (match* (t1 t2)
  21035. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21036. (define env (map cons xs ys))
  21037. (type-equal? (substitute_type env T1) T2)]
  21038. [(other wise)
  21039. (super type-equal? t1 t2)]))
  21040. (define/public (match_types env pt at)
  21041. (match* (pt at)
  21042. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21043. [('Void 'Void) env] [('Any 'Any) env]
  21044. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21045. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21046. (match_types env^ pt1 at1))]
  21047. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21048. (define env^ (match_types env prt art))
  21049. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21050. (match_types env^^ pt1 at1))]
  21051. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21052. (define env^ (append (map cons pxs axs) env))
  21053. (match_types env^ pt1 at1)]
  21054. [((? symbol? x) at)
  21055. (match (dict-ref env x (lambda () #f))
  21056. [#f (error 'type-check "undefined type variable ~a" x)]
  21057. ['Type (cons (cons x at) env)]
  21058. [t^ (check-type-equal? at t^ 'matching) env])]
  21059. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21060. (define/public (substitute_type env pt)
  21061. (match pt
  21062. ['Integer 'Integer] ['Boolean 'Boolean]
  21063. ['Void 'Void] ['Any 'Any]
  21064. [`(Vector ,ts ...)
  21065. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21066. [`(,ts ... -> ,rt)
  21067. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21068. [`(All ,xs ,t)
  21069. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21070. [(? symbol? x) (dict-ref env x)]
  21071. [else (error 'type-check "expected a type not ~a" pt)]))
  21072. (define/public (combine-decls-defs ds)
  21073. (match ds
  21074. ['() '()]
  21075. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21076. (unless (equal? name f)
  21077. (error 'type-check "name mismatch, ~a != ~a" name f))
  21078. (match type
  21079. [`(All ,xs (,ps ... -> ,rt))
  21080. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21081. (cons (Generic xs (Def name params^ rt info body))
  21082. (combine-decls-defs ds^))]
  21083. [`(,ps ... -> ,rt)
  21084. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21085. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21086. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21087. [`(,(Def f params rt info body) . ,ds^)
  21088. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21089. \end{lstlisting}
  21090. \fi}
  21091. {\if\edition\pythonEd\pythonColor
  21092. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21093. def match_types(self, param_ty, arg_ty, deduced, e):
  21094. match (param_ty, arg_ty):
  21095. case (GenericVar(id), _):
  21096. if id in deduced:
  21097. self.check_type_equal(arg_ty, deduced[id], e)
  21098. else:
  21099. deduced[id] = arg_ty
  21100. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21101. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21102. new_arg_ty = self.substitute_type(arg_ty, rename)
  21103. self.match_types(ty, new_arg_ty, deduced, e)
  21104. case (TupleType(ps), TupleType(ts)):
  21105. for (p, a) in zip(ps, ts):
  21106. self.match_types(p, a, deduced, e)
  21107. case (ListType(p), ListType(a)):
  21108. self.match_types(p, a, deduced, e)
  21109. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21110. for (pp, ap) in zip(pps, aps):
  21111. self.match_types(pp, ap, deduced, e)
  21112. self.match_types(prt, art, deduced, e)
  21113. case (IntType(), IntType()):
  21114. pass
  21115. case (BoolType(), BoolType()):
  21116. pass
  21117. case _:
  21118. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21119. def substitute_type(self, ty, var_map):
  21120. match ty:
  21121. case GenericVar(id):
  21122. return var_map[id]
  21123. case AllType(ps, ty):
  21124. new_map = copy.deepcopy(var_map)
  21125. for p in ps:
  21126. new_map[p] = GenericVar(p)
  21127. return AllType(ps, self.substitute_type(ty, new_map))
  21128. case TupleType(ts):
  21129. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21130. case ListType(ty):
  21131. return ListType(self.substitute_type(ty, var_map))
  21132. case FunctionType(pts, rt):
  21133. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21134. self.substitute_type(rt, var_map))
  21135. case IntType():
  21136. return IntType()
  21137. case BoolType():
  21138. return BoolType()
  21139. case _:
  21140. raise Exception('substitute_type: unexpected ' + repr(ty))
  21141. def check_type_equal(self, t1, t2, e):
  21142. match (t1, t2):
  21143. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21144. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21145. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21146. case (_, _):
  21147. return super().check_type_equal(t1, t2, e)
  21148. \end{lstlisting}
  21149. \fi}
  21150. \end{tcolorbox}
  21151. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21152. \label{fig:type-check-Lpoly-aux}
  21153. \end{figure}
  21154. {\if\edition\racketEd
  21155. \begin{figure}[tbp]
  21156. \begin{tcolorbox}[colback=white]
  21157. \begin{lstlisting}
  21158. (define/public ((check_well_formed env) ty)
  21159. (match ty
  21160. ['Integer (void)]
  21161. ['Boolean (void)]
  21162. ['Void (void)]
  21163. [(? symbol? a)
  21164. (match (dict-ref env a (lambda () #f))
  21165. ['Type (void)]
  21166. [else (error 'type-check "undefined type variable ~a" a)])]
  21167. [`(Vector ,ts ...)
  21168. (for ([t ts]) ((check_well_formed env) t))]
  21169. [`(,ts ... -> ,t)
  21170. (for ([t ts]) ((check_well_formed env) t))
  21171. ((check_well_formed env) t)]
  21172. [`(All ,xs ,t)
  21173. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21174. ((check_well_formed env^) t)]
  21175. [else (error 'type-check "unrecognized type ~a" ty)]))
  21176. \end{lstlisting}
  21177. \end{tcolorbox}
  21178. \caption{Well-formed types.}
  21179. \label{fig:well-formed-types}
  21180. \end{figure}
  21181. \fi}
  21182. % TODO: interpreter for R'_10
  21183. \clearpage
  21184. \section{Compiling Generics}
  21185. \label{sec:compiling-poly}
  21186. Broadly speaking, there are four approaches to compiling generics, as
  21187. follows:
  21188. \begin{description}
  21189. \item[Monomorphization] generates a different version of a generic
  21190. function for each set of type arguments with which it is used,
  21191. producing type-specialized code. This approach results in the most
  21192. efficient code but requires whole-program compilation (no separate
  21193. compilation) and may increase code size. Unfortunately,
  21194. monomorphization is incompatible with first-class generics because
  21195. it is not always possible to determine which generic functions are
  21196. used with which type arguments during compilation. (It can be done
  21197. at runtime with just-in-time compilation.) Monomorphization is
  21198. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21199. generic functions in NESL~\citep{Blelloch:1993aa} and
  21200. ML~\citep{Weeks:2006aa}.
  21201. \item[Uniform representation] generates one version of each generic
  21202. function and requires all values to have a common \emph{boxed} format,
  21203. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21204. generic and monomorphic code is compiled similarly to code in a
  21205. dynamically typed language (like \LangDyn{}), in which primitive
  21206. operators require their arguments to be projected from \CANYTY{} and
  21207. their results to be injected into \CANYTY{}. (In object-oriented
  21208. languages, the projection is accomplished via virtual method
  21209. dispatch.) The uniform representation approach is compatible with
  21210. separate compilation and with first-class generics. However, it
  21211. produces the least efficient code because it introduces overhead in
  21212. the entire program. This approach is used in
  21213. Java~\citep{Bracha:1998fk},
  21214. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21215. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21216. \item[Mixed representation] generates one version of each generic
  21217. function, using a boxed representation for type variables. However,
  21218. monomorphic code is compiled as usual (as in \LangLam{}), and
  21219. conversions are performed at the boundaries between monomorphic code
  21220. and polymorphic code (for example, when a generic function is instantiated
  21221. and called). This approach is compatible with separate compilation
  21222. and first-class generics and maintains efficiency in monomorphic
  21223. code. The trade-off is increased overhead at the boundary between
  21224. monomorphic and generic code. This approach is used in
  21225. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21226. Java 5 with the addition of autoboxing.
  21227. \item[Type passing] uses the unboxed representation in both
  21228. monomorphic and generic code. Each generic function is compiled to a
  21229. single function with extra parameters that describe the type
  21230. arguments. The type information is used by the generated code to
  21231. determine how to access the unboxed values at runtime. This approach is
  21232. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21233. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21234. compilation and first-class generics and maintains the
  21235. efficiency for monomorphic code. There is runtime overhead in
  21236. polymorphic code from dispatching on type information.
  21237. \end{description}
  21238. In this chapter we use the mixed representation approach, partly
  21239. because of its favorable attributes and partly because it is
  21240. straightforward to implement using the tools that we have already
  21241. built to support gradual typing. The work of compiling generic
  21242. functions is performed in two passes, \code{resolve} and
  21243. \code{erase\_types}, that we discuss next. The output of
  21244. \code{erase\_types} is \LangCast{}
  21245. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21246. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21247. \section{Resolve Instantiation}
  21248. \label{sec:generic-resolve}
  21249. Recall that the type checker for \LangPoly{} deduces the type
  21250. arguments at call sites to a generic function. The purpose of the
  21251. \code{resolve} pass is to turn this implicit instantiation into an
  21252. explicit one, by adding \code{inst} nodes to the syntax of the
  21253. intermediate language. An \code{inst} node records the mapping of
  21254. type parameters to type arguments. The semantics of the \code{inst}
  21255. node is to instantiate the result of its first argument, a generic
  21256. function, to produce a monomorphic function. However, because the
  21257. interpreter never analyzes type annotations, instantiation can be a
  21258. no-op and simply return the generic function.
  21259. %
  21260. The output language of the \code{resolve} pass is \LangInst{},
  21261. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21262. {\if\edition\racketEd
  21263. The \code{resolve} pass combines the type declaration and polymorphic
  21264. function into a single definition, using the \code{Poly} form, to make
  21265. polymorphic functions more convenient to process in the next pass of the
  21266. compiler.
  21267. \fi}
  21268. \newcommand{\LinstASTRacket}{
  21269. \begin{array}{lcl}
  21270. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21271. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21272. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21273. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21274. \end{array}
  21275. }
  21276. \newcommand{\LinstASTPython}{
  21277. \begin{array}{lcl}
  21278. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21279. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21280. \end{array}
  21281. }
  21282. \begin{figure}[tp]
  21283. \centering
  21284. \begin{tcolorbox}[colback=white]
  21285. \small
  21286. {\if\edition\racketEd
  21287. \[
  21288. \begin{array}{l}
  21289. \gray{\LintOpAST} \\ \hline
  21290. \gray{\LvarASTRacket{}} \\ \hline
  21291. \gray{\LifASTRacket{}} \\ \hline
  21292. \gray{\LwhileASTRacket{}} \\ \hline
  21293. \gray{\LtupASTRacket{}} \\ \hline
  21294. \gray{\LfunASTRacket} \\ \hline
  21295. \gray{\LlambdaASTRacket} \\ \hline
  21296. \LinstASTRacket \\
  21297. \begin{array}{lcl}
  21298. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21299. \end{array}
  21300. \end{array}
  21301. \]
  21302. \fi}
  21303. {\if\edition\pythonEd\pythonColor
  21304. \[
  21305. \begin{array}{l}
  21306. \gray{\LintASTPython} \\ \hline
  21307. \gray{\LvarASTPython{}} \\ \hline
  21308. \gray{\LifASTPython{}} \\ \hline
  21309. \gray{\LwhileASTPython{}} \\ \hline
  21310. \gray{\LtupASTPython{}} \\ \hline
  21311. \gray{\LfunASTPython} \\ \hline
  21312. \gray{\LlambdaASTPython} \\ \hline
  21313. \LinstASTPython \\
  21314. \begin{array}{lcl}
  21315. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21316. \end{array}
  21317. \end{array}
  21318. \]
  21319. \fi}
  21320. \end{tcolorbox}
  21321. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21322. (figure~\ref{fig:Llam-syntax}).}
  21323. \label{fig:Lpoly-prime-syntax}
  21324. \end{figure}
  21325. The output of the \code{resolve} pass on the generic \code{map}
  21326. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21327. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21328. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21329. \begin{figure}[tbp]
  21330. % poly_test_2.rkt
  21331. \begin{tcolorbox}[colback=white]
  21332. {\if\edition\racketEd
  21333. \begin{lstlisting}
  21334. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21335. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21336. (define (inc [x : Integer]) : Integer (+ x 1))
  21337. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21338. (Integer))
  21339. inc (vector 0 41)) 1)
  21340. \end{lstlisting}
  21341. \fi}
  21342. {\if\edition\pythonEd\pythonColor
  21343. \begin{lstlisting}
  21344. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21345. return (f(tup[0]), f(tup[1]))
  21346. def add1(x : int) -> int:
  21347. return x + 1
  21348. t = inst(map, {T: int})(add1, (0, 41))
  21349. print(t[1])
  21350. \end{lstlisting}
  21351. \fi}
  21352. \end{tcolorbox}
  21353. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21354. \label{fig:map-resolve}
  21355. \end{figure}
  21356. \section{Erase Generic Types}
  21357. \label{sec:erase_types}
  21358. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21359. represent type variables. For example, figure~\ref{fig:map-erase}
  21360. shows the output of the \code{erase\_types} pass on the generic
  21361. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21362. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21363. \code{All} types are removed from the type of \code{map}.
  21364. \begin{figure}[tbp]
  21365. \begin{tcolorbox}[colback=white]
  21366. {\if\edition\racketEd
  21367. \begin{lstlisting}
  21368. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21369. : (Vector Any Any)
  21370. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21371. (define (inc [x : Integer]) : Integer (+ x 1))
  21372. (vector-ref ((cast map
  21373. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21374. ((Integer -> Integer) (Vector Integer Integer)
  21375. -> (Vector Integer Integer)))
  21376. inc (vector 0 41)) 1)
  21377. \end{lstlisting}
  21378. \fi}
  21379. {\if\edition\pythonEd\pythonColor
  21380. \begin{lstlisting}
  21381. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21382. return (f(tup[0]), f(tup[1]))
  21383. def add1(x : int) -> int:
  21384. return (x + 1)
  21385. def main() -> int:
  21386. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21387. print(t[1])
  21388. return 0
  21389. \end{lstlisting}
  21390. {\small
  21391. where\\
  21392. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21393. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21394. }
  21395. \fi}
  21396. \end{tcolorbox}
  21397. \caption{The generic \code{map} example after type erasure.}
  21398. \label{fig:map-erase}
  21399. \end{figure}
  21400. This process of type erasure creates a challenge at points of
  21401. instantiation. For example, consider the instantiation of
  21402. \code{map} shown in figure~\ref{fig:map-resolve}.
  21403. The type of \code{map} is
  21404. %
  21405. {\if\edition\racketEd
  21406. \begin{lstlisting}
  21407. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21408. \end{lstlisting}
  21409. \fi}
  21410. {\if\edition\pythonEd\pythonColor
  21411. \begin{lstlisting}
  21412. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21413. \end{lstlisting}
  21414. \fi}
  21415. %
  21416. \noindent and it is instantiated to
  21417. %
  21418. {\if\edition\racketEd
  21419. \begin{lstlisting}
  21420. ((Integer -> Integer) (Vector Integer Integer)
  21421. -> (Vector Integer Integer))
  21422. \end{lstlisting}
  21423. \fi}
  21424. {\if\edition\pythonEd\pythonColor
  21425. \begin{lstlisting}
  21426. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21427. \end{lstlisting}
  21428. \fi}
  21429. %
  21430. \noindent After erasure, the type of \code{map} is
  21431. %
  21432. {\if\edition\racketEd
  21433. \begin{lstlisting}
  21434. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21435. \end{lstlisting}
  21436. \fi}
  21437. {\if\edition\pythonEd\pythonColor
  21438. \begin{lstlisting}
  21439. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21440. \end{lstlisting}
  21441. \fi}
  21442. %
  21443. \noindent but we need to convert it to the instantiated type. This is
  21444. easy to do in the language \LangCast{} with a single \code{cast}. In
  21445. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21446. \code{map} has been compiled to a \code{cast} from the type of
  21447. \code{map} to the instantiated type. The source and the target type of
  21448. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21449. is the case because both the source and target are obtained from the
  21450. same generic type of \code{map}, replacing the type parameters with
  21451. \CANYTY{} in the former and with the deduced type arguments in the
  21452. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21453. To implement the \code{erase\_types} pass, we first recommend defining
  21454. a recursive function that translates types, named
  21455. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21456. follows.
  21457. %
  21458. {\if\edition\racketEd
  21459. \begin{lstlisting}
  21460. |$T$|
  21461. |$\Rightarrow$|
  21462. Any
  21463. \end{lstlisting}
  21464. \fi}
  21465. {\if\edition\pythonEd\pythonColor
  21466. \begin{lstlisting}
  21467. GenericVar(|$T$|)
  21468. |$\Rightarrow$|
  21469. Any
  21470. \end{lstlisting}
  21471. \fi}
  21472. %
  21473. \noindent The \code{erase\_type} function also removes the generic
  21474. \code{All} types.
  21475. %
  21476. {\if\edition\racketEd
  21477. \begin{lstlisting}
  21478. (All |$xs$| |$T_1$|)
  21479. |$\Rightarrow$|
  21480. |$T'_1$|
  21481. \end{lstlisting}
  21482. \fi}
  21483. {\if\edition\pythonEd\pythonColor
  21484. \begin{lstlisting}
  21485. AllType(|$xs$|, |$T_1$|)
  21486. |$\Rightarrow$|
  21487. |$T'_1$|
  21488. \end{lstlisting}
  21489. \fi}
  21490. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21491. $T_1$.
  21492. %
  21493. In this compiler pass, apply the \code{erase\_type} function to all
  21494. the type annotations in the program.
  21495. Regarding the translation of expressions, the case for \code{Inst} is
  21496. the interesting one. We translate it into a \code{Cast}, as shown
  21497. next.
  21498. The type of the subexpression $e$ is a generic type of the form
  21499. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21500. The source type of the cast is the erasure of $T$, the type $T_s$.
  21501. %
  21502. {\if\edition\racketEd
  21503. %
  21504. The target type $T_t$ is the result of substituting the argument types
  21505. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21506. erasure.
  21507. %
  21508. \begin{lstlisting}
  21509. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21510. |$\Rightarrow$|
  21511. (Cast |$e'$| |$T_s$| |$T_t$|)
  21512. \end{lstlisting}
  21513. %
  21514. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21515. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21516. \fi}
  21517. {\if\edition\pythonEd\pythonColor
  21518. %
  21519. The target type $T_t$ is the result of substituting the deduced
  21520. argument types $d$ in $T$ and then performing type erasure.
  21521. %
  21522. \begin{lstlisting}
  21523. Inst(|$e$|, |$d$|)
  21524. |$\Rightarrow$|
  21525. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21526. \end{lstlisting}
  21527. %
  21528. where
  21529. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21530. \fi}
  21531. Finally, each generic function is translated to a regular
  21532. function in which type erasure has been applied to all the type
  21533. annotations and the body.
  21534. %% \begin{lstlisting}
  21535. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21536. %% |$\Rightarrow$|
  21537. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21538. %% \end{lstlisting}
  21539. \begin{exercise}\normalfont\normalsize
  21540. Implement a compiler for the polymorphic language \LangPoly{} by
  21541. extending and adapting your compiler for \LangGrad{}. Create six new
  21542. test programs that use polymorphic functions. Some of them should
  21543. make use of first-class generics.
  21544. \end{exercise}
  21545. \begin{figure}[tbp]
  21546. \begin{tcolorbox}[colback=white]
  21547. {\if\edition\racketEd
  21548. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21549. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21550. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21551. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21552. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21553. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21554. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21555. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21556. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21557. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21558. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21559. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21560. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21561. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21562. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21563. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21564. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21565. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21566. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21567. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21568. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21569. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21570. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21571. \path[->,bend left=15] (Lpoly) edge [above] node
  21572. {\ttfamily\footnotesize resolve} (Lpolyp);
  21573. \path[->,bend left=15] (Lpolyp) edge [above] node
  21574. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21575. \path[->,bend left=15] (Lgradualp) edge [above] node
  21576. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21577. \path[->,bend left=15] (Llambdapp) edge [left] node
  21578. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21579. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21580. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21581. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21582. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21583. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21584. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21585. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21586. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21587. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21588. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21589. \path[->,bend left=15] (F1-1) edge [above] node
  21590. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21591. \path[->,bend left=15] (F1-2) edge [above] node
  21592. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21593. \path[->,bend left=15] (F1-3) edge [left] node
  21594. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21595. \path[->,bend left=15] (F1-4) edge [below] node
  21596. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21597. \path[->,bend right=15] (F1-5) edge [above] node
  21598. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21599. \path[->,bend right=15] (F1-6) edge [above] node
  21600. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21601. \path[->,bend right=15] (C3-2) edge [right] node
  21602. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21603. \path[->,bend right=15] (x86-2) edge [right] node
  21604. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21605. \path[->,bend right=15] (x86-2-1) edge [below] node
  21606. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21607. \path[->,bend right=15] (x86-2-2) edge [right] node
  21608. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21609. \path[->,bend left=15] (x86-3) edge [above] node
  21610. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21611. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21612. \end{tikzpicture}
  21613. \fi}
  21614. {\if\edition\pythonEd\pythonColor
  21615. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21616. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21617. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21618. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21619. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21620. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21621. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21622. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21623. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21624. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21625. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21626. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21627. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21628. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21629. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21630. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21631. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21632. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21633. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21634. \path[->,bend left=15] (Lgradual) edge [above] node
  21635. {\ttfamily\footnotesize shrink} (Lgradual2);
  21636. \path[->,bend left=15] (Lgradual2) edge [above] node
  21637. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21638. \path[->,bend left=15] (Lgradual3) edge [above] node
  21639. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21640. \path[->,bend left=15] (Lgradual4) edge [left] node
  21641. {\ttfamily\footnotesize resolve} (Lgradualr);
  21642. \path[->,bend left=15] (Lgradualr) edge [below] node
  21643. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21644. \path[->,bend right=15] (Llambdapp) edge [above] node
  21645. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21646. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21647. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21648. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21649. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21650. \path[->,bend right=15] (F1-1) edge [below] node
  21651. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21652. \path[->,bend right=15] (F1-2) edge [below] node
  21653. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21654. \path[->,bend left=15] (F1-3) edge [above] node
  21655. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21656. \path[->,bend left=15] (F1-5) edge [left] node
  21657. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21658. \path[->,bend left=5] (F1-6) edge [below] node
  21659. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21660. \path[->,bend right=15] (C3-2) edge [right] node
  21661. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21662. \path[->,bend right=15] (x86-2) edge [below] node
  21663. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21664. \path[->,bend right=15] (x86-3) edge [below] node
  21665. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21666. \path[->,bend left=15] (x86-4) edge [above] node
  21667. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21668. \end{tikzpicture}
  21669. \fi}
  21670. \end{tcolorbox}
  21671. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21672. \label{fig:Lpoly-passes}
  21673. \end{figure}
  21674. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21675. needed to compile \LangPoly{}.
  21676. % TODO: challenge problem: specialization of instantiations
  21677. % Further Reading
  21678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21679. \clearpage
  21680. \appendix
  21681. \chapter{Appendix}
  21682. \setcounter{footnote}{0}
  21683. {\if\edition\racketEd
  21684. \section{Interpreters}
  21685. \label{appendix:interp}
  21686. \index{subject}{interpreter}
  21687. We provide interpreters for each of the source languages \LangInt{},
  21688. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21689. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21690. intermediate languages \LangCVar{} and \LangCIf{} are in
  21691. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21692. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21693. \key{interp.rkt} file.
  21694. \section{Utility Functions}
  21695. \label{appendix:utilities}
  21696. The utility functions described in this section are in the
  21697. \key{utilities.rkt} file of the support code.
  21698. \paragraph{\code{interp-tests}}
  21699. This function runs the compiler passes and the interpreters on each of
  21700. the specified tests to check whether each pass is correct. The
  21701. \key{interp-tests} function has the following parameters:
  21702. \begin{description}
  21703. \item[name (a string)] A name to identify the compiler.
  21704. \item[typechecker] A function of exactly one argument that either
  21705. raises an error using the \code{error} function when it encounters a
  21706. type error, or returns \code{\#f} when it encounters a type
  21707. error. If there is no type error, the type checker returns the
  21708. program.
  21709. \item[passes] A list with one entry per pass. An entry is a list
  21710. consisting of four things:
  21711. \begin{enumerate}
  21712. \item a string giving the name of the pass;
  21713. \item the function that implements the pass (a translator from AST
  21714. to AST);
  21715. \item a function that implements the interpreter (a function from
  21716. AST to result value) for the output language; and,
  21717. \item a type checker for the output language. Type checkers for
  21718. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21719. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21720. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21721. type checker entry is optional. The support code does not provide
  21722. type checkers for the x86 languages.
  21723. \end{enumerate}
  21724. \item[source-interp] An interpreter for the source language. The
  21725. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21726. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21727. \item[tests] A list of test numbers that specifies which tests to
  21728. run (explained next).
  21729. \end{description}
  21730. %
  21731. The \key{interp-tests} function assumes that the subdirectory
  21732. \key{tests} has a collection of Racket programs whose names all start
  21733. with the family name, followed by an underscore and then the test
  21734. number, and ending with the file extension \key{.rkt}. Also, for each test
  21735. program that calls \code{read} one or more times, there is a file with
  21736. the same name except that the file extension is \key{.in}, which
  21737. provides the input for the Racket program. If the test program is
  21738. expected to fail type checking, then there should be an empty file of
  21739. the same name with extension \key{.tyerr}.
  21740. \paragraph{\code{compiler-tests}}
  21741. This function runs the compiler passes to generate x86 (a \key{.s}
  21742. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21743. It runs the machine code and checks that the output is $42$. The
  21744. parameters to the \code{compiler-tests} function are similar to those
  21745. of the \code{interp-tests} function, and they consist of
  21746. \begin{itemize}
  21747. \item a compiler name (a string),
  21748. \item a type checker,
  21749. \item description of the passes,
  21750. \item name of a test-family, and
  21751. \item a list of test numbers.
  21752. \end{itemize}
  21753. \paragraph{\code{compile-file}}
  21754. This function takes a description of the compiler passes (see the
  21755. comment for \key{interp-tests}) and returns a function that, given a
  21756. program file name (a string ending in \key{.rkt}), applies all the
  21757. passes and writes the output to a file whose name is the same as the
  21758. program file name with extension \key{.rkt} replaced by \key{.s}.
  21759. \paragraph{\code{read-program}}
  21760. This function takes a file path and parses that file (it must be a
  21761. Racket program) into an abstract syntax tree.
  21762. \paragraph{\code{parse-program}}
  21763. This function takes an S-expression representation of an abstract
  21764. syntax tree and converts it into the struct-based representation.
  21765. \paragraph{\code{assert}}
  21766. This function takes two parameters, a string (\code{msg}) and Boolean
  21767. (\code{bool}), and displays the message \key{msg} if the Boolean
  21768. \key{bool} is false.
  21769. \paragraph{\code{lookup}}
  21770. % remove discussion of lookup? -Jeremy
  21771. This function takes a key and an alist and returns the first value that is
  21772. associated with the given key, if there is one. If not, an error is
  21773. triggered. The alist may contain both immutable pairs (built with
  21774. \key{cons}) and mutable pairs (built with \key{mcons}).
  21775. %The \key{map2} function ...
  21776. \fi} %\racketEd
  21777. \section{x86 Instruction Set Quick Reference}
  21778. \label{sec:x86-quick-reference}
  21779. \index{subject}{x86}
  21780. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21781. do. We write $A \to B$ to mean that the value of $A$ is written into
  21782. location $B$. Address offsets are given in bytes. The instruction
  21783. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21784. registers (such as \code{\%rax}), or memory references (such as
  21785. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21786. reference per instruction. Other operands must be immediates or
  21787. registers.
  21788. \begin{table}[tbp]
  21789. \captionabove{Quick reference for the x86 instructions used in this book.}
  21790. \label{tab:x86-instr}
  21791. \centering
  21792. \begin{tabular}{l|l}
  21793. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21794. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21795. \texttt{negq} $A$ & $- A \to A$ \\
  21796. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21797. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21798. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21799. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21800. \texttt{retq} & Pops the return address and jumps to it. \\
  21801. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21802. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21803. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21804. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21805. be an immediate). \\
  21806. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21807. matches the condition code of the instruction; otherwise go to the
  21808. next instructions. The condition codes are \key{e} for \emph{equal},
  21809. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21810. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21811. \texttt{jl} $L$ & \\
  21812. \texttt{jle} $L$ & \\
  21813. \texttt{jg} $L$ & \\
  21814. \texttt{jge} $L$ & \\
  21815. \texttt{jmp} $L$ & Jump to label $L$. \\
  21816. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21817. \texttt{movzbq} $A$, $B$ &
  21818. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21819. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21820. and the extra bytes of $B$ are set to zero.} \\
  21821. & \\
  21822. & \\
  21823. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21824. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21825. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21826. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21827. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21828. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21829. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21830. description of the condition codes. $A$ must be a single byte register
  21831. (e.g., \texttt{al} or \texttt{cl}).} \\
  21832. \texttt{setl} $A$ & \\
  21833. \texttt{setle} $A$ & \\
  21834. \texttt{setg} $A$ & \\
  21835. \texttt{setge} $A$ &
  21836. \end{tabular}
  21837. \end{table}
  21838. \backmatter
  21839. \addtocontents{toc}{\vspace{11pt}}
  21840. \cleardoublepage % needed for right page number in TOC for References
  21841. %% \nocite{*} is a way to get all the entries in the .bib file to
  21842. %% print in the bibliography:
  21843. \nocite{*}\let\bibname\refname
  21844. \addcontentsline{toc}{fmbm}{\refname}
  21845. \printbibliography
  21846. %\printindex{authors}{Author Index}
  21847. \printindex{subject}{Index}
  21848. \end{document}
  21849. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21850. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21851. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21852. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21853. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21854. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21855. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21856. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21857. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21858. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21859. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21860. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21861. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21862. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21863. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21864. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21865. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21866. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21867. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21868. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21869. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21870. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21871. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21872. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21873. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21874. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21875. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21876. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21877. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21878. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21879. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21880. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21881. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21882. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21883. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21884. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21885. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21886. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21887. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21888. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21889. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21890. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21891. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21892. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21893. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21894. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21895. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21896. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21897. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21898. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21899. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21900. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21901. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21902. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21903. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21904. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21905. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21906. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21907. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21908. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21909. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21910. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21911. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21912. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21913. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21914. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21915. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21916. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21917. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21918. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21919. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21920. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21921. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21922. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21923. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21924. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21925. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21926. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21927. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21928. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21929. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21930. % LocalWords: pseudocode underapproximation underapproximations LALR
  21931. % LocalWords: semilattices overapproximate incrementing Earley docs
  21932. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21933. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21934. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21935. % LocalWords: LC partialevaluation pythonEd TOC TrappedError