book.tex 830 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841
  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. Title: Essentials of compilation : an incremental approach in Python / Jeremy G. Siek. \\
  148. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  149. bibliographical references and index. \\
  150. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  151. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  152. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  153. language) | Programming languages (Electronic computers) | Computer
  154. programming. \\
  155. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  156. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  157. LC record available at https://lccn.loc.gov/2022043053\\
  158. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  159. \ \\
  160. \fi}
  161. 10 9 8 7 6 5 4 3 2 1
  162. %% Jeremy G. Siek. Available for free viewing
  163. %% or personal downloading under the
  164. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  165. %% license.
  166. %% Copyright in this monograph has been licensed exclusively to The MIT
  167. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  168. %% version to the public in 2022. All inquiries regarding rights should
  169. %% be addressed to The MIT Press, Rights and Permissions Department.
  170. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  171. %% All rights reserved. No part of this book may be reproduced in any
  172. %% form by any electronic or mechanical means (including photocopying,
  173. %% recording, or information storage and retrieval) without permission in
  174. %% writing from the publisher.
  175. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  176. %% United States of America.
  177. %% Library of Congress Cataloging-in-Publication Data is available.
  178. %% ISBN:
  179. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  180. \end{copyrightpage}
  181. \dedication{This book is dedicated to Katie, my partner in everything,
  182. my children, who grew up during the writing of this book, and the
  183. programming language students at Indiana University, whose
  184. thoughtful questions made this a better book.}
  185. %% \begin{epigraphpage}
  186. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  187. %% \textit{Book Name if any}}
  188. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  189. %% \end{epigraphpage}
  190. \tableofcontents
  191. %\listoffigures
  192. %\listoftables
  193. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  194. \chapter*{Preface}
  195. \addcontentsline{toc}{fmbm}{Preface}
  196. There is a magical moment when a programmer presses the \emph{run}
  197. button and the software begins to execute. Somehow a program written
  198. in a high-level language is running on a computer that is capable only
  199. of shuffling bits. Here we reveal the wizardry that makes that moment
  200. possible. Beginning with the groundbreaking work of Backus and
  201. colleagues in the 1950s, computer scientists developed techniques for
  202. constructing programs called \emph{compilers} that automatically
  203. translate high-level programs into machine code.
  204. We take you on a journey through constructing your own compiler for a
  205. small but powerful language. Along the way we explain the essential
  206. concepts, algorithms, and data structures that underlie compilers. We
  207. develop your understanding of how programs are mapped onto computer
  208. hardware, which is helpful in reasoning about properties at the
  209. junction of hardware and software, such as execution time, software
  210. errors, and security vulnerabilities. For those interested in
  211. pursuing compiler construction as a career, our goal is to provide a
  212. stepping-stone to advanced topics such as just-in-time compilation,
  213. program analysis, and program optimization. For those interested in
  214. designing and implementing programming languages, we connect language
  215. design choices to their impact on the compiler and the generated code.
  216. A compiler is typically organized as a sequence of stages that
  217. progressively translate a program to the code that runs on
  218. hardware. We take this approach to the extreme by partitioning our
  219. compiler into a large number of \emph{nanopasses}, each of which
  220. performs a single task. This enables the testing of each pass in
  221. isolation and focuses our attention, making the compiler far easier to
  222. understand.
  223. The most familiar approach to describing compilers is to dedicate each
  224. chapter to one pass. The problem with that approach is that it
  225. obfuscates how language features motivate design choices in a
  226. compiler. We instead take an \emph{incremental} approach in which we
  227. build a complete compiler in each chapter, starting with a small input
  228. language that includes only arithmetic and variables. We add new
  229. language features in subsequent chapters, extending the compiler as
  230. necessary.
  231. Our choice of language features is designed to elicit fundamental
  232. concepts and algorithms used in compilers.
  233. \begin{itemize}
  234. \item We begin with integer arithmetic and local variables in
  235. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  236. the fundamental tools of compiler construction: \emph{abstract
  237. syntax trees} and \emph{recursive functions}.
  238. {\if\edition\pythonEd\pythonColor
  239. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  240. parser framework to create a parser for the language of integer
  241. arithmetic and local variables. We learn about the parsing
  242. algorithms inside Lark, including Earley and LALR(1).
  243. %
  244. \fi}
  245. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  246. \emph{graph coloring} to assign variables to machine registers.
  247. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  248. motivates an elegant recursive algorithm for translating them into
  249. conditional \code{goto} statements.
  250. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  251. variables}. This elicits the need for \emph{dataflow
  252. analysis} in the register allocator.
  253. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  254. \emph{garbage collection}.
  255. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  256. without lexical scoping, similar to functions in the C programming
  257. language~\citep{Kernighan:1988nx}. The reader learns about the
  258. procedure call stack and \emph{calling conventions} and how they interact
  259. with register allocation and garbage collection. The chapter also
  260. describes how to generate efficient tail calls.
  261. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  262. scoping, that is, \emph{lambda} expressions. The reader learns about
  263. \emph{closure conversion}, in which lambdas are translated into a
  264. combination of functions and tuples.
  265. % Chapter about classes and objects?
  266. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  267. point the input languages are statically typed. The reader extends
  268. the statically typed language with an \code{Any} type that serves
  269. as a target for compiling the dynamically typed language.
  270. %% {\if\edition\pythonEd\pythonColor
  271. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  272. %% \emph{classes}.
  273. %% \fi}
  274. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  275. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  276. in which different regions of a program may be static or dynamically
  277. typed. The reader implements runtime support for \emph{proxies} that
  278. allow values to safely move between regions.
  279. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  280. leveraging the \code{Any} type and type casts developed in chapters
  281. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  282. \end{itemize}
  283. There are many language features that we do not include. Our choices
  284. balance the incidental complexity of a feature versus the fundamental
  285. concepts that it exposes. For example, we include tuples and not
  286. records because although they both elicit the study of heap allocation and
  287. garbage collection, records come with more incidental complexity.
  288. Since 2009, drafts of this book have served as the textbook for
  289. sixteen-week compiler courses for upper-level undergraduates and
  290. first-year graduate students at the University of Colorado and Indiana
  291. University.
  292. %
  293. Students come into the course having learned the basics of
  294. programming, data structures and algorithms, and discrete
  295. mathematics.
  296. %
  297. At the beginning of the course, students form groups of two to four
  298. people. The groups complete approximately one chapter every two
  299. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  300. according to the students interests while respecting the dependencies
  301. between chapters shown in
  302. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  303. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  304. implementation of efficient tail calls.
  305. %
  306. The last two weeks of the course involve a final project in which
  307. students design and implement a compiler extension of their choosing.
  308. The last few chapters can be used in support of these projects. Many
  309. chapters include a challenge problem that we assign to the graduate
  310. students.
  311. For compiler courses at universities on the quarter system
  312. (about ten weeks in length), we recommend completing the course
  313. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  314. some scaffolding code to the students for each compiler pass.
  315. %
  316. The course can be adapted to emphasize functional languages by
  317. skipping chapter~\ref{ch:Lwhile} (loops) and including
  318. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  319. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  320. %
  321. %% \python{A course that emphasizes object-oriented languages would
  322. %% include Chapter~\ref{ch:Lobject}.}
  323. This book has been used in compiler courses at California Polytechnic
  324. State University, Portland State University, Rose–Hulman Institute of
  325. Technology, University of Freiburg, University of Massachusetts
  326. Lowell, and the University of Vermont.
  327. \begin{figure}[tp]
  328. \begin{tcolorbox}[colback=white]
  329. {\if\edition\racketEd
  330. \begin{tikzpicture}[baseline=(current bounding box.center)]
  331. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  332. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  333. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  334. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  335. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  336. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  337. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  338. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  339. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  340. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  341. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  342. \path[->] (C1) edge [above] node {} (C2);
  343. \path[->] (C2) edge [above] node {} (C3);
  344. \path[->] (C3) edge [above] node {} (C4);
  345. \path[->] (C4) edge [above] node {} (C5);
  346. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  347. \path[->] (C5) edge [above] node {} (C7);
  348. \path[->] (C6) edge [above] node {} (C7);
  349. \path[->] (C4) edge [above] node {} (C8);
  350. \path[->] (C4) edge [above] node {} (C9);
  351. \path[->] (C7) edge [above] node {} (C10);
  352. \path[->] (C8) edge [above] node {} (C10);
  353. \path[->] (C10) edge [above] node {} (C11);
  354. \end{tikzpicture}
  355. \fi}
  356. {\if\edition\pythonEd\pythonColor
  357. \begin{tikzpicture}[baseline=(current bounding box.center)]
  358. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  359. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  360. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  361. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  362. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  363. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  364. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  365. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  366. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  367. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  368. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  369. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  370. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  371. \path[->] (Prelim) edge [above] node {} (Var);
  372. \path[->] (Var) edge [above] node {} (Reg);
  373. \path[->] (Var) edge [above] node {} (Parse);
  374. \path[->] (Reg) edge [above] node {} (Cond);
  375. \path[->] (Cond) edge [above] node {} (Tuple);
  376. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  377. \path[->] (Cond) edge [above] node {} (Fun);
  378. \path[->] (Tuple) edge [above] node {} (Lam);
  379. \path[->] (Fun) edge [above] node {} (Lam);
  380. \path[->] (Cond) edge [above] node {} (Dyn);
  381. \path[->] (Cond) edge [above] node {} (Loop);
  382. \path[->] (Lam) edge [above] node {} (Gradual);
  383. \path[->] (Dyn) edge [above] node {} (Gradual);
  384. % \path[->] (Dyn) edge [above] node {} (CO);
  385. \path[->] (Gradual) edge [above] node {} (Generic);
  386. \end{tikzpicture}
  387. \fi}
  388. \end{tcolorbox}
  389. \caption{Diagram of chapter dependencies.}
  390. \label{fig:chapter-dependences}
  391. \end{figure}
  392. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  393. the implementation of the compiler and for the input language, so the
  394. reader should be proficient with Racket or Scheme. There are many
  395. excellent resources for learning Scheme and
  396. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  397. %
  398. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  399. both for the implementation of the compiler and for the input language, so the
  400. reader should be proficient with Python. There are many
  401. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  402. %
  403. The support code for this book is in the GitHub repository at
  404. the following location:
  405. \begin{center}\small\texttt
  406. https://github.com/IUCompilerCourse/
  407. \end{center}
  408. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  409. is helpful but not necessary for the reader to have taken a computer
  410. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  411. assembly language that are needed in the compiler.
  412. %
  413. We follow the System V calling
  414. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  415. that we generate works with the runtime system (written in C) when it
  416. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  417. operating systems on Intel hardware.
  418. %
  419. On the Windows operating system, \code{gcc} uses the Microsoft x64
  420. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  421. assembly code that we generate does \emph{not} work with the runtime
  422. system on Windows. One workaround is to use a virtual machine with
  423. Linux as the guest operating system.
  424. \section*{Acknowledgments}
  425. The tradition of compiler construction at Indiana University goes back
  426. to research and courses on programming languages by Daniel Friedman in
  427. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  428. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  429. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  430. the compiler course and continued the development of Chez Scheme.
  431. %
  432. The compiler course evolved to incorporate novel pedagogical ideas
  433. while also including elements of real-world compilers. One of
  434. Friedman's ideas was to split the compiler into many small
  435. passes. Another idea, called ``the game,'' was to test the code
  436. generated by each pass using interpreters.
  437. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  438. developed infrastructure to support this approach and evolved the
  439. course to use even smaller
  440. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  441. design decisions in this book are inspired by the assignment
  442. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  443. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  444. organization of the course made it difficult for students to
  445. understand the rationale for the compiler design. Ghuloum proposed the
  446. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  447. based.
  448. I thank the many students who served as teaching assistants for the
  449. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  450. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  451. garbage collector and x86 interpreter, Michael Vollmer for work on
  452. efficient tail calls, and Michael Vitousek for help with the first
  453. offering of the incremental compiler course at IU.
  454. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  455. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  456. Michael Wollowski for teaching courses based on drafts of this book
  457. and for their feedback. I thank the National Science Foundation for
  458. the grants that helped to support this work: Grant Numbers 1518844,
  459. 1763922, and 1814460.
  460. I thank Ronald Garcia for helping me survive Dybvig's compiler
  461. course in the early 2000s and especially for finding the bug that
  462. sent our garbage collector on a wild goose chase!
  463. \mbox{}\\
  464. \noindent Jeremy G. Siek \\
  465. Bloomington, Indiana
  466. \mainmatter
  467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  468. \chapter{Preliminaries}
  469. \label{ch:trees-recur}
  470. \setcounter{footnote}{0}
  471. In this chapter we introduce the basic tools needed to implement a
  472. compiler. Programs are typically input by a programmer as text, that
  473. is, a sequence of characters. The program-as-text representation is
  474. called \emph{concrete syntax}. We use concrete syntax to concisely
  475. write down and talk about programs. Inside the compiler, we use
  476. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  477. that efficiently supports the operations that the compiler needs to
  478. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  479. syntax}\index{subject}{abstract syntax
  480. tree}\index{subject}{AST}\index{subject}{program}
  481. The process of translating concrete syntax to abstract syntax is
  482. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  483. chapter~\ref{ch:parsing}}.
  484. \racket{This book does not cover the theory and implementation of parsing.
  485. We refer the readers interested in parsing to the thorough treatment
  486. of parsing by \citet{Aho:2006wb}.}%
  487. %
  488. \racket{A parser is provided in the support code for translating from
  489. concrete to abstract syntax.}%
  490. %
  491. \python{For now we use the \code{parse} function in Python's
  492. \code{ast} module to translate from concrete to abstract syntax.}
  493. ASTs can be represented inside the compiler in many different ways,
  494. depending on the programming language used to write the compiler.
  495. %
  496. \racket{We use Racket's
  497. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  498. feature to represent ASTs (section~\ref{sec:ast}).}
  499. %
  500. \python{We use Python classes and objects to represent ASTs, especially the
  501. classes defined in the standard \code{ast} module for the Python
  502. source language.}
  503. %
  504. We use grammars to define the abstract syntax of programming languages
  505. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  506. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  507. recursive functions to construct and deconstruct ASTs
  508. (section~\ref{sec:recursion}). This chapter provides a brief
  509. introduction to these components.
  510. \racket{\index{subject}{struct}}
  511. \python{\index{subject}{class}\index{subject}{object}}
  512. \section{Abstract Syntax Trees}
  513. \label{sec:ast}
  514. Compilers use abstract syntax trees to represent programs because they
  515. often need to ask questions such as, for a given part of a program,
  516. what kind of language feature is it? What are its subparts? Consider
  517. the program on the left and the diagram of its AST on the
  518. right~\eqref{eq:arith-prog}. This program is an addition operation
  519. that has two subparts, a \racket{read}\python{input} operation and a
  520. negation. The negation has another subpart, the integer constant
  521. \code{8}. By using a tree to represent the program, we can easily
  522. follow the links to go from one part of a program to its subparts.
  523. \begin{center}
  524. \begin{minipage}{0.4\textwidth}
  525. {\if\edition\racketEd
  526. \begin{lstlisting}
  527. (+ (read) (- 8))
  528. \end{lstlisting}
  529. \fi}
  530. {\if\edition\pythonEd\pythonColor
  531. \begin{lstlisting}
  532. input_int() + -8
  533. \end{lstlisting}
  534. \fi}
  535. \end{minipage}
  536. \begin{minipage}{0.4\textwidth}
  537. \begin{equation}
  538. \begin{tikzpicture}
  539. \node[draw] (plus) at (0 , 0) {\key{+}};
  540. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  541. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  542. \node[draw] (8) at (1 , -2) {\key{8}};
  543. \draw[->] (plus) to (read);
  544. \draw[->] (plus) to (minus);
  545. \draw[->] (minus) to (8);
  546. \end{tikzpicture}
  547. \label{eq:arith-prog}
  548. \end{equation}
  549. \end{minipage}
  550. \end{center}
  551. We use the standard terminology for trees to describe ASTs: each
  552. rectangle above is called a \emph{node}. The arrows connect a node to its
  553. \emph{children}, which are also nodes. The top-most node is the
  554. \emph{root}. Every node except for the root has a \emph{parent} (the
  555. node of which it is the child). If a node has no children, it is a
  556. \emph{leaf} node; otherwise it is an \emph{internal} node.
  557. \index{subject}{node}
  558. \index{subject}{children}
  559. \index{subject}{root}
  560. \index{subject}{parent}
  561. \index{subject}{leaf}
  562. \index{subject}{internal node}
  563. %% Recall that an \emph{symbolic expression} (S-expression) is either
  564. %% \begin{enumerate}
  565. %% \item an atom, or
  566. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  567. %% where $e_1$ and $e_2$ are each an S-expression.
  568. %% \end{enumerate}
  569. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  570. %% null value \code{'()}, etc. We can create an S-expression in Racket
  571. %% simply by writing a backquote (called a quasi-quote in Racket)
  572. %% followed by the textual representation of the S-expression. It is
  573. %% quite common to use S-expressions to represent a list, such as $a, b
  574. %% ,c$ in the following way:
  575. %% \begin{lstlisting}
  576. %% `(a . (b . (c . ())))
  577. %% \end{lstlisting}
  578. %% Each element of the list is in the first slot of a pair, and the
  579. %% second slot is either the rest of the list or the null value, to mark
  580. %% the end of the list. Such lists are so common that Racket provides
  581. %% special notation for them that removes the need for the periods
  582. %% and so many parenthesis:
  583. %% \begin{lstlisting}
  584. %% `(a b c)
  585. %% \end{lstlisting}
  586. %% The following expression creates an S-expression that represents AST
  587. %% \eqref{eq:arith-prog}.
  588. %% \begin{lstlisting}
  589. %% `(+ (read) (- 8))
  590. %% \end{lstlisting}
  591. %% When using S-expressions to represent ASTs, the convention is to
  592. %% represent each AST node as a list and to put the operation symbol at
  593. %% the front of the list. The rest of the list contains the children. So
  594. %% in the above case, the root AST node has operation \code{`+} and its
  595. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  596. %% diagram \eqref{eq:arith-prog}.
  597. %% To build larger S-expressions one often needs to splice together
  598. %% several smaller S-expressions. Racket provides the comma operator to
  599. %% splice an S-expression into a larger one. For example, instead of
  600. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  601. %% we could have first created an S-expression for AST
  602. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  603. %% S-expression.
  604. %% \begin{lstlisting}
  605. %% (define ast1.4 `(- 8))
  606. %% (define ast1_1 `(+ (read) ,ast1.4))
  607. %% \end{lstlisting}
  608. %% In general, the Racket expression that follows the comma (splice)
  609. %% can be any expression that produces an S-expression.
  610. {\if\edition\racketEd
  611. We define a Racket \code{struct} for each kind of node. For this
  612. chapter we require just two kinds of nodes: one for integer constants
  613. (aka literals\index{subject}{literals})
  614. and one for primitive operations. The following is the \code{struct}
  615. definition for integer constants.\footnote{All the AST structures are
  616. defined in the file \code{utilities.rkt} in the support code.}
  617. \begin{lstlisting}
  618. (struct Int (value))
  619. \end{lstlisting}
  620. An integer node contains just one thing: the integer value.
  621. We establish the convention that \code{struct} names, such
  622. as \code{Int}, are capitalized.
  623. To create an AST node for the integer $8$, we write \INT{8}.
  624. \begin{lstlisting}
  625. (define eight (Int 8))
  626. \end{lstlisting}
  627. We say that the value created by \INT{8} is an
  628. \emph{instance} of the
  629. \code{Int} structure.
  630. The following is the \code{struct} definition for primitive operations.
  631. \begin{lstlisting}
  632. (struct Prim (op args))
  633. \end{lstlisting}
  634. A primitive operation node includes an operator symbol \code{op} and a
  635. list of child arguments called \code{args}. For example, to create an
  636. AST that negates the number $8$, we write the following.
  637. \begin{lstlisting}
  638. (define neg-eight (Prim '- (list eight)))
  639. \end{lstlisting}
  640. Primitive operations may have zero or more children. The \code{read}
  641. operator has zero:
  642. \begin{lstlisting}
  643. (define rd (Prim 'read '()))
  644. \end{lstlisting}
  645. The addition operator has two children:
  646. \begin{lstlisting}
  647. (define ast1_1 (Prim '+ (list rd neg-eight)))
  648. \end{lstlisting}
  649. We have made a design choice regarding the \code{Prim} structure.
  650. Instead of using one structure for many different operations
  651. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  652. structure for each operation, as follows:
  653. \begin{lstlisting}
  654. (struct Read ())
  655. (struct Add (left right))
  656. (struct Neg (value))
  657. \end{lstlisting}
  658. The reason that we choose to use just one structure is that many parts
  659. of the compiler can use the same code for the different primitive
  660. operators, so we might as well just write that code once by using a
  661. single structure.
  662. %
  663. \fi}
  664. {\if\edition\pythonEd\pythonColor
  665. We use a Python \code{class} for each kind of node.
  666. The following is the class definition for
  667. constants (aka literals\index{subject}{literals})
  668. from the Python \code{ast} module.
  669. \begin{lstlisting}
  670. class Constant:
  671. def __init__(self, value):
  672. self.value = value
  673. \end{lstlisting}
  674. An integer constant node includes just one thing: the integer value.
  675. To create an AST node for the integer $8$, we write \INT{8}.
  676. \begin{lstlisting}
  677. eight = Constant(8)
  678. \end{lstlisting}
  679. We say that the value created by \INT{8} is an
  680. \emph{instance} of the \code{Constant} class.
  681. The following is the class definition for unary operators.
  682. \begin{lstlisting}
  683. class UnaryOp:
  684. def __init__(self, op, operand):
  685. self.op = op
  686. self.operand = operand
  687. \end{lstlisting}
  688. The specific operation is specified by the \code{op} parameter. For
  689. example, the class \code{USub} is for unary subtraction.
  690. (More unary operators are introduced in later chapters.) To create an AST that
  691. negates the number $8$, we write the following.
  692. \begin{lstlisting}
  693. neg_eight = UnaryOp(USub(), eight)
  694. \end{lstlisting}
  695. The call to the \code{input\_int} function is represented by the
  696. \code{Call} and \code{Name} classes.
  697. \begin{lstlisting}
  698. class Call:
  699. def __init__(self, func, args):
  700. self.func = func
  701. self.args = args
  702. class Name:
  703. def __init__(self, id):
  704. self.id = id
  705. \end{lstlisting}
  706. To create an AST node that calls \code{input\_int}, we write
  707. \begin{lstlisting}
  708. read = Call(Name('input_int'), [])
  709. \end{lstlisting}
  710. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  711. the \code{BinOp} class for binary operators.
  712. \begin{lstlisting}
  713. class BinOp:
  714. def __init__(self, left, op, right):
  715. self.op = op
  716. self.left = left
  717. self.right = right
  718. \end{lstlisting}
  719. Similar to \code{UnaryOp}, the specific operation is specified by the
  720. \code{op} parameter, which for now is just an instance of the
  721. \code{Add} class. So to create the AST
  722. node that adds negative eight to some user input, we write the following.
  723. \begin{lstlisting}
  724. ast1_1 = BinOp(read, Add(), neg_eight)
  725. \end{lstlisting}
  726. \fi}
  727. To compile a program such as \eqref{eq:arith-prog}, we need to know
  728. that the operation associated with the root node is addition and we
  729. need to be able to access its two
  730. children. \racket{Racket}\python{Python} provides pattern matching to
  731. support these kinds of queries, as we see in
  732. section~\ref{sec:pattern-matching}.
  733. We often write down the concrete syntax of a program even when we
  734. actually have in mind the AST, because the concrete syntax is more
  735. concise. We recommend that you always think of programs as abstract
  736. syntax trees.
  737. \section{Grammars}
  738. \label{sec:grammar}
  739. \index{subject}{integer}
  740. %\index{subject}{constant}
  741. A programming language can be thought of as a \emph{set} of programs.
  742. The set is infinite (that is, one can always create larger programs),
  743. so one cannot simply describe a language by listing all the
  744. programs in the language. Instead we write down a set of rules, a
  745. \emph{context-free grammar}, for building programs. Grammars are often used to
  746. define the concrete syntax of a language, but they can also be used to
  747. describe the abstract syntax. We write our rules in a variant of
  748. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  749. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  750. we describe a small language, named \LangInt{}, that consists of
  751. integers and arithmetic operations.\index{subject}{grammar}
  752. \index{subject}{context-free grammar}
  753. The first grammar rule for the abstract syntax of \LangInt{} says that an
  754. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  755. \begin{equation}
  756. \Exp ::= \INT{\Int} \label{eq:arith-int}
  757. \end{equation}
  758. %
  759. Each rule has a left-hand side and a right-hand side.
  760. If you have an AST node that matches the
  761. right-hand side, then you can categorize it according to the
  762. left-hand side.
  763. %
  764. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  765. are \emph{terminal} symbols and must literally appear in the program for the
  766. rule to be applicable.\index{subject}{terminal}
  767. %
  768. Our grammars do not mention \emph{white space}, that is, delimiter
  769. characters like spaces, tabs, and new lines. White space may be
  770. inserted between symbols for disambiguation and to improve
  771. readability. \index{subject}{white space}
  772. %
  773. A name such as $\Exp$ that is defined by the grammar rules is a
  774. \emph{nonterminal}. \index{subject}{nonterminal}
  775. %
  776. The name $\Int$ is also a nonterminal, but instead of defining it with
  777. a grammar rule, we define it with the following explanation. An
  778. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  779. $-$ (for negative integers), such that the sequence of decimals
  780. %
  781. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  782. enables the representation of integers using 63 bits, which simplifies
  783. several aspects of compilation.
  784. %
  785. Thus, these integers correspond to the Racket \texttt{fixnum}
  786. datatype on a 64-bit machine.}
  787. %
  788. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  789. enables the representation of integers using 64 bits, which simplifies
  790. several aspects of compilation. In contrast, integers in Python have
  791. unlimited precision, but the techniques needed to handle unlimited
  792. precision fall outside the scope of this book.}
  793. The second grammar rule is the \READOP{} operation, which receives an
  794. input integer from the user of the program.
  795. \begin{equation}
  796. \Exp ::= \READ{} \label{eq:arith-read}
  797. \end{equation}
  798. The third rule categorizes the negation of an $\Exp$ node as an
  799. $\Exp$.
  800. \begin{equation}
  801. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  802. \end{equation}
  803. We can apply these rules to categorize the ASTs that are in the
  804. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  805. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  806. following AST is an $\Exp$.
  807. \begin{center}
  808. \begin{minipage}{0.5\textwidth}
  809. \NEG{\INT{\code{8}}}
  810. \end{minipage}
  811. \begin{minipage}{0.25\textwidth}
  812. \begin{equation}
  813. \begin{tikzpicture}
  814. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  815. \node[draw, circle] (8) at (0, -1.2) {$8$};
  816. \draw[->] (minus) to (8);
  817. \end{tikzpicture}
  818. \label{eq:arith-neg8}
  819. \end{equation}
  820. \end{minipage}
  821. \end{center}
  822. The next two grammar rules are for addition and subtraction expressions:
  823. \begin{align}
  824. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  825. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  826. \end{align}
  827. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  828. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  829. \eqref{eq:arith-read}, and we have already categorized
  830. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  831. to show that
  832. \[
  833. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  834. \]
  835. is an $\Exp$ in the \LangInt{} language.
  836. If you have an AST for which these rules do not apply, then the
  837. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  838. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  839. because there is no rule for the \key{*} operator. Whenever we
  840. define a language with a grammar, the language includes only those
  841. programs that are justified by the grammar rules.
  842. {\if\edition\pythonEd\pythonColor
  843. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  844. There is a statement for printing the value of an expression
  845. \[
  846. \Stmt{} ::= \PRINT{\Exp}
  847. \]
  848. and a statement that evaluates an expression but ignores the result.
  849. \[
  850. \Stmt{} ::= \EXPR{\Exp}
  851. \]
  852. \fi}
  853. {\if\edition\racketEd
  854. The last grammar rule for \LangInt{} states that there is a
  855. \code{Program} node to mark the top of the whole program:
  856. \[
  857. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  858. \]
  859. The \code{Program} structure is defined as follows:
  860. \begin{lstlisting}
  861. (struct Program (info body))
  862. \end{lstlisting}
  863. where \code{body} is an expression. In further chapters, the \code{info}
  864. part is used to store auxiliary information, but for now it is
  865. just the empty list.
  866. \fi}
  867. {\if\edition\pythonEd\pythonColor
  868. The last grammar rule for \LangInt{} states that there is a
  869. \code{Module} node to mark the top of the whole program:
  870. \[
  871. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  872. \]
  873. The asterisk $*$ indicates a list of the preceding grammar item, in
  874. this case a list of statements.
  875. %
  876. The \code{Module} class is defined as follows:
  877. \begin{lstlisting}
  878. class Module:
  879. def __init__(self, body):
  880. self.body = body
  881. \end{lstlisting}
  882. where \code{body} is a list of statements.
  883. \fi}
  884. It is common to have many grammar rules with the same left-hand side
  885. but different right-hand sides, such as the rules for $\Exp$ in the
  886. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  887. combine several right-hand sides into a single rule.
  888. The concrete syntax for \LangInt{} is shown in
  889. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  890. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  891. %
  892. \racket{The \code{read-program} function provided in
  893. \code{utilities.rkt} of the support code reads a program from a file
  894. (the sequence of characters in the concrete syntax of Racket) and
  895. parses it into an abstract syntax tree. Refer to the description of
  896. \code{read-program} in appendix~\ref{appendix:utilities} for more
  897. details.}
  898. %
  899. \python{We recommend using the \code{parse} function in Python's
  900. \code{ast} module to convert the concrete syntax into an abstract
  901. syntax tree.}
  902. \newcommand{\LintGrammarRacket}{
  903. \begin{array}{rcl}
  904. \Type &::=& \key{Integer} \\
  905. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  906. \MID \CSUB{\Exp}{\Exp}
  907. \end{array}
  908. }
  909. \newcommand{\LintASTRacket}{
  910. \begin{array}{rcl}
  911. \Type &::=& \key{Integer} \\
  912. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  913. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  914. \end{array}
  915. }
  916. \newcommand{\LintGrammarPython}{
  917. \begin{array}{rcl}
  918. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  919. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  920. \end{array}
  921. }
  922. \newcommand{\LintASTPython}{
  923. \begin{array}{rcl}
  924. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  925. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  926. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  927. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  928. \end{array}
  929. }
  930. \begin{figure}[tp]
  931. \begin{tcolorbox}[colback=white]
  932. {\if\edition\racketEd
  933. \[
  934. \begin{array}{l}
  935. \LintGrammarRacket \\
  936. \begin{array}{rcl}
  937. \LangInt{} &::=& \Exp
  938. \end{array}
  939. \end{array}
  940. \]
  941. \fi}
  942. {\if\edition\pythonEd\pythonColor
  943. \[
  944. \begin{array}{l}
  945. \LintGrammarPython \\
  946. \begin{array}{rcl}
  947. \LangInt{} &::=& \Stmt^{*}
  948. \end{array}
  949. \end{array}
  950. \]
  951. \fi}
  952. \end{tcolorbox}
  953. \caption{The concrete syntax of \LangInt{}.}
  954. \label{fig:r0-concrete-syntax}
  955. \end{figure}
  956. \begin{figure}[tp]
  957. \begin{tcolorbox}[colback=white]
  958. {\if\edition\racketEd
  959. \[
  960. \begin{array}{l}
  961. \LintASTRacket{} \\
  962. \begin{array}{rcl}
  963. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  964. \end{array}
  965. \end{array}
  966. \]
  967. \fi}
  968. {\if\edition\pythonEd\pythonColor
  969. \[
  970. \begin{array}{l}
  971. \LintASTPython\\
  972. \begin{array}{rcl}
  973. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  974. \end{array}
  975. \end{array}
  976. \]
  977. \fi}
  978. \end{tcolorbox}
  979. \python{
  980. \index{subject}{Constant@\texttt{Constant}}
  981. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  982. \index{subject}{USub@\texttt{USub}}
  983. \index{subject}{inputint@\texttt{input\_int}}
  984. \index{subject}{Call@\texttt{Call}}
  985. \index{subject}{Name@\texttt{Name}}
  986. \index{subject}{BinOp@\texttt{BinOp}}
  987. \index{subject}{Add@\texttt{Add}}
  988. \index{subject}{Sub@\texttt{Sub}}
  989. \index{subject}{print@\texttt{print}}
  990. \index{subject}{Expr@\texttt{Expr}}
  991. \index{subject}{Module@\texttt{Module}}
  992. }
  993. \caption{The abstract syntax of \LangInt{}.}
  994. \label{fig:r0-syntax}
  995. \end{figure}
  996. \section{Pattern Matching}
  997. \label{sec:pattern-matching}
  998. As mentioned in section~\ref{sec:ast}, compilers often need to access
  999. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  1000. provides the \texttt{match} feature to access the parts of a value.
  1001. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  1002. \begin{center}
  1003. \begin{minipage}{1.0\textwidth}
  1004. {\if\edition\racketEd
  1005. \begin{lstlisting}
  1006. (match ast1_1
  1007. [(Prim op (list child1 child2))
  1008. (print op)])
  1009. \end{lstlisting}
  1010. \fi}
  1011. {\if\edition\pythonEd\pythonColor
  1012. \begin{lstlisting}
  1013. match ast1_1:
  1014. case BinOp(child1, op, child2):
  1015. print(op)
  1016. \end{lstlisting}
  1017. \fi}
  1018. \end{minipage}
  1019. \end{center}
  1020. {\if\edition\racketEd
  1021. %
  1022. In this example, the \texttt{match} form checks whether the AST
  1023. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1024. three pattern variables \texttt{op}, \texttt{child1}, and
  1025. \texttt{child2}. In general, a match clause consists of a
  1026. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1027. recursively defined to be a pattern variable, a structure name
  1028. followed by a pattern for each of the structure's arguments, or an
  1029. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1030. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1031. and chapter 9 of The Racket
  1032. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1033. for complete descriptions of \code{match}.)
  1034. %
  1035. The body of a match clause may contain arbitrary Racket code. The
  1036. pattern variables can be used in the scope of the body, such as
  1037. \code{op} in \code{(print op)}.
  1038. %
  1039. \fi}
  1040. %
  1041. %
  1042. {\if\edition\pythonEd\pythonColor
  1043. %
  1044. In the example above, the \texttt{match} form checks whether the AST
  1045. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1046. three pattern variables (\texttt{child1}, \texttt{op}, and
  1047. \texttt{child2}). In general, each \code{case} consists of a
  1048. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1049. recursively defined to be one of the following: a pattern variable, a
  1050. class name followed by a pattern for each of its constructor's
  1051. arguments, or other literals\index{subject}{literals} such as strings
  1052. or lists.
  1053. %
  1054. The body of each \code{case} may contain arbitrary Python code. The
  1055. pattern variables can be used in the body, such as \code{op} in
  1056. \code{print(op)}.
  1057. %
  1058. \fi}
  1059. A \code{match} form may contain several clauses, as in the following
  1060. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1061. the AST. The \code{match} proceeds through the clauses in order,
  1062. checking whether the pattern can match the input AST. The body of the
  1063. first clause that matches is executed. The output of \code{leaf} for
  1064. several ASTs is shown on the right side of the following:
  1065. \begin{center}
  1066. \begin{minipage}{0.6\textwidth}
  1067. {\if\edition\racketEd
  1068. \begin{lstlisting}
  1069. (define (leaf arith)
  1070. (match arith
  1071. [(Int n) #t]
  1072. [(Prim 'read '()) #t]
  1073. [(Prim '- (list e1)) #f]
  1074. [(Prim '+ (list e1 e2)) #f]
  1075. [(Prim '- (list e1 e2)) #f]))
  1076. (leaf (Prim 'read '()))
  1077. (leaf (Prim '- (list (Int 8))))
  1078. (leaf (Int 8))
  1079. \end{lstlisting}
  1080. \fi}
  1081. {\if\edition\pythonEd\pythonColor
  1082. \begin{lstlisting}
  1083. def leaf(arith):
  1084. match arith:
  1085. case Constant(n):
  1086. return True
  1087. case Call(Name('input_int'), []):
  1088. return True
  1089. case UnaryOp(USub(), e1):
  1090. return False
  1091. case BinOp(e1, Add(), e2):
  1092. return False
  1093. case BinOp(e1, Sub(), e2):
  1094. return False
  1095. print(leaf(Call(Name('input_int'), [])))
  1096. print(leaf(UnaryOp(USub(), eight)))
  1097. print(leaf(Constant(8)))
  1098. \end{lstlisting}
  1099. \fi}
  1100. \end{minipage}
  1101. \vrule
  1102. \begin{minipage}{0.25\textwidth}
  1103. {\if\edition\racketEd
  1104. \begin{lstlisting}
  1105. #t
  1106. #f
  1107. #t
  1108. \end{lstlisting}
  1109. \fi}
  1110. {\if\edition\pythonEd\pythonColor
  1111. \begin{lstlisting}
  1112. True
  1113. False
  1114. True
  1115. \end{lstlisting}
  1116. \fi}
  1117. \end{minipage}
  1118. \index{subject}{True@\TRUE{}}
  1119. \index{subject}{False@\FALSE{}}
  1120. \end{center}
  1121. When constructing a \code{match} expression, we refer to the grammar
  1122. definition to identify which nonterminal we are expecting to match
  1123. against, and then we make sure that (1) we have one
  1124. \racket{clause}\python{case} for each alternative of that nonterminal
  1125. and (2) the pattern in each \racket{clause}\python{case}
  1126. corresponds to the corresponding right-hand side of a grammar
  1127. rule. For the \code{match} in the \code{leaf} function, we refer to
  1128. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1129. nonterminal has five alternatives, so the \code{match} has five
  1130. \racket{clauses}\python{cases}. The pattern in each
  1131. \racket{clause}\python{case} corresponds to the right-hand side of a
  1132. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1133. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1134. translating from grammars to patterns, replace nonterminals such as
  1135. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1136. \code{e2}).
  1137. \section{Recursive Functions}
  1138. \label{sec:recursion}
  1139. \index{subject}{recursive function}
  1140. Programs are inherently recursive. For example, an expression is often
  1141. made of smaller expressions. Thus, the natural way to process an
  1142. entire program is to use a recursive function. As a first example of
  1143. such a recursive function, we define the function \code{is\_exp} as
  1144. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1145. value and determine whether or not it is an expression in \LangInt{}.
  1146. %
  1147. We say that a function is defined by \emph{structural recursion} if
  1148. it is defined using a sequence of match \racket{clauses}\python{cases}
  1149. that correspond to a grammar and the body of each
  1150. \racket{clause}\python{case} makes a recursive call on each child
  1151. node.\footnote{This principle of structuring code according to the
  1152. data definition is advocated in the book \emph{How to Design
  1153. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1154. second function, named \code{is\_stmt}, that recognizes whether a value
  1155. is a \LangInt{} statement.} \python{Finally, }
  1156. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1157. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1158. In general, we can write one recursive function to handle each
  1159. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1160. two examples at the bottom of the figure, the first is in
  1161. \LangInt{} and the second is not.
  1162. \begin{figure}[tp]
  1163. \begin{tcolorbox}[colback=white]
  1164. {\if\edition\racketEd
  1165. \begin{lstlisting}
  1166. (define (is_exp ast)
  1167. (match ast
  1168. [(Int n) #t]
  1169. [(Prim 'read '()) #t]
  1170. [(Prim '- (list e)) (is_exp e)]
  1171. [(Prim '+ (list e1 e2))
  1172. (and (is_exp e1) (is_exp e2))]
  1173. [(Prim '- (list e1 e2))
  1174. (and (is_exp e1) (is_exp e2))]
  1175. [else #f]))
  1176. (define (is_Lint ast)
  1177. (match ast
  1178. [(Program '() e) (is_exp e)]
  1179. [else #f]))
  1180. (is_Lint (Program '() ast1_1)
  1181. (is_Lint (Program '()
  1182. (Prim '* (list (Prim 'read '())
  1183. (Prim '+ (list (Int 8)))))))
  1184. \end{lstlisting}
  1185. \fi}
  1186. {\if\edition\pythonEd\pythonColor
  1187. \begin{lstlisting}
  1188. def is_exp(e):
  1189. match e:
  1190. case Constant(n):
  1191. return True
  1192. case Call(Name('input_int'), []):
  1193. return True
  1194. case UnaryOp(USub(), e1):
  1195. return is_exp(e1)
  1196. case BinOp(e1, Add(), e2):
  1197. return is_exp(e1) and is_exp(e2)
  1198. case BinOp(e1, Sub(), e2):
  1199. return is_exp(e1) and is_exp(e2)
  1200. case _:
  1201. return False
  1202. def is_stmt(s):
  1203. match s:
  1204. case Expr(Call(Name('print'), [e])):
  1205. return is_exp(e)
  1206. case Expr(e):
  1207. return is_exp(e)
  1208. case _:
  1209. return False
  1210. def is_Lint(p):
  1211. match p:
  1212. case Module(body):
  1213. return all([is_stmt(s) for s in body])
  1214. case _:
  1215. return False
  1216. print(is_Lint(Module([Expr(ast1_1)])))
  1217. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1218. UnaryOp(Add(), Constant(8))))])))
  1219. \end{lstlisting}
  1220. \fi}
  1221. \end{tcolorbox}
  1222. \caption{Example of recursive functions for \LangInt{}. These functions
  1223. recognize whether an AST is in \LangInt{}.}
  1224. \label{fig:exp-predicate}
  1225. \end{figure}
  1226. %% You may be tempted to merge the two functions into one, like this:
  1227. %% \begin{center}
  1228. %% \begin{minipage}{0.5\textwidth}
  1229. %% \begin{lstlisting}
  1230. %% (define (Lint ast)
  1231. %% (match ast
  1232. %% [(Int n) #t]
  1233. %% [(Prim 'read '()) #t]
  1234. %% [(Prim '- (list e)) (Lint e)]
  1235. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1236. %% [(Program '() e) (Lint e)]
  1237. %% [else #f]))
  1238. %% \end{lstlisting}
  1239. %% \end{minipage}
  1240. %% \end{center}
  1241. %% %
  1242. %% Sometimes such a trick will save a few lines of code, especially when
  1243. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1244. %% \emph{not} recommended because it can get you into trouble.
  1245. %% %
  1246. %% For example, the above function is subtly wrong:
  1247. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1248. %% returns true when it should return false.
  1249. \section{Interpreters}
  1250. \label{sec:interp_Lint}
  1251. \index{subject}{interpreter}
  1252. The behavior of a program is defined by the specification of the
  1253. programming language.
  1254. %
  1255. \racket{For example, the Scheme language is defined in the report by
  1256. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1257. reference manual~\citep{plt-tr}.}
  1258. %
  1259. \python{For example, the Python language is defined in the Python
  1260. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1261. %
  1262. In this book we use interpreters to specify each language that we
  1263. consider. An interpreter that is designated as the definition of a
  1264. language is called a \emph{definitional
  1265. interpreter}~\citep{reynolds72:_def_interp}.
  1266. \index{subject}{definitional interpreter} We warm up by creating a
  1267. definitional interpreter for the \LangInt{} language. This interpreter
  1268. serves as a second example of structural recursion. The definition of the
  1269. \code{interp\_Lint} function is shown in
  1270. figure~\ref{fig:interp_Lint}.
  1271. %
  1272. \racket{The body of the function is a match on the input program
  1273. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1274. which in turn has one match clause per grammar rule for \LangInt{}
  1275. expressions.}
  1276. %
  1277. \python{The body of the function matches on the \code{Module} AST node
  1278. and then invokes \code{interp\_stmt} on each statement in the
  1279. module. The \code{interp\_stmt} function includes a case for each
  1280. grammar rule of the \Stmt{} nonterminal, and it calls
  1281. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1282. function includes a case for each grammar rule of the \Exp{}
  1283. nonterminal. We use several auxiliary functions such as \code{add64}
  1284. and \code{input\_int} that are defined in the support code for this book.}
  1285. \begin{figure}[tp]
  1286. \begin{tcolorbox}[colback=white]
  1287. {\if\edition\racketEd
  1288. \begin{lstlisting}
  1289. (define (interp_exp e)
  1290. (match e
  1291. [(Int n) n]
  1292. [(Prim 'read '())
  1293. (define r (read))
  1294. (cond [(fixnum? r) r]
  1295. [else (error 'interp_exp "read expected an integer" r)])]
  1296. [(Prim '- (list e))
  1297. (define v (interp_exp e))
  1298. (fx- 0 v)]
  1299. [(Prim '+ (list e1 e2))
  1300. (define v1 (interp_exp e1))
  1301. (define v2 (interp_exp e2))
  1302. (fx+ v1 v2)]
  1303. [(Prim '- (list e1 e2))
  1304. (define v1 (interp_exp e1))
  1305. (define v2 (interp_exp e2))
  1306. (fx- v1 v2)]))
  1307. (define (interp_Lint p)
  1308. (match p
  1309. [(Program '() e) (interp_exp e)]))
  1310. \end{lstlisting}
  1311. \fi}
  1312. {\if\edition\pythonEd\pythonColor
  1313. \begin{lstlisting}
  1314. def interp_exp(e):
  1315. match e:
  1316. case BinOp(left, Add(), right):
  1317. l = interp_exp(left); r = interp_exp(right)
  1318. return add64(l, r)
  1319. case BinOp(left, Sub(), right):
  1320. l = interp_exp(left); r = interp_exp(right)
  1321. return sub64(l, r)
  1322. case UnaryOp(USub(), v):
  1323. return neg64(interp_exp(v))
  1324. case Constant(value):
  1325. return value
  1326. case Call(Name('input_int'), []):
  1327. return input_int()
  1328. def interp_stmt(s):
  1329. match s:
  1330. case Expr(Call(Name('print'), [arg])):
  1331. print(interp_exp(arg))
  1332. case Expr(value):
  1333. interp_exp(value)
  1334. def interp_Lint(p):
  1335. match p:
  1336. case Module(body):
  1337. for s in body:
  1338. interp_stmt(s)
  1339. \end{lstlisting}
  1340. \fi}
  1341. \end{tcolorbox}
  1342. \caption{Interpreter for the \LangInt{} language.}
  1343. \label{fig:interp_Lint}
  1344. \end{figure}
  1345. Let us consider the result of interpreting a few \LangInt{} programs. The
  1346. following program adds two integers:
  1347. {\if\edition\racketEd
  1348. \begin{lstlisting}
  1349. (+ 10 32)
  1350. \end{lstlisting}
  1351. \fi}
  1352. {\if\edition\pythonEd\pythonColor
  1353. \begin{lstlisting}
  1354. print(10 + 32)
  1355. \end{lstlisting}
  1356. \fi}
  1357. %
  1358. \noindent The result is \key{42}, the answer to life, the universe,
  1359. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1360. the Galaxy} by Douglas Adams.}
  1361. %
  1362. We wrote this program in concrete syntax, whereas the parsed
  1363. abstract syntax is
  1364. {\if\edition\racketEd
  1365. \begin{lstlisting}
  1366. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1367. \end{lstlisting}
  1368. \fi}
  1369. {\if\edition\pythonEd\pythonColor
  1370. \begin{lstlisting}
  1371. Module([Expr(Call(Name('print'),
  1372. [BinOp(Constant(10), Add(), Constant(32))]))])
  1373. \end{lstlisting}
  1374. \fi}
  1375. The following program demonstrates that expressions may be nested within
  1376. each other, in this case nesting several additions and negations.
  1377. {\if\edition\racketEd
  1378. \begin{lstlisting}
  1379. (+ 10 (- (+ 12 20)))
  1380. \end{lstlisting}
  1381. \fi}
  1382. {\if\edition\pythonEd\pythonColor
  1383. \begin{lstlisting}
  1384. print(10 + -(12 + 20))
  1385. \end{lstlisting}
  1386. \fi}
  1387. %
  1388. \noindent What is the result of this program?
  1389. {\if\edition\racketEd
  1390. As mentioned previously, the \LangInt{} language does not support
  1391. arbitrarily large integers but only $63$-bit integers, so we
  1392. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1393. in Racket.
  1394. Suppose that
  1395. \[
  1396. n = 999999999999999999
  1397. \]
  1398. which indeed fits in $63$ bits. What happens when we run the
  1399. following program in our interpreter?
  1400. \begin{lstlisting}
  1401. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1402. \end{lstlisting}
  1403. It produces the following error:
  1404. \begin{lstlisting}
  1405. fx+: result is not a fixnum
  1406. \end{lstlisting}
  1407. We establish the convention that if running the definitional
  1408. interpreter on a program produces an error, then the meaning of that
  1409. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1410. error is a \code{trapped-error}. A compiler for the language is under
  1411. no obligation regarding programs with unspecified behavior; it does
  1412. not have to produce an executable, and if it does, that executable can
  1413. do anything. On the other hand, if the error is a
  1414. \code{trapped-error}, then the compiler must produce an executable and
  1415. it is required to report that an error occurred. To signal an error,
  1416. exit with a return code of \code{255}. The interpreters in chapters
  1417. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1418. \code{trapped-error}.
  1419. \fi}
  1420. % TODO: how to deal with too-large integers in the Python interpreter?
  1421. %% This convention applies to the languages defined in this
  1422. %% book, as a way to simplify the student's task of implementing them,
  1423. %% but this convention is not applicable to all programming languages.
  1424. %%
  1425. The last feature of the \LangInt{} language, the \READOP{} operation,
  1426. prompts the user of the program for an integer. Recall that program
  1427. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1428. \code{8}. So, if we run {\if\edition\racketEd
  1429. \begin{lstlisting}
  1430. (interp_Lint (Program '() ast1_1))
  1431. \end{lstlisting}
  1432. \fi}
  1433. {\if\edition\pythonEd\pythonColor
  1434. \begin{lstlisting}
  1435. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1436. \end{lstlisting}
  1437. \fi}
  1438. \noindent and if the input is \code{50}, the result is \code{42}.
  1439. We include the \READOP{} operation in \LangInt{} so that a clever
  1440. student cannot implement a compiler for \LangInt{} that simply runs
  1441. the interpreter during compilation to obtain the output and then
  1442. generates the trivial code to produce the output.\footnote{Yes, a
  1443. clever student did this in the first instance of this course!}
  1444. The job of a compiler is to translate a program in one language into a
  1445. program in another language so that the output program behaves the
  1446. same way as the input program. This idea is depicted in the
  1447. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1448. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1449. Given a compiler that translates from language $\mathcal{L}_1$ to
  1450. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1451. compiler must translate it into some program $P_2$ such that
  1452. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1453. same input $i$ yields the same output $o$.
  1454. \begin{equation} \label{eq:compile-correct}
  1455. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1456. \node (p1) at (0, 0) {$P_1$};
  1457. \node (p2) at (3, 0) {$P_2$};
  1458. \node (o) at (3, -2.5) {$o$};
  1459. \path[->] (p1) edge [above] node {compile} (p2);
  1460. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1461. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1462. \end{tikzpicture}
  1463. \end{equation}
  1464. \python{We establish the convention that if running the definitional
  1465. interpreter on a program produces an error, then the meaning of that
  1466. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1467. unless the exception raised is a \code{TrappedError}. A compiler for
  1468. the language is under no obligation regarding programs with
  1469. unspecified behavior; it does not have to produce an executable, and
  1470. if it does, that executable can do anything. On the other hand, if
  1471. the error is a \code{TrappedError}, then the compiler must produce
  1472. an executable and it is required to report that an error
  1473. occurred. To signal an error, exit with a return code of \code{255}.
  1474. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1475. section \ref{sec:arrays} use \code{TrappedError}.}
  1476. In the next section we see our first example of a compiler.
  1477. \section{Example Compiler: A Partial Evaluator}
  1478. \label{sec:partial-evaluation}
  1479. In this section we consider a compiler that translates \LangInt{}
  1480. programs into \LangInt{} programs that may be more efficient. The
  1481. compiler eagerly computes the parts of the program that do not depend
  1482. on any inputs, a process known as \emph{partial
  1483. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1484. For example, given the following program
  1485. {\if\edition\racketEd
  1486. \begin{lstlisting}
  1487. (+ (read) (- (+ 5 3)))
  1488. \end{lstlisting}
  1489. \fi}
  1490. {\if\edition\pythonEd\pythonColor
  1491. \begin{lstlisting}
  1492. print(input_int() + -(5 + 3) )
  1493. \end{lstlisting}
  1494. \fi}
  1495. \noindent our compiler translates it into the program
  1496. {\if\edition\racketEd
  1497. \begin{lstlisting}
  1498. (+ (read) -8)
  1499. \end{lstlisting}
  1500. \fi}
  1501. {\if\edition\pythonEd\pythonColor
  1502. \begin{lstlisting}
  1503. print(input_int() + -8)
  1504. \end{lstlisting}
  1505. \fi}
  1506. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1507. evaluator for the \LangInt{} language. The output of the partial evaluator
  1508. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1509. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1510. whereas the code for partially evaluating the negation and addition
  1511. operations is factored into three auxiliary functions:
  1512. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1513. functions is the output of partially evaluating the children.
  1514. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1515. arguments are integers and if they are, perform the appropriate
  1516. arithmetic. Otherwise, they create an AST node for the arithmetic
  1517. operation.
  1518. \begin{figure}[tp]
  1519. \begin{tcolorbox}[colback=white]
  1520. {\if\edition\racketEd
  1521. \begin{lstlisting}
  1522. (define (pe_neg r)
  1523. (match r
  1524. [(Int n) (Int (fx- 0 n))]
  1525. [else (Prim '- (list r))]))
  1526. (define (pe_add r1 r2)
  1527. (match* (r1 r2)
  1528. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1529. [(_ _) (Prim '+ (list r1 r2))]))
  1530. (define (pe_sub r1 r2)
  1531. (match* (r1 r2)
  1532. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1533. [(_ _) (Prim '- (list r1 r2))]))
  1534. (define (pe_exp e)
  1535. (match e
  1536. [(Int n) (Int n)]
  1537. [(Prim 'read '()) (Prim 'read '())]
  1538. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1539. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1540. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1541. (define (pe_Lint p)
  1542. (match p
  1543. [(Program '() e) (Program '() (pe_exp e))]))
  1544. \end{lstlisting}
  1545. \fi}
  1546. {\if\edition\pythonEd\pythonColor
  1547. \begin{lstlisting}
  1548. def pe_neg(r):
  1549. match r:
  1550. case Constant(n):
  1551. return Constant(neg64(n))
  1552. case _:
  1553. return UnaryOp(USub(), r)
  1554. def pe_add(r1, r2):
  1555. match (r1, r2):
  1556. case (Constant(n1), Constant(n2)):
  1557. return Constant(add64(n1, n2))
  1558. case _:
  1559. return BinOp(r1, Add(), r2)
  1560. def pe_sub(r1, r2):
  1561. match (r1, r2):
  1562. case (Constant(n1), Constant(n2)):
  1563. return Constant(sub64(n1, n2))
  1564. case _:
  1565. return BinOp(r1, Sub(), r2)
  1566. def pe_exp(e):
  1567. match e:
  1568. case BinOp(left, Add(), right):
  1569. return pe_add(pe_exp(left), pe_exp(right))
  1570. case BinOp(left, Sub(), right):
  1571. return pe_sub(pe_exp(left), pe_exp(right))
  1572. case UnaryOp(USub(), v):
  1573. return pe_neg(pe_exp(v))
  1574. case Constant(value):
  1575. return e
  1576. case Call(Name('input_int'), []):
  1577. return e
  1578. def pe_stmt(s):
  1579. match s:
  1580. case Expr(Call(Name('print'), [arg])):
  1581. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1582. case Expr(value):
  1583. return Expr(pe_exp(value))
  1584. def pe_P_int(p):
  1585. match p:
  1586. case Module(body):
  1587. new_body = [pe_stmt(s) for s in body]
  1588. return Module(new_body)
  1589. \end{lstlisting}
  1590. \fi}
  1591. \end{tcolorbox}
  1592. \caption{A partial evaluator for \LangInt{}.}
  1593. \label{fig:pe-arith}
  1594. \end{figure}
  1595. To gain some confidence that the partial evaluator is correct, we can
  1596. test whether it produces programs that produce the same result as the
  1597. input programs. That is, we can test whether it satisfies the diagram
  1598. of \eqref{eq:compile-correct}.
  1599. %
  1600. {\if\edition\racketEd
  1601. The following code runs the partial evaluator on several examples and
  1602. tests the output program. The \texttt{parse-program} and
  1603. \texttt{assert} functions are defined in
  1604. appendix~\ref{appendix:utilities}.\\
  1605. \begin{minipage}{1.0\textwidth}
  1606. \begin{lstlisting}
  1607. (define (test_pe p)
  1608. (assert "testing pe_Lint"
  1609. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1610. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1611. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1612. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1613. \end{lstlisting}
  1614. \end{minipage}
  1615. \fi}
  1616. % TODO: python version of testing the PE
  1617. \begin{exercise}\normalfont\normalsize
  1618. Create three programs in the \LangInt{} language and test whether
  1619. partially evaluating them with \code{pe\_Lint} and then
  1620. interpreting them with \code{interp\_Lint} gives the same result
  1621. as directly interpreting them with \code{interp\_Lint}.
  1622. \end{exercise}
  1623. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1624. \chapter{Integers and Variables}
  1625. \label{ch:Lvar}
  1626. \setcounter{footnote}{0}
  1627. This chapter covers compiling a subset of
  1628. \racket{Racket}\python{Python} to x86-64 assembly
  1629. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1630. integer arithmetic and local variables. We often refer to x86-64
  1631. simply as x86. The chapter first describes the \LangVar{} language
  1632. (section~\ref{sec:s0}) and then introduces x86 assembly
  1633. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1634. discuss only the instructions needed for compiling \LangVar{}. We
  1635. introduce more x86 instructions in subsequent chapters. After
  1636. introducing \LangVar{} and x86, we reflect on their differences and
  1637. create a plan to break down the translation from \LangVar{} to x86
  1638. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1639. the chapter gives detailed hints regarding each step. We aim to give
  1640. enough hints that the well-prepared reader, together with a few
  1641. friends, can implement a compiler from \LangVar{} to x86 in a short
  1642. time. To suggest the scale of this first compiler, we note that the
  1643. instructor solution for the \LangVar{} compiler is approximately
  1644. \racket{500}\python{300} lines of code.
  1645. \section{The \LangVar{} Language}
  1646. \label{sec:s0}
  1647. \index{subject}{variable}
  1648. The \LangVar{} language extends the \LangInt{} language with
  1649. variables. The concrete syntax of the \LangVar{} language is defined
  1650. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1651. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1652. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1653. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1654. \key{-} is a unary operator, and \key{+} is a binary operator.
  1655. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1656. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1657. the top of the program.
  1658. %% The $\itm{info}$
  1659. %% field of the \key{Program} structure contains an \emph{association
  1660. %% list} (a list of key-value pairs) that is used to communicate
  1661. %% auxiliary data from one compiler pass the next.
  1662. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1663. exhibit several compilation techniques.
  1664. \newcommand{\LvarGrammarRacket}{
  1665. \begin{array}{rcl}
  1666. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1667. \end{array}
  1668. }
  1669. \newcommand{\LvarASTRacket}{
  1670. \begin{array}{rcl}
  1671. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1672. \end{array}
  1673. }
  1674. \newcommand{\LvarGrammarPython}{
  1675. \begin{array}{rcl}
  1676. \Exp &::=& \Var{} \\
  1677. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1678. \end{array}
  1679. }
  1680. \newcommand{\LvarASTPython}{
  1681. \begin{array}{rcl}
  1682. \Exp{} &::=& \VAR{\Var{}} \\
  1683. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1684. \end{array}
  1685. }
  1686. \begin{figure}[tp]
  1687. \centering
  1688. \begin{tcolorbox}[colback=white]
  1689. {\if\edition\racketEd
  1690. \[
  1691. \begin{array}{l}
  1692. \gray{\LintGrammarRacket{}} \\ \hline
  1693. \LvarGrammarRacket{} \\
  1694. \begin{array}{rcl}
  1695. \LangVarM{} &::=& \Exp
  1696. \end{array}
  1697. \end{array}
  1698. \]
  1699. \fi}
  1700. {\if\edition\pythonEd\pythonColor
  1701. \[
  1702. \begin{array}{l}
  1703. \gray{\LintGrammarPython} \\ \hline
  1704. \LvarGrammarPython \\
  1705. \begin{array}{rcl}
  1706. \LangVarM{} &::=& \Stmt^{*}
  1707. \end{array}
  1708. \end{array}
  1709. \]
  1710. \fi}
  1711. \end{tcolorbox}
  1712. \caption{The concrete syntax of \LangVar{}.}
  1713. \label{fig:Lvar-concrete-syntax}
  1714. \end{figure}
  1715. \begin{figure}[tp]
  1716. \centering
  1717. \begin{tcolorbox}[colback=white]
  1718. {\if\edition\racketEd
  1719. \[
  1720. \begin{array}{l}
  1721. \gray{\LintASTRacket{}} \\ \hline
  1722. \LvarASTRacket \\
  1723. \begin{array}{rcl}
  1724. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1725. \end{array}
  1726. \end{array}
  1727. \]
  1728. \fi}
  1729. {\if\edition\pythonEd\pythonColor
  1730. \[
  1731. \begin{array}{l}
  1732. \gray{\LintASTPython}\\ \hline
  1733. \LvarASTPython \\
  1734. \begin{array}{rcl}
  1735. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1736. \end{array}
  1737. \end{array}
  1738. \]
  1739. \fi}
  1740. \end{tcolorbox}
  1741. \caption{The abstract syntax of \LangVar{}.}
  1742. \label{fig:Lvar-syntax}
  1743. \end{figure}
  1744. {\if\edition\racketEd
  1745. Let us dive further into the syntax and semantics of the \LangVar{}
  1746. language. The \key{let} feature defines a variable for use within its
  1747. body and initializes the variable with the value of an expression.
  1748. The abstract syntax for \key{let} is shown in
  1749. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1750. \begin{lstlisting}
  1751. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1752. \end{lstlisting}
  1753. For example, the following program initializes \code{x} to $32$ and then
  1754. evaluates the body \code{(+ 10 x)}, producing $42$.
  1755. \begin{lstlisting}
  1756. (let ([x (+ 12 20)]) (+ 10 x))
  1757. \end{lstlisting}
  1758. \fi}
  1759. %
  1760. {\if\edition\pythonEd\pythonColor
  1761. %
  1762. The \LangVar{} language includes an assignment statement, which defines a
  1763. variable for use in later statements and initializes the variable with
  1764. the value of an expression. The abstract syntax for assignment is
  1765. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1766. assignment is \index{subject}{Assign@\texttt{Assign}}
  1767. \begin{lstlisting}
  1768. |$\itm{var}$| = |$\itm{exp}$|
  1769. \end{lstlisting}
  1770. For example, the following program initializes the variable \code{x}
  1771. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1772. \begin{lstlisting}
  1773. x = 12 + 20
  1774. print(10 + x)
  1775. \end{lstlisting}
  1776. \fi}
  1777. {\if\edition\racketEd
  1778. %
  1779. When there are multiple \key{let}s for the same variable, the closest
  1780. enclosing \key{let} is used. That is, variable definitions overshadow
  1781. prior definitions. Consider the following program with two \key{let}s
  1782. that define two variables named \code{x}. Can you figure out the
  1783. result?
  1784. \begin{lstlisting}
  1785. (let ([x 32]) (+ (let ([x 10]) x) x))
  1786. \end{lstlisting}
  1787. For the purposes of depicting which variable occurrences correspond to
  1788. which definitions, the following shows the \code{x}'s annotated with
  1789. subscripts to distinguish them. Double-check that your answer for the
  1790. previous program is the same as your answer for this annotated version
  1791. of the program.
  1792. \begin{lstlisting}
  1793. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1794. \end{lstlisting}
  1795. The initializing expression is always evaluated before the body of the
  1796. \key{let}, so in the following, the \key{read} for \code{x} is
  1797. performed before the \key{read} for \code{y}. Given the input
  1798. $52$ then $10$, the following produces $42$ (not $-42$).
  1799. \begin{lstlisting}
  1800. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1801. \end{lstlisting}
  1802. \fi}
  1803. \subsection{Extensible Interpreters via Method Overriding}
  1804. \label{sec:extensible-interp}
  1805. \index{subject}{method overriding}
  1806. To prepare for discussing the interpreter of \LangVar{}, we explain
  1807. why we implement it in an object-oriented style. Throughout this book
  1808. we define many interpreters, one for each language that we
  1809. study. Because each language builds on the prior one, there is a lot
  1810. of commonality between these interpreters. We want to write down the
  1811. common parts just once instead of many times. A naive interpreter for
  1812. \LangVar{} would handle the \racket{cases for variables and
  1813. \code{let}} \python{case for variables} but dispatch to an
  1814. interpreter for \LangInt{} in the rest of the cases. The following
  1815. code sketches this idea. (We explain the \code{env} parameter in
  1816. section~\ref{sec:interp-Lvar}.)
  1817. \begin{center}
  1818. {\if\edition\racketEd
  1819. \begin{minipage}{0.45\textwidth}
  1820. \begin{lstlisting}
  1821. (define ((interp_Lint env) e)
  1822. (match e
  1823. [(Prim '- (list e1))
  1824. (fx- 0 ((interp_Lint env) e1))]
  1825. ...))
  1826. \end{lstlisting}
  1827. \end{minipage}
  1828. \begin{minipage}{0.45\textwidth}
  1829. \begin{lstlisting}
  1830. (define ((interp_Lvar env) e)
  1831. (match e
  1832. [(Var x)
  1833. (dict-ref env x)]
  1834. [(Let x e body)
  1835. (define v ((interp_Lvar env) e))
  1836. (define env^ (dict-set env x v))
  1837. ((interp_Lvar env^) body)]
  1838. [else ((interp_Lint env) e)]))
  1839. \end{lstlisting}
  1840. \end{minipage}
  1841. \fi}
  1842. {\if\edition\pythonEd\pythonColor
  1843. \begin{minipage}{0.45\textwidth}
  1844. \begin{lstlisting}
  1845. def interp_Lint(e, env):
  1846. match e:
  1847. case UnaryOp(USub(), e1):
  1848. return - interp_Lint(e1, env)
  1849. ...
  1850. \end{lstlisting}
  1851. \end{minipage}
  1852. \begin{minipage}{0.45\textwidth}
  1853. \begin{lstlisting}
  1854. def interp_Lvar(e, env):
  1855. match e:
  1856. case Name(id):
  1857. return env[id]
  1858. case _:
  1859. return interp_Lint(e, env)
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. \fi}
  1863. \end{center}
  1864. The problem with this naive approach is that it does not handle
  1865. situations in which an \LangVar{} feature, such as a variable, is
  1866. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1867. in the following program.
  1868. {\if\edition\racketEd
  1869. \begin{lstlisting}
  1870. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1871. \end{lstlisting}
  1872. \fi}
  1873. {\if\edition\pythonEd\pythonColor
  1874. \begin{minipage}{1.0\textwidth}
  1875. \begin{lstlisting}
  1876. y = 10
  1877. print(-y)
  1878. \end{lstlisting}
  1879. \end{minipage}
  1880. \fi}
  1881. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1882. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1883. then it recursively calls \code{interp\_Lint} again on its argument.
  1884. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1885. \code{interp\_Lint}, we get an error!
  1886. To make our interpreters extensible we need something called
  1887. \emph{open recursion}\index{subject}{open recursion}, in which the
  1888. tying of the recursive knot is delayed until the functions are
  1889. composed. Object-oriented languages provide open recursion via method
  1890. overriding. The following code uses
  1891. method overriding to interpret \LangInt{} and \LangVar{} using
  1892. %
  1893. \racket{the
  1894. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1895. \index{subject}{class} feature of Racket.}%
  1896. %
  1897. \python{Python \code{class} definitions.}
  1898. %
  1899. We define one class for each language and define a method for
  1900. interpreting expressions inside each class. The class for \LangVar{}
  1901. inherits from the class for \LangInt{}, and the method
  1902. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1903. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1904. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1905. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1906. \code{interp\_exp} in \LangInt{}.
  1907. \begin{center}
  1908. \hspace{-20pt}
  1909. {\if\edition\racketEd
  1910. \begin{minipage}{0.45\textwidth}
  1911. \begin{lstlisting}
  1912. (define interp-Lint-class
  1913. (class object%
  1914. (define/public ((interp_exp env) e)
  1915. (match e
  1916. [(Prim '- (list e))
  1917. (fx- 0 ((interp_exp env) e))]
  1918. ...))
  1919. ...))
  1920. \end{lstlisting}
  1921. \end{minipage}
  1922. \begin{minipage}{0.45\textwidth}
  1923. \begin{lstlisting}
  1924. (define interp-Lvar-class
  1925. (class interp-Lint-class
  1926. (define/override ((interp_exp env) e)
  1927. (match e
  1928. [(Var x)
  1929. (dict-ref env x)]
  1930. [(Let x e body)
  1931. (define v ((interp_exp env) e))
  1932. (define env^ (dict-set env x v))
  1933. ((interp_exp env^) body)]
  1934. [else
  1935. (super (interp_exp env) e)]))
  1936. ...
  1937. ))
  1938. \end{lstlisting}
  1939. \end{minipage}
  1940. \fi}
  1941. {\if\edition\pythonEd\pythonColor
  1942. \begin{minipage}{0.45\textwidth}
  1943. \begin{lstlisting}
  1944. class InterpLint:
  1945. def interp_exp(e):
  1946. match e:
  1947. case UnaryOp(USub(), e1):
  1948. return neg64(self.interp_exp(e1))
  1949. ...
  1950. ...
  1951. \end{lstlisting}
  1952. \end{minipage}
  1953. \begin{minipage}{0.45\textwidth}
  1954. \begin{lstlisting}
  1955. def InterpLvar(InterpLint):
  1956. def interp_exp(e):
  1957. match e:
  1958. case Name(id):
  1959. return env[id]
  1960. case _:
  1961. return super().interp_exp(e)
  1962. ...
  1963. \end{lstlisting}
  1964. \end{minipage}
  1965. \fi}
  1966. \end{center}
  1967. We return to the troublesome example, repeated here:
  1968. {\if\edition\racketEd
  1969. \begin{lstlisting}
  1970. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1971. \end{lstlisting}
  1972. \fi}
  1973. {\if\edition\pythonEd\pythonColor
  1974. \begin{lstlisting}
  1975. y = 10
  1976. print(-y)
  1977. \end{lstlisting}
  1978. \fi}
  1979. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1980. \racket{on this expression,}
  1981. \python{on the \code{-y} expression,}
  1982. %
  1983. which we call \code{e0}, by creating an object of the \LangVar{} class
  1984. and calling the \code{interp\_exp} method
  1985. {\if\edition\racketEd
  1986. \begin{lstlisting}
  1987. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1988. \end{lstlisting}
  1989. \fi}
  1990. {\if\edition\pythonEd\pythonColor
  1991. \begin{lstlisting}
  1992. InterpLvar().interp_exp(e0)
  1993. \end{lstlisting}
  1994. \fi}
  1995. \noindent To process the \code{-} operator, the default case of
  1996. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1997. method in \LangInt{}. But then for the recursive method call, it
  1998. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1999. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  2000. Thus, method overriding gives us the open recursion that we need to
  2001. implement our interpreters in an extensible way.
  2002. \subsection{Definitional Interpreter for \LangVar{}}
  2003. \label{sec:interp-Lvar}
  2004. Having justified the use of classes and methods to implement
  2005. interpreters, we revisit the definitional interpreter for \LangInt{}
  2006. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  2007. create an interpreter for \LangVar{}, shown in
  2008. figure~\ref{fig:interp-Lvar}.
  2009. %
  2010. \python{We change the \code{interp\_stmt} method in the interpreter
  2011. for \LangInt{} to take two extra parameters named \code{env}, which
  2012. we discuss in the next paragraph, and \code{cont} for
  2013. \emph{continuation}, which is the technical name for what comes
  2014. after a particular point in a program. The \code{cont} parameter is
  2015. the list of statements that follow the current statement. Note
  2016. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2017. statement and passes the rest of the statements as the argument for
  2018. \code{cont}. This organization enables each statement to decide what
  2019. if anything should be evaluated after it, for example, allowing a
  2020. \code{return} statement to exit early from a function (see
  2021. Chapter~\ref{ch:Lfun}).}
  2022. The interpreter for \LangVar{} adds two new cases for
  2023. variables and \racket{\key{let}}\python{assignment}. For
  2024. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2025. value bound to a variable to all the uses of the variable. To
  2026. accomplish this, we maintain a mapping from variables to values called
  2027. an \emph{environment}\index{subject}{environment}.
  2028. %
  2029. We use
  2030. %
  2031. \racket{an association list (alist) }%
  2032. %
  2033. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2034. %
  2035. to represent the environment.
  2036. %
  2037. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2038. and the \code{racket/dict} package.}
  2039. %
  2040. The \code{interp\_exp} function takes the current environment,
  2041. \code{env}, as an extra parameter. When the interpreter encounters a
  2042. variable, it looks up the corresponding value in the environment. If
  2043. the variable is not in the environment (because the variable was not
  2044. defined) then the lookup will fail and the interpreter will
  2045. halt with an error. Recall that the compiler is not obligated to
  2046. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2047. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2048. prohibit access to undefined variables.}
  2049. %
  2050. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2051. initializing expression, extends the environment with the result
  2052. value bound to the variable, using \code{dict-set}, then evaluates
  2053. the body of the \key{Let}.}
  2054. %
  2055. \python{When the interpreter encounters an assignment, it evaluates
  2056. the initializing expression and then associates the resulting value
  2057. with the variable in the environment.}
  2058. \begin{figure}[tp]
  2059. \begin{tcolorbox}[colback=white]
  2060. {\if\edition\racketEd
  2061. \begin{lstlisting}
  2062. (define interp-Lint-class
  2063. (class object%
  2064. (super-new)
  2065. (define/public ((interp_exp env) e)
  2066. (match e
  2067. [(Int n) n]
  2068. [(Prim 'read '())
  2069. (define r (read))
  2070. (cond [(fixnum? r) r]
  2071. [else (error 'interp_exp "expected an integer" r)])]
  2072. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2073. [(Prim '+ (list e1 e2))
  2074. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2075. [(Prim '- (list e1 e2))
  2076. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2077. (define/public (interp_program p)
  2078. (match p
  2079. [(Program '() e) ((interp_exp '()) e)]))
  2080. ))
  2081. \end{lstlisting}
  2082. \fi}
  2083. {\if\edition\pythonEd\pythonColor
  2084. \begin{lstlisting}
  2085. class InterpLint:
  2086. def interp_exp(self, e, env):
  2087. match e:
  2088. case BinOp(left, Add(), right):
  2089. l = self.interp_exp(left, env)
  2090. r = self.interp_exp(right, env)
  2091. return add64(l, r)
  2092. case BinOp(left, Sub(), right):
  2093. l = self.interp_exp(left, env)
  2094. r = self.interp_exp(right, env)
  2095. return sub64(l, r)
  2096. case UnaryOp(USub(), v):
  2097. return neg64(self.interp_exp(v, env))
  2098. case Constant(value):
  2099. return value
  2100. case Call(Name('input_int'), []):
  2101. return int(input())
  2102. def interp_stmt(self, s, env, cont):
  2103. match s:
  2104. case Expr(Call(Name('print'), [arg])):
  2105. val = self.interp_exp(arg, env)
  2106. print(val, end='')
  2107. return self.interp_stmts(cont, env)
  2108. case Expr(value):
  2109. self.interp_exp(value, env)
  2110. return self.interp_stmts(cont, env)
  2111. case _:
  2112. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2113. def interp_stmts(self, ss, env):
  2114. match ss:
  2115. case []:
  2116. return 0
  2117. case [s, *ss]:
  2118. return self.interp_stmt(s, env, ss)
  2119. def interp(self, p):
  2120. match p:
  2121. case Module(body):
  2122. self.interp_stmts(body, {})
  2123. def interp_Lint(p):
  2124. return InterpLint().interp(p)
  2125. \end{lstlisting}
  2126. \fi}
  2127. \end{tcolorbox}
  2128. \caption{Interpreter for \LangInt{} as a class.}
  2129. \label{fig:interp-Lint-class}
  2130. \end{figure}
  2131. \begin{figure}[tp]
  2132. \begin{tcolorbox}[colback=white]
  2133. {\if\edition\racketEd
  2134. \begin{lstlisting}
  2135. (define interp-Lvar-class
  2136. (class interp-Lint-class
  2137. (super-new)
  2138. (define/override ((interp_exp env) e)
  2139. (match e
  2140. [(Var x) (dict-ref env x)]
  2141. [(Let x e body)
  2142. (define new-env (dict-set env x ((interp_exp env) e)))
  2143. ((interp_exp new-env) body)]
  2144. [else ((super interp_exp env) e)]))
  2145. ))
  2146. (define (interp_Lvar p)
  2147. (send (new interp-Lvar-class) interp_program p))
  2148. \end{lstlisting}
  2149. \fi}
  2150. {\if\edition\pythonEd\pythonColor
  2151. \begin{lstlisting}
  2152. class InterpLvar(InterpLint):
  2153. def interp_exp(self, e, env):
  2154. match e:
  2155. case Name(id):
  2156. return env[id]
  2157. case _:
  2158. return super().interp_exp(e, env)
  2159. def interp_stmt(self, s, env, cont):
  2160. match s:
  2161. case Assign([Name(id)], value):
  2162. env[id] = self.interp_exp(value, env)
  2163. return self.interp_stmts(cont, env)
  2164. case _:
  2165. return super().interp_stmt(s, env, cont)
  2166. def interp_Lvar(p):
  2167. return InterpLvar().interp(p)
  2168. \end{lstlisting}
  2169. \fi}
  2170. \end{tcolorbox}
  2171. \caption{Interpreter for the \LangVar{} language.}
  2172. \label{fig:interp-Lvar}
  2173. \end{figure}
  2174. {\if\edition\racketEd
  2175. \begin{figure}[tp]
  2176. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2177. \small
  2178. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2179. An \emph{association list} (called an alist) is a list of key-value pairs.
  2180. For example, we can map people to their ages with an alist
  2181. \index{subject}{alist}\index{subject}{association list}
  2182. \begin{lstlisting}[basicstyle=\ttfamily]
  2183. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2184. \end{lstlisting}
  2185. The \emph{dictionary} interface is for mapping keys to values.
  2186. Every alist implements this interface. \index{subject}{dictionary}
  2187. The package
  2188. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2189. provides many functions for working with dictionaries, such as
  2190. \begin{description}
  2191. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2192. returns the value associated with the given $\itm{key}$.
  2193. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2194. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2195. and otherwise is the same as $\itm{dict}$.
  2196. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2197. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2198. of keys and values in $\itm{dict}$. For example, the following
  2199. creates a new alist in which the ages are incremented:
  2200. \end{description}
  2201. \vspace{-10pt}
  2202. \begin{lstlisting}[basicstyle=\ttfamily]
  2203. (for/list ([(k v) (in-dict ages)])
  2204. (cons k (add1 v)))
  2205. \end{lstlisting}
  2206. \end{tcolorbox}
  2207. %\end{wrapfigure}
  2208. \caption{Association lists implement the dictionary interface.}
  2209. \label{fig:alist}
  2210. \end{figure}
  2211. \fi}
  2212. The goal for this chapter is to implement a compiler that translates
  2213. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2214. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2215. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2216. That is, they output the same integer $n$. We depict this correctness
  2217. criteria in the following diagram:
  2218. \[
  2219. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2220. \node (p1) at (0, 0) {$P_1$};
  2221. \node (p2) at (4, 0) {$P_2$};
  2222. \node (o) at (4, -2) {$n$};
  2223. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2224. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2225. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2226. \end{tikzpicture}
  2227. \]
  2228. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2229. compiling \LangVar{}.
  2230. \section{The \LangXInt{} Assembly Language}
  2231. \label{sec:x86}
  2232. \index{subject}{x86}
  2233. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2234. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2235. assembler.
  2236. %
  2237. A program begins with a \code{main} label followed by a sequence of
  2238. instructions. The \key{globl} directive makes the \key{main} procedure
  2239. externally visible so that the operating system can call it.
  2240. %
  2241. An x86 program is stored in the computer's memory. For our purposes,
  2242. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2243. values. The computer has a \emph{program counter}
  2244. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2245. \code{rip} register that points to the address of the next instruction
  2246. to be executed. For most instructions, the program counter is
  2247. incremented after the instruction is executed so that it points to the
  2248. next instruction in memory. Most x86 instructions take two operands,
  2249. each of which is an integer constant (called an \emph{immediate
  2250. value}\index{subject}{immediate value}), a
  2251. \emph{register}\index{subject}{register}, or a memory location.
  2252. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2253. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2254. && \key{r8} \MID \key{r9} \MID \key{r10}
  2255. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2256. \MID \key{r14} \MID \key{r15}}
  2257. \newcommand{\GrammarXInt}{
  2258. \begin{array}{rcl}
  2259. \Reg &::=& \allregisters{} \\
  2260. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2261. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2262. \key{subq} \; \Arg\key{,} \Arg \MID
  2263. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2264. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2265. \key{callq} \; \mathit{label} \MID
  2266. \key{retq} \MID
  2267. \key{jmp}\,\itm{label} \MID \\
  2268. && \itm{label}\key{:}\; \Instr
  2269. \end{array}
  2270. }
  2271. \begin{figure}[tp]
  2272. \begin{tcolorbox}[colback=white]
  2273. {\if\edition\racketEd
  2274. \[
  2275. \begin{array}{l}
  2276. \GrammarXInt \\
  2277. \begin{array}{lcl}
  2278. \LangXIntM{} &::= & \key{.globl main}\\
  2279. & & \key{main:} \; \Instr\ldots
  2280. \end{array}
  2281. \end{array}
  2282. \]
  2283. \fi}
  2284. {\if\edition\pythonEd\pythonColor
  2285. \[
  2286. \begin{array}{lcl}
  2287. \Reg &::=& \allregisters{} \\
  2288. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2289. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2290. \key{subq} \; \Arg\key{,} \Arg \MID
  2291. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2292. && \key{callq} \; \mathit{label} \MID
  2293. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2294. \LangXIntM{} &::= & \key{.globl main}\\
  2295. & & \key{main:} \; \Instr^{*}
  2296. \end{array}
  2297. \]
  2298. \fi}
  2299. \end{tcolorbox}
  2300. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2301. \label{fig:x86-int-concrete}
  2302. \end{figure}
  2303. A register is a special kind of variable that holds a 64-bit
  2304. value. There are 16 general-purpose registers in the computer; their
  2305. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2306. written with a percent sign, \key{\%}, followed by its name,
  2307. for example \key{\%rax}.
  2308. An immediate value is written using the notation \key{\$}$n$ where $n$
  2309. is an integer.
  2310. %
  2311. %
  2312. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2313. which obtains the address stored in register $r$ and then adds $n$
  2314. bytes to the address. The resulting address is used to load or to store
  2315. to memory depending on whether it occurs as a source or destination
  2316. argument of an instruction.
  2317. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2318. the source $s$ and destination $d$, applies the arithmetic operation,
  2319. and then writes the result to the destination $d$. \index{subject}{instruction}
  2320. %
  2321. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2322. stores the result in $d$.
  2323. %
  2324. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2325. specified by the label, and $\key{retq}$ returns from a procedure to
  2326. its caller.
  2327. %
  2328. We discuss procedure calls in more detail further in this chapter and
  2329. in chapter~\ref{ch:Lfun}.
  2330. %
  2331. The last letter \key{q} indicates that these instructions operate on
  2332. quadwords, which are 64-bit values.
  2333. %
  2334. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2335. counter to the address of the instruction immediately after the
  2336. specified label.}
  2337. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2338. all the x86 instructions used in this book.
  2339. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2340. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2341. \lstinline{movq $10, %rax}
  2342. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2343. adds $32$ to the $10$ in \key{rax} and
  2344. puts the result, $42$, into \key{rax}.
  2345. %
  2346. The last instruction \key{retq} finishes the \key{main} function by
  2347. returning the integer in \key{rax} to the operating system. The
  2348. operating system interprets this integer as the program's exit
  2349. code. By convention, an exit code of 0 indicates that a program has
  2350. completed successfully, and all other exit codes indicate various
  2351. errors.
  2352. %
  2353. \racket{However, in this book we return the result of the program
  2354. as the exit code.}
  2355. \begin{figure}[tbp]
  2356. \begin{minipage}{0.45\textwidth}
  2357. \begin{tcolorbox}[colback=white]
  2358. \begin{lstlisting}
  2359. .globl main
  2360. main:
  2361. movq $10, %rax
  2362. addq $32, %rax
  2363. retq
  2364. \end{lstlisting}
  2365. \end{tcolorbox}
  2366. \end{minipage}
  2367. \caption{An x86 program that computes
  2368. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2369. \label{fig:p0-x86}
  2370. \end{figure}
  2371. We exhibit the use of memory for storing intermediate results in the
  2372. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2373. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2374. uses a region of memory called the \emph{procedure call stack}
  2375. (\emph{stack} for
  2376. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2377. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2378. for each procedure call. The memory layout for an individual frame is
  2379. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2380. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2381. address of the item at the top of the stack. In general, we use the
  2382. term \emph{pointer}\index{subject}{pointer} for something that
  2383. contains an address. The stack grows downward in memory, so we
  2384. increase the size of the stack by subtracting from the stack pointer.
  2385. In the context of a procedure call, the \emph{return
  2386. address}\index{subject}{return address} is the location of the
  2387. instruction that immediately follows the call instruction on the
  2388. caller side. The function call instruction, \code{callq}, pushes the
  2389. return address onto the stack prior to jumping to the procedure. The
  2390. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2391. pointer} and is used to access variables that are stored in the
  2392. frame of the current procedure call. The base pointer of the caller
  2393. is stored immediately after the return address.
  2394. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2395. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2396. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2397. $-16\key{(\%rbp)}$, and so on.
  2398. \begin{figure}[tbp]
  2399. \begin{minipage}{0.66\textwidth}
  2400. \begin{tcolorbox}[colback=white]
  2401. {\if\edition\racketEd
  2402. \begin{lstlisting}
  2403. start:
  2404. movq $10, -8(%rbp)
  2405. negq -8(%rbp)
  2406. movq -8(%rbp), %rax
  2407. addq $52, %rax
  2408. jmp conclusion
  2409. .globl main
  2410. main:
  2411. pushq %rbp
  2412. movq %rsp, %rbp
  2413. subq $16, %rsp
  2414. jmp start
  2415. conclusion:
  2416. addq $16, %rsp
  2417. popq %rbp
  2418. retq
  2419. \end{lstlisting}
  2420. \fi}
  2421. {\if\edition\pythonEd\pythonColor
  2422. \begin{lstlisting}
  2423. .globl main
  2424. main:
  2425. pushq %rbp
  2426. movq %rsp, %rbp
  2427. subq $16, %rsp
  2428. movq $10, -8(%rbp)
  2429. negq -8(%rbp)
  2430. movq -8(%rbp), %rax
  2431. addq $52, %rax
  2432. addq $16, %rsp
  2433. popq %rbp
  2434. retq
  2435. \end{lstlisting}
  2436. \fi}
  2437. \end{tcolorbox}
  2438. \end{minipage}
  2439. \caption{An x86 program that computes
  2440. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2441. \label{fig:p1-x86}
  2442. \end{figure}
  2443. \begin{figure}[tbp]
  2444. \begin{minipage}{0.66\textwidth}
  2445. \begin{tcolorbox}[colback=white]
  2446. \centering
  2447. \begin{tabular}{|r|l|} \hline
  2448. Position & Contents \\ \hline
  2449. $8$(\key{\%rbp}) & return address \\
  2450. $0$(\key{\%rbp}) & old \key{rbp} \\
  2451. $-8$(\key{\%rbp}) & variable $1$ \\
  2452. $-16$(\key{\%rbp}) & variable $2$ \\
  2453. \ldots & \ldots \\
  2454. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2455. \end{tabular}
  2456. \end{tcolorbox}
  2457. \end{minipage}
  2458. \caption{Memory layout of a frame.}
  2459. \label{fig:frame}
  2460. \end{figure}
  2461. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2462. is transferred from the operating system to the \code{main} function.
  2463. The operating system issues a \code{callq main} instruction that
  2464. pushes its return address on the stack and then jumps to
  2465. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2466. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2467. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2468. out of alignment (because the \code{callq} pushed the return address).
  2469. The first three instructions are the typical
  2470. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2471. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2472. pointer \code{rsp} and then saves the base pointer of the caller at
  2473. address \code{rsp} on the stack. The next instruction \code{movq
  2474. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2475. which is pointing to the location of the old base pointer. The
  2476. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2477. make enough room for storing variables. This program needs one
  2478. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2479. 16-byte-aligned, and then we are ready to make calls to other functions.
  2480. \racket{The last instruction of the prelude is \code{jmp start}, which
  2481. transfers control to the instructions that were generated from the
  2482. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2483. \racket{The first instruction under the \code{start} label is}
  2484. %
  2485. \python{The first instruction after the prelude is}
  2486. %
  2487. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2488. %
  2489. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2490. $1$ to $-10$.
  2491. %
  2492. The next instruction moves the $-10$ from variable $1$ into the
  2493. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2494. the value in \code{rax}, updating its contents to $42$.
  2495. \racket{The three instructions under the label \code{conclusion} are the
  2496. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2497. %
  2498. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2499. \code{main} function consists of the last three instructions.}
  2500. %
  2501. The first two restore the \code{rsp} and \code{rbp} registers to their
  2502. states at the beginning of the procedure. In particular,
  2503. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2504. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2505. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2506. \key{retq}, jumps back to the procedure that called this one and adds
  2507. $8$ to the stack pointer.
  2508. Our compiler needs a convenient representation for manipulating x86
  2509. programs, so we define an abstract syntax for x86, shown in
  2510. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2511. \LangXInt{}.
  2512. %
  2513. {\if\edition\pythonEd\pythonColor%
  2514. The main difference between this and the concrete syntax of \LangXInt{}
  2515. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2516. names, and register names are explicitly represented by strings.
  2517. \fi} %
  2518. {\if\edition\racketEd
  2519. The main difference between this and the concrete syntax of \LangXInt{}
  2520. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2521. front of every instruction. Instead instructions are grouped into
  2522. \emph{basic blocks}\index{subject}{basic block} with a
  2523. label associated with every basic block; this is why the \key{X86Program}
  2524. struct includes an alist mapping labels to basic blocks. The reason for this
  2525. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2526. introduce conditional branching. The \code{Block} structure includes
  2527. an $\itm{info}$ field that is not needed in this chapter but becomes
  2528. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2529. $\itm{info}$ field should contain an empty list.
  2530. \fi}
  2531. %
  2532. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2533. node includes an integer for representing the arity of the function,
  2534. that is, the number of arguments, which is helpful to know during
  2535. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2536. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2537. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2538. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2539. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2540. \MID \skey{r14} \MID \skey{r15}}
  2541. \newcommand{\ASTXIntRacket}{
  2542. \begin{array}{lcl}
  2543. \Reg &::=& \allregisters{} \\
  2544. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2545. \MID \DEREF{\Reg}{\Int} \\
  2546. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2547. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2548. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2549. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2550. &\MID& \PUSHQ{\Arg}
  2551. \MID \POPQ{\Arg} \\
  2552. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2553. \MID \RETQ{}
  2554. \MID \JMP{\itm{label}} \\
  2555. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2556. \end{array}
  2557. }
  2558. \newcommand{\ASTXIntPython}{
  2559. \begin{array}{lcl}
  2560. \Reg &::=& \allregisters{} \\
  2561. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2562. \MID \DEREF{\Reg}{\Int} \\
  2563. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2564. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2565. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2566. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2567. &\MID& \PUSHQ{\Arg}
  2568. \MID \POPQ{\Arg} \\
  2569. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2570. \MID \RETQ{}
  2571. \MID \JMP{\itm{label}} \\
  2572. \Block &::= & \Instr^{+}
  2573. \end{array}
  2574. }
  2575. \begin{figure}[tp]
  2576. \begin{tcolorbox}[colback=white]
  2577. \small
  2578. {\if\edition\racketEd
  2579. \[\arraycolsep=3pt
  2580. \begin{array}{l}
  2581. \ASTXIntRacket \\
  2582. \begin{array}{lcl}
  2583. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2584. \end{array}
  2585. \end{array}
  2586. \]
  2587. \fi}
  2588. {\if\edition\pythonEd\pythonColor
  2589. \[
  2590. \begin{array}{lcl}
  2591. \Reg &::=& \allastregisters{} \\
  2592. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2593. \MID \DEREF{\Reg}{\Int} \\
  2594. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2595. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2596. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2597. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2598. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2599. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2600. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2601. \end{array}
  2602. \]
  2603. \fi}
  2604. \end{tcolorbox}
  2605. \caption{The abstract syntax of \LangXInt{} assembly.}
  2606. \label{fig:x86-int-ast}
  2607. \end{figure}
  2608. \section{Planning the Trip to x86}
  2609. \label{sec:plan-s0-x86}
  2610. To compile one language to another, it helps to focus on the
  2611. differences between the two languages because the compiler will need
  2612. to bridge those differences. What are the differences between \LangVar{}
  2613. and x86 assembly? Here are some of the most important ones:
  2614. \begin{enumerate}
  2615. \item x86 arithmetic instructions typically have two arguments and
  2616. update the second argument in place. In contrast, \LangVar{}
  2617. arithmetic operations take two arguments and produce a new value.
  2618. An x86 instruction may have at most one memory-accessing argument.
  2619. Furthermore, some x86 instructions place special restrictions on
  2620. their arguments.
  2621. \item An argument of an \LangVar{} operator can be a deeply nested
  2622. expression, whereas x86 instructions restrict their arguments to be
  2623. integer constants, registers, and memory locations.
  2624. {\if\edition\racketEd
  2625. \item The order of execution in x86 is explicit in the syntax, which
  2626. is a sequence of instructions and jumps to labeled positions,
  2627. whereas in \LangVar{} the order of evaluation is a left-to-right
  2628. depth-first traversal of the abstract syntax tree. \fi}
  2629. \item A program in \LangVar{} can have any number of variables,
  2630. whereas x86 has 16 registers and the procedure call stack.
  2631. {\if\edition\racketEd
  2632. \item Variables in \LangVar{} can shadow other variables with the
  2633. same name. In x86, registers have unique names, and memory locations
  2634. have unique addresses.
  2635. \fi}
  2636. \end{enumerate}
  2637. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2638. down the problem into several steps, which deal with these differences
  2639. one at a time. Each of these steps is called a \emph{pass} of the
  2640. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2641. %
  2642. This term indicates that each step passes over, or traverses, the AST
  2643. of the program.
  2644. %
  2645. Furthermore, we follow the nanopass approach, which means that we
  2646. strive for each pass to accomplish one clear objective rather than two
  2647. or three at the same time.
  2648. %
  2649. We begin by sketching how we might implement each pass and give each
  2650. pass a name. We then figure out an ordering of the passes and the
  2651. input/output language for each pass. The very first pass has
  2652. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2653. its output language. In between these two passes, we can choose
  2654. whichever language is most convenient for expressing the output of
  2655. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2656. \emph{intermediate language} of our own design. Finally, to
  2657. implement each pass we write one recursive function per nonterminal in
  2658. the grammar of the input language of the pass.
  2659. \index{subject}{intermediate language}
  2660. Our compiler for \LangVar{} consists of the following passes:
  2661. %
  2662. \begin{description}
  2663. {\if\edition\racketEd
  2664. \item[\key{uniquify}] deals with the shadowing of variables by
  2665. renaming every variable to a unique name.
  2666. \fi}
  2667. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2668. of a primitive operation or function call is a variable or integer,
  2669. that is, an \emph{atomic} expression. We refer to nonatomic
  2670. expressions as \emph{complex}. This pass introduces temporary
  2671. variables to hold the results of complex
  2672. subexpressions.\index{subject}{atomic
  2673. expression}\index{subject}{complex expression}%
  2674. {\if\edition\racketEd
  2675. \item[\key{explicate\_control}] makes the execution order of the
  2676. program explicit. It converts the abstract syntax tree
  2677. representation into a graph in which each node is a labeled sequence
  2678. of statements and the edges are \code{goto} statements.
  2679. \fi}
  2680. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2681. handles the difference between
  2682. \LangVar{} operations and x86 instructions. This pass converts each
  2683. \LangVar{} operation to a short sequence of instructions that
  2684. accomplishes the same task.
  2685. \item[\key{assign\_homes}] replaces variables with registers or stack
  2686. locations.
  2687. \end{description}
  2688. %
  2689. {\if\edition\racketEd
  2690. %
  2691. Our treatment of \code{remove\_complex\_operands} and
  2692. \code{explicate\_control} as separate passes is an example of the
  2693. nanopass approach.\footnote{For analogous decompositions of the
  2694. translation into continuation passing style, see the work of
  2695. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2696. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2697. %
  2698. \fi}
  2699. The next question is, in what order should we apply these passes? This
  2700. question can be challenging because it is difficult to know ahead of
  2701. time which orderings will be better (that is, will be easier to
  2702. implement, produce more efficient code, and so on), and therefore
  2703. ordering often involves trial and error. Nevertheless, we can plan
  2704. ahead and make educated choices regarding the ordering.
  2705. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2706. \key{uniquify}? The \key{uniquify} pass should come first because
  2707. \key{explicate\_control} changes all the \key{let}-bound variables to
  2708. become local variables whose scope is the entire program, which would
  2709. confuse variables with the same name.}
  2710. %
  2711. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2712. because the later removes the \key{let} form, but it is convenient to
  2713. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2714. %
  2715. \racket{The ordering of \key{uniquify} with respect to
  2716. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2717. \key{uniquify} to come first.}
  2718. The \key{select\_instructions} and \key{assign\_homes} passes are
  2719. intertwined.
  2720. %
  2721. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2722. passing arguments to functions and that it is preferable to assign
  2723. parameters to their corresponding registers. This suggests that it
  2724. would be better to start with the \key{select\_instructions} pass,
  2725. which generates the instructions for argument passing, before
  2726. performing register allocation.
  2727. %
  2728. On the other hand, by selecting instructions first we may run into a
  2729. dead end in \key{assign\_homes}. Recall that only one argument of an
  2730. x86 instruction may be a memory access, but \key{assign\_homes} might
  2731. be forced to assign both arguments to memory locations.
  2732. %
  2733. A sophisticated approach is to repeat the two passes until a solution
  2734. is found. However, to reduce implementation complexity we recommend
  2735. placing \key{select\_instructions} first, followed by the
  2736. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2737. that uses a reserved register to fix outstanding problems.
  2738. \begin{figure}[tbp]
  2739. \begin{tcolorbox}[colback=white]
  2740. {\if\edition\racketEd
  2741. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2742. \node (Lvar) at (0,2) {\large \LangVar{}};
  2743. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2744. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2745. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2746. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2747. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2748. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2749. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2750. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2751. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2752. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2753. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2754. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2755. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2756. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2757. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2758. \end{tikzpicture}
  2759. \fi}
  2760. {\if\edition\pythonEd\pythonColor
  2761. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2762. \node (Lvar) at (0,2) {\large \LangVar{}};
  2763. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2764. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2765. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2766. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2767. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2768. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2769. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2770. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2771. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2772. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2773. \end{tikzpicture}
  2774. \fi}
  2775. \end{tcolorbox}
  2776. \caption{Diagram of the passes for compiling \LangVar{}. }
  2777. \label{fig:Lvar-passes}
  2778. \end{figure}
  2779. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2780. passes and identifies the input and output language of each pass.
  2781. %
  2782. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2783. language, which extends \LangXInt{} with an unbounded number of
  2784. program-scope variables and removes the restrictions regarding
  2785. instruction arguments.
  2786. %
  2787. The last pass, \key{prelude\_and\_conclusion}, places the program
  2788. instructions inside a \code{main} function with instructions for the
  2789. prelude and conclusion.
  2790. %
  2791. \racket{In the next section we discuss the \LangCVar{} intermediate
  2792. language that serves as the output of \code{explicate\_control}.}
  2793. %
  2794. The remainder of this chapter provides guidance on the implementation
  2795. of each of the compiler passes represented in
  2796. figure~\ref{fig:Lvar-passes}.
  2797. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2798. %% are programs that are still in the \LangVar{} language, though the
  2799. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2800. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2801. %% %
  2802. %% The output of \code{explicate\_control} is in an intermediate language
  2803. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2804. %% syntax, which we introduce in the next section. The
  2805. %% \key{select-instruction} pass translates from \LangCVar{} to
  2806. %% \LangXVar{}. The \key{assign-homes} and
  2807. %% \key{patch-instructions}
  2808. %% passes input and output variants of x86 assembly.
  2809. \newcommand{\CvarGrammarRacket}{
  2810. \begin{array}{lcl}
  2811. \Atm &::=& \Int \MID \Var \\
  2812. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2813. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2814. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2815. \end{array}
  2816. }
  2817. \newcommand{\CvarASTRacket}{
  2818. \begin{array}{lcl}
  2819. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2820. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2821. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2822. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2823. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2824. \end{array}
  2825. }
  2826. {\if\edition\racketEd
  2827. \subsection{The \LangCVar{} Intermediate Language}
  2828. The output of \code{explicate\_control} is similar to the C
  2829. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2830. categories for expressions and statements, so we name it \LangCVar{}.
  2831. This style of intermediate language is also known as
  2832. \emph{three-address code}, to emphasize that the typical form of a
  2833. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2834. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2835. The concrete syntax for \LangCVar{} is shown in
  2836. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2837. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2838. %
  2839. The \LangCVar{} language supports the same operators as \LangVar{} but
  2840. the arguments of operators are restricted to atomic
  2841. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2842. assignment statements that can be executed in sequence using the
  2843. \key{Seq} form. A sequence of statements always ends with
  2844. \key{Return}, a guarantee that is baked into the grammar rules for
  2845. \itm{tail}. The naming of this nonterminal comes from the term
  2846. \emph{tail position}\index{subject}{tail position}, which refers to an
  2847. expression that is the last one to execute within a function or
  2848. program.
  2849. A \LangCVar{} program consists of an alist mapping labels to
  2850. tails. This is more general than necessary for the present chapter, as
  2851. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2852. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2853. there is just one label, \key{start}, and the whole program is
  2854. its tail.
  2855. %
  2856. The $\itm{info}$ field of the \key{CProgram} form, after the
  2857. \code{explicate\_control} pass, contains an alist that associates the
  2858. symbol \key{locals} with a list of all the variables used in the
  2859. program. At the start of the program, these variables are
  2860. uninitialized; they become initialized on their first assignment.
  2861. \begin{figure}[tbp]
  2862. \begin{tcolorbox}[colback=white]
  2863. \[
  2864. \begin{array}{l}
  2865. \CvarGrammarRacket \\
  2866. \begin{array}{lcl}
  2867. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2868. \end{array}
  2869. \end{array}
  2870. \]
  2871. \end{tcolorbox}
  2872. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2873. \label{fig:c0-concrete-syntax}
  2874. \end{figure}
  2875. \begin{figure}[tbp]
  2876. \begin{tcolorbox}[colback=white]
  2877. \[
  2878. \begin{array}{l}
  2879. \CvarASTRacket \\
  2880. \begin{array}{lcl}
  2881. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2882. \end{array}
  2883. \end{array}
  2884. \]
  2885. \end{tcolorbox}
  2886. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2887. \label{fig:c0-syntax}
  2888. \end{figure}
  2889. The definitional interpreter for \LangCVar{} is in the support code,
  2890. in the file \code{interp-Cvar.rkt}.
  2891. \fi}
  2892. {\if\edition\racketEd
  2893. \section{Uniquify Variables}
  2894. \label{sec:uniquify-Lvar}
  2895. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2896. with a unique name. Both the input and output of the \code{uniquify}
  2897. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2898. should translate the program on the left into the program on the
  2899. right.
  2900. \begin{transformation}
  2901. \begin{lstlisting}
  2902. (let ([x 32])
  2903. (+ (let ([x 10]) x) x))
  2904. \end{lstlisting}
  2905. \compilesto
  2906. \begin{lstlisting}
  2907. (let ([x.1 32])
  2908. (+ (let ([x.2 10]) x.2) x.1))
  2909. \end{lstlisting}
  2910. \end{transformation}
  2911. The following is another example translation, this time of a program
  2912. with a \key{let} nested inside the initializing expression of another
  2913. \key{let}.
  2914. \begin{transformation}
  2915. \begin{lstlisting}
  2916. (let ([x (let ([x 4])
  2917. (+ x 1))])
  2918. (+ x 2))
  2919. \end{lstlisting}
  2920. \compilesto
  2921. \begin{lstlisting}
  2922. (let ([x.2 (let ([x.1 4])
  2923. (+ x.1 1))])
  2924. (+ x.2 2))
  2925. \end{lstlisting}
  2926. \end{transformation}
  2927. We recommend implementing \code{uniquify} by creating a structurally
  2928. recursive function named \code{uniquify\_exp} that does little other
  2929. than copy an expression. However, when encountering a \key{let}, it
  2930. should generate a unique name for the variable and associate the old
  2931. name with the new name in an alist.\footnote{The Racket function
  2932. \code{gensym} is handy for generating unique variable names.} The
  2933. \code{uniquify\_exp} function needs to access this alist when it gets
  2934. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2935. for the alist.
  2936. The skeleton of the \code{uniquify\_exp} function is shown in
  2937. figure~\ref{fig:uniquify-Lvar}.
  2938. %% The function is curried so that it is
  2939. %% convenient to partially apply it to an alist and then apply it to
  2940. %% different expressions, as in the last case for primitive operations in
  2941. %% figure~\ref{fig:uniquify-Lvar}.
  2942. The
  2943. %
  2944. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2945. %
  2946. form of Racket is useful for transforming the element of a list to
  2947. produce a new list.\index{subject}{for/list}
  2948. \begin{figure}[tbp]
  2949. \begin{tcolorbox}[colback=white]
  2950. \begin{lstlisting}
  2951. (define (uniquify_exp env)
  2952. (lambda (e)
  2953. (match e
  2954. [(Var x) ___]
  2955. [(Int n) (Int n)]
  2956. [(Let x e body) ___]
  2957. [(Prim op es)
  2958. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2959. (define (uniquify p)
  2960. (match p
  2961. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2962. \end{lstlisting}
  2963. \end{tcolorbox}
  2964. \caption{Skeleton for the \key{uniquify} pass.}
  2965. \label{fig:uniquify-Lvar}
  2966. \end{figure}
  2967. \begin{exercise}
  2968. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2969. Complete the \code{uniquify} pass by filling in the blanks in
  2970. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2971. variables and for the \key{let} form in the file \code{compiler.rkt}
  2972. in the support code.
  2973. \end{exercise}
  2974. \begin{exercise}
  2975. \normalfont\normalsize
  2976. \label{ex:Lvar}
  2977. Create five \LangVar{} programs that exercise the most interesting
  2978. parts of the \key{uniquify} pass; that is, the programs should include
  2979. \key{let} forms, variables, and variables that shadow each other.
  2980. The five programs should be placed in the subdirectory named
  2981. \key{tests}, and the file names should start with \code{var\_test\_}
  2982. followed by a unique integer and end with the file extension
  2983. \key{.rkt}.
  2984. %
  2985. The \key{run-tests.rkt} script in the support code checks whether the
  2986. output programs produce the same result as the input programs. The
  2987. script uses the \key{interp-tests} function
  2988. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2989. your \key{uniquify} pass on the example programs. The \code{passes}
  2990. parameter of \key{interp-tests} is a list that should have one entry
  2991. for each pass in your compiler. For now, define \code{passes} to
  2992. contain just one entry for \code{uniquify} as follows:
  2993. \begin{lstlisting}
  2994. (define passes
  2995. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2996. \end{lstlisting}
  2997. Run the \key{run-tests.rkt} script in the support code to check
  2998. whether the output programs produce the same result as the input
  2999. programs.
  3000. \end{exercise}
  3001. \fi}
  3002. \section{Remove Complex Operands}
  3003. \label{sec:remove-complex-opera-Lvar}
  3004. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3005. into a restricted form in which the arguments of operations are atomic
  3006. expressions. Put another way, this pass removes complex
  3007. operands\index{subject}{complex operand}, such as the expression
  3008. \racket{\code{(- 10)}}\python{\code{-10}}
  3009. in the following program. This is accomplished by introducing a new
  3010. temporary variable, assigning the complex operand to the new
  3011. variable, and then using the new variable in place of the complex
  3012. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3013. right.
  3014. {\if\edition\racketEd
  3015. \begin{transformation}
  3016. % var_test_19.rkt
  3017. \begin{lstlisting}
  3018. (let ([x (+ 42 (- 10))])
  3019. (+ x 10))
  3020. \end{lstlisting}
  3021. \compilesto
  3022. \begin{lstlisting}
  3023. (let ([x (let ([tmp.1 (- 10)])
  3024. (+ 42 tmp.1))])
  3025. (+ x 10))
  3026. \end{lstlisting}
  3027. \end{transformation}
  3028. \fi}
  3029. {\if\edition\pythonEd\pythonColor
  3030. \begin{transformation}
  3031. \begin{lstlisting}
  3032. x = 42 + -10
  3033. print(x + 10)
  3034. \end{lstlisting}
  3035. \compilesto
  3036. \begin{lstlisting}
  3037. tmp_0 = -10
  3038. x = 42 + tmp_0
  3039. tmp_1 = x + 10
  3040. print(tmp_1)
  3041. \end{lstlisting}
  3042. \end{transformation}
  3043. \fi}
  3044. \newcommand{\LvarMonadASTRacket}{
  3045. \begin{array}{rcl}
  3046. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3047. \Exp &::=& \Atm \MID \READ{} \\
  3048. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3049. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3050. \end{array}
  3051. }
  3052. \newcommand{\LvarMonadASTPython}{
  3053. \begin{array}{rcl}
  3054. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3055. \Exp{} &::=& \Atm \MID \READ{} \\
  3056. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3057. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3058. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3059. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3060. \end{array}
  3061. }
  3062. \begin{figure}[tp]
  3063. \centering
  3064. \begin{tcolorbox}[colback=white]
  3065. {\if\edition\racketEd
  3066. \[
  3067. \begin{array}{l}
  3068. \LvarMonadASTRacket \\
  3069. \begin{array}{rcl}
  3070. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3071. \end{array}
  3072. \end{array}
  3073. \]
  3074. \fi}
  3075. {\if\edition\pythonEd\pythonColor
  3076. \[
  3077. \begin{array}{l}
  3078. \LvarMonadASTPython \\
  3079. \begin{array}{rcl}
  3080. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3081. \end{array}
  3082. \end{array}
  3083. \]
  3084. \fi}
  3085. \end{tcolorbox}
  3086. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3087. atomic expressions.}
  3088. \label{fig:Lvar-anf-syntax}
  3089. \end{figure}
  3090. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3091. of this pass, the language \LangVarANF{}. The only difference is that
  3092. operator arguments are restricted to be atomic expressions that are
  3093. defined by the \Atm{} nonterminal. In particular, integer constants
  3094. and variables are atomic.
  3095. The atomic expressions are pure (they do not cause or depend on side
  3096. effects) whereas complex expressions may have side effects, such as
  3097. \READ{}. A language with this separation between pure expressions
  3098. versus expressions with side effects is said to be in monadic normal
  3099. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3100. in the name \LangVarANF{}. An important invariant of the
  3101. \code{remove\_complex\_operands} pass is that the relative ordering
  3102. among complex expressions is not changed, but the relative ordering
  3103. between atomic expressions and complex expressions can change and
  3104. often does. These changes are behavior preserving because
  3105. atomic expressions are pure.
  3106. {\if\edition\racketEd
  3107. Another well-known form for intermediate languages is the
  3108. \emph{administrative normal form}
  3109. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3110. \index{subject}{administrative normal form} \index{subject}{ANF}
  3111. %
  3112. The \LangVarANF{} language is not quite in ANF because it allows the
  3113. right-hand side of a \code{let} to be a complex expression, such as
  3114. another \code{let}. The flattening of nested \code{let} expressions is
  3115. instead one of the responsibilities of the \code{explicate\_control}
  3116. pass.
  3117. \fi}
  3118. {\if\edition\racketEd
  3119. We recommend implementing this pass with two mutually recursive
  3120. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3121. \code{rco\_atom} to subexpressions that need to become atomic and to
  3122. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3123. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3124. returns an expression. The \code{rco\_atom} function returns two
  3125. things: an atomic expression and an alist mapping temporary variables to
  3126. complex subexpressions. You can return multiple things from a function
  3127. using Racket's \key{values} form, and you can receive multiple things
  3128. from a function call using the \key{define-values} form.
  3129. \fi}
  3130. %
  3131. {\if\edition\pythonEd\pythonColor
  3132. %
  3133. We recommend implementing this pass with an auxiliary method named
  3134. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3135. Boolean that specifies whether the expression needs to become atomic
  3136. or not. The \code{rco\_exp} method should return a pair consisting of
  3137. the new expression and a list of pairs, associating new temporary
  3138. variables with their initializing expressions.
  3139. %
  3140. \fi}
  3141. {\if\edition\racketEd
  3142. %
  3143. In the example program with the expression \code{(+ 42 (-
  3144. 10))}, the subexpression \code{(- 10)} should be processed using the
  3145. \code{rco\_atom} function because it is an argument of the \code{+}
  3146. operator and therefore needs to become atomic. The output of
  3147. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3148. \begin{transformation}
  3149. \begin{lstlisting}
  3150. (- 10)
  3151. \end{lstlisting}
  3152. \compilesto
  3153. \begin{lstlisting}
  3154. tmp.1
  3155. ((tmp.1 . (- 10)))
  3156. \end{lstlisting}
  3157. \end{transformation}
  3158. \fi}
  3159. %
  3160. {\if\edition\pythonEd\pythonColor
  3161. %
  3162. Returning to the example program with the expression \code{42 + -10},
  3163. the subexpression \code{-10} should be processed using the
  3164. \code{rco\_exp} function with \code{True} as the second argument,
  3165. because \code{-10} is an argument of the \code{+} operator and
  3166. therefore needs to become atomic. The output of \code{rco\_exp}
  3167. applied to \code{-10} is as follows.
  3168. \begin{transformation}
  3169. \begin{lstlisting}
  3170. -10
  3171. \end{lstlisting}
  3172. \compilesto
  3173. \begin{lstlisting}
  3174. tmp_1
  3175. [(tmp_1, -10)]
  3176. \end{lstlisting}
  3177. \end{transformation}
  3178. %
  3179. \fi}
  3180. Take special care of programs, such as the following, that
  3181. %
  3182. \racket{bind a variable to an atomic expression.}
  3183. %
  3184. \python{assign an atomic expression to a variable.}
  3185. %
  3186. You should leave such \racket{variable bindings}\python{assignments}
  3187. unchanged, as shown in the program on the right:\\
  3188. %
  3189. {\if\edition\racketEd
  3190. \begin{transformation}
  3191. % var_test_20.rkt
  3192. \begin{lstlisting}
  3193. (let ([a 42])
  3194. (let ([b a])
  3195. b))
  3196. \end{lstlisting}
  3197. \compilesto
  3198. \begin{lstlisting}
  3199. (let ([a 42])
  3200. (let ([b a])
  3201. b))
  3202. \end{lstlisting}
  3203. \end{transformation}
  3204. \fi}
  3205. {\if\edition\pythonEd\pythonColor
  3206. \begin{transformation}
  3207. \begin{lstlisting}
  3208. a = 42
  3209. b = a
  3210. print(b)
  3211. \end{lstlisting}
  3212. \compilesto
  3213. \begin{lstlisting}
  3214. a = 42
  3215. b = a
  3216. print(b)
  3217. \end{lstlisting}
  3218. \end{transformation}
  3219. \fi}
  3220. %
  3221. \noindent A careless implementation might produce the following output with
  3222. unnecessary temporary variables.
  3223. \begin{center}
  3224. \begin{minipage}{0.4\textwidth}
  3225. {\if\edition\racketEd
  3226. \begin{lstlisting}
  3227. (let ([tmp.1 42])
  3228. (let ([a tmp.1])
  3229. (let ([tmp.2 a])
  3230. (let ([b tmp.2])
  3231. b))))
  3232. \end{lstlisting}
  3233. \fi}
  3234. {\if\edition\pythonEd\pythonColor
  3235. \begin{lstlisting}
  3236. tmp_1 = 42
  3237. a = tmp_1
  3238. tmp_2 = a
  3239. b = tmp_2
  3240. print(b)
  3241. \end{lstlisting}
  3242. \fi}
  3243. \end{minipage}
  3244. \end{center}
  3245. \begin{exercise}
  3246. \normalfont\normalsize
  3247. {\if\edition\racketEd
  3248. Implement the \code{remove\_complex\_operands} function in
  3249. \code{compiler.rkt}.
  3250. %
  3251. Create three new \LangVar{} programs that exercise the interesting
  3252. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3253. regarding file names described in exercise~\ref{ex:Lvar}.
  3254. %
  3255. In the \code{run-tests.rkt} script, add the following entry to the
  3256. list of \code{passes}, and then run the script to test your compiler.
  3257. \begin{lstlisting}
  3258. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3259. \end{lstlisting}
  3260. In debugging your compiler, it is often useful to see the intermediate
  3261. programs that are output from each pass. To print the intermediate
  3262. programs, place \lstinline{(debug-level 1)} before the call to
  3263. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3264. %
  3265. {\if\edition\pythonEd\pythonColor
  3266. Implement the \code{remove\_complex\_operands} pass in
  3267. \code{compiler.py}, creating auxiliary functions for each
  3268. nonterminal in the grammar, that is, \code{rco\_exp}
  3269. and \code{rco\_stmt}. We recommend that you use the function
  3270. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3271. \fi}
  3272. \end{exercise}
  3273. {\if\edition\pythonEd\pythonColor
  3274. \begin{exercise}
  3275. \normalfont\normalsize
  3276. \label{ex:Lvar}
  3277. Create five \LangVar{} programs that exercise the most interesting
  3278. parts of the \code{remove\_complex\_operands} pass. The five programs
  3279. should be placed in the subdirectory \key{tests/var}, and the file
  3280. names should end with the file extension \key{.py}. Run the
  3281. \key{run-tests.py} script in the support code to check whether the
  3282. output programs produce the same result as the input programs.
  3283. \end{exercise}
  3284. \fi}
  3285. {\if\edition\racketEd
  3286. \section{Explicate Control}
  3287. \label{sec:explicate-control-Lvar}
  3288. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3289. programs that make the order of execution explicit in their
  3290. syntax. For now this amounts to flattening \key{let} constructs into a
  3291. sequence of assignment statements. For example, consider the following
  3292. \LangVar{} program:\\
  3293. % var_test_11.rkt
  3294. \begin{minipage}{0.96\textwidth}
  3295. \begin{lstlisting}
  3296. (let ([y (let ([x 20])
  3297. (+ x (let ([x 22]) x)))])
  3298. y)
  3299. \end{lstlisting}
  3300. \end{minipage}\\
  3301. %
  3302. The output of the previous pass is shown next, on the left, and the
  3303. output of \code{explicate\_control} is on the right. Recall that the
  3304. right-hand side of a \key{let} executes before its body, so that the order
  3305. of evaluation for this program is to assign \code{20} to \code{x.1},
  3306. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3307. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3308. this ordering explicit.
  3309. \begin{transformation}
  3310. \begin{lstlisting}
  3311. (let ([y (let ([x.1 20])
  3312. (let ([x.2 22])
  3313. (+ x.1 x.2)))])
  3314. y)
  3315. \end{lstlisting}
  3316. \compilesto
  3317. \begin{lstlisting}[language=C]
  3318. start:
  3319. x.1 = 20;
  3320. x.2 = 22;
  3321. y = (+ x.1 x.2);
  3322. return y;
  3323. \end{lstlisting}
  3324. \end{transformation}
  3325. \begin{figure}[tbp]
  3326. \begin{tcolorbox}[colback=white]
  3327. \begin{lstlisting}
  3328. (define (explicate_tail e)
  3329. (match e
  3330. [(Var x) ___]
  3331. [(Int n) (Return (Int n))]
  3332. [(Let x rhs body) ___]
  3333. [(Prim op es) ___]
  3334. [else (error "explicate_tail unhandled case" e)]))
  3335. (define (explicate_assign e x cont)
  3336. (match e
  3337. [(Var x) ___]
  3338. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3339. [(Let y rhs body) ___]
  3340. [(Prim op es) ___]
  3341. [else (error "explicate_assign unhandled case" e)]))
  3342. (define (explicate_control p)
  3343. (match p
  3344. [(Program info body) ___]))
  3345. \end{lstlisting}
  3346. \end{tcolorbox}
  3347. \caption{Skeleton for the \code{explicate\_control} pass.}
  3348. \label{fig:explicate-control-Lvar}
  3349. \end{figure}
  3350. The organization of this pass depends on the notion of tail position
  3351. to which we have alluded. Here is the definition.
  3352. \begin{definition}\normalfont
  3353. The following rules define when an expression is in \emph{tail
  3354. position}\index{subject}{tail position} for the language \LangVar{}.
  3355. \begin{enumerate}
  3356. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3357. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3358. \end{enumerate}
  3359. \end{definition}
  3360. We recommend implementing \code{explicate\_control} using two
  3361. recursive functions, \code{explicate\_tail} and
  3362. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3363. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3364. function should be applied to expressions in tail position, whereas the
  3365. \code{explicate\_assign} should be applied to expressions that occur on
  3366. the right-hand side of a \key{let}.
  3367. %
  3368. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3369. input and produces a \Tail{} in \LangCVar{} (see
  3370. figure~\ref{fig:c0-syntax}).
  3371. %
  3372. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3373. the variable to which it is to be assigned, and a \Tail{} in
  3374. \LangCVar{} for the code that comes after the assignment. The
  3375. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3376. The \code{explicate\_assign} function is in accumulator-passing style:
  3377. the \code{cont} parameter is used for accumulating the output. This
  3378. accumulator-passing style plays an important role in the way that we
  3379. generate high-quality code for conditional expressions in
  3380. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3381. continuation because it contains the generated code that should come
  3382. after the current assignment. This code organization is also related
  3383. to continuation-passing style, except that \code{cont} is not what
  3384. happens next during compilation but is what happens next in the
  3385. generated code.
  3386. \begin{exercise}\normalfont\normalsize
  3387. %
  3388. Implement the \code{explicate\_control} function in
  3389. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3390. exercise the code in \code{explicate\_control}.
  3391. %
  3392. In the \code{run-tests.rkt} script, add the following entry to the
  3393. list of \code{passes} and then run the script to test your compiler.
  3394. \begin{lstlisting}
  3395. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3396. \end{lstlisting}
  3397. \end{exercise}
  3398. \fi}
  3399. \section{Select Instructions}
  3400. \label{sec:select-Lvar}
  3401. \index{subject}{select instructions}
  3402. In the \code{select\_instructions} pass we begin the work of
  3403. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3404. language of this pass is a variant of x86 that still uses variables,
  3405. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3406. nonterminal of the \LangXInt{} abstract syntax
  3407. (figure~\ref{fig:x86-int-ast}).
  3408. \racket{We recommend implementing the
  3409. \code{select\_instructions} with three auxiliary functions, one for
  3410. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3411. $\Tail$.}
  3412. \python{We recommend implementing an auxiliary function
  3413. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3414. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3415. same and integer constants change to immediates; that is, $\INT{n}$
  3416. changes to $\IMM{n}$.}
  3417. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3418. arithmetic operations. For example, consider the following addition
  3419. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3420. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3421. \key{addq} instruction in x86, but it performs an in-place update.
  3422. %
  3423. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3424. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3425. \begin{transformation}
  3426. {\if\edition\racketEd
  3427. \begin{lstlisting}
  3428. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3429. \end{lstlisting}
  3430. \fi}
  3431. {\if\edition\pythonEd\pythonColor
  3432. \begin{lstlisting}
  3433. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3434. \end{lstlisting}
  3435. \fi}
  3436. \compilesto
  3437. \begin{lstlisting}
  3438. movq |$\Arg_1$|, %rax
  3439. addq |$\Arg_2$|, %rax
  3440. movq %rax, |$\itm{var}$|
  3441. \end{lstlisting}
  3442. \end{transformation}
  3443. %
  3444. However, with some care we can generate shorter sequences of
  3445. instructions. Suppose that one or more of the arguments of the
  3446. addition is the same variable as the left-hand side of the assignment.
  3447. Then the assignment statement can be translated into a single
  3448. \key{addq} instruction, as follows.
  3449. \begin{transformation}
  3450. {\if\edition\racketEd
  3451. \begin{lstlisting}
  3452. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3453. \end{lstlisting}
  3454. \fi}
  3455. {\if\edition\pythonEd\pythonColor
  3456. \begin{lstlisting}
  3457. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3458. \end{lstlisting}
  3459. \fi}
  3460. \compilesto
  3461. \begin{lstlisting}
  3462. addq |$\Arg_1$|, |$\itm{var}$|
  3463. \end{lstlisting}
  3464. \end{transformation}
  3465. %
  3466. On the other hand, if $\Atm_2$ is not the same variable as the
  3467. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3468. and then add $\Arg_2$ to \itm{var}.
  3469. %
  3470. \begin{transformation}
  3471. {\if\edition\racketEd
  3472. \begin{lstlisting}
  3473. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3474. \end{lstlisting}
  3475. \fi}
  3476. {\if\edition\pythonEd\pythonColor
  3477. \begin{lstlisting}
  3478. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3479. \end{lstlisting}
  3480. \fi}
  3481. \compilesto
  3482. \begin{lstlisting}
  3483. movq |$\Arg_1$|, |$\itm{var}$|
  3484. addq |$\Arg_2$|, |$\itm{var}$|
  3485. \end{lstlisting}
  3486. \end{transformation}
  3487. The \READOP{} operation does not have a direct counterpart in x86
  3488. assembly, so we provide this functionality with the function
  3489. \code{read\_int} in the file \code{runtime.c}, written in
  3490. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3491. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3492. system}, or simply the \emph{runtime} for short. When compiling your
  3493. generated x86 assembly code, you need to compile \code{runtime.c} to
  3494. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3495. \code{-c}) and link it into the executable. For our purposes of code
  3496. generation, all you need to do is translate an assignment of
  3497. \READOP{} into a call to the \code{read\_int} function followed by a
  3498. move from \code{rax} to the left-hand side variable. (The
  3499. return value of a function is placed in \code{rax}.)
  3500. \begin{transformation}
  3501. {\if\edition\racketEd
  3502. \begin{lstlisting}
  3503. |$\itm{var}$| = (read);
  3504. \end{lstlisting}
  3505. \fi}
  3506. {\if\edition\pythonEd\pythonColor
  3507. \begin{lstlisting}
  3508. |$\itm{var}$| = input_int();
  3509. \end{lstlisting}
  3510. \fi}
  3511. \compilesto
  3512. \begin{lstlisting}
  3513. callq read_int
  3514. movq %rax, |$\itm{var}$|
  3515. \end{lstlisting}
  3516. \end{transformation}
  3517. {\if\edition\pythonEd\pythonColor
  3518. %
  3519. Similarly, we translate the \code{print} operation, shown below, into
  3520. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3521. In x86, the first six arguments to functions are passed in registers,
  3522. with the first argument passed in register \code{rdi}. So we move the
  3523. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3524. \code{callq} instruction.
  3525. \begin{transformation}
  3526. \begin{lstlisting}
  3527. print(|$\Atm$|)
  3528. \end{lstlisting}
  3529. \compilesto
  3530. \begin{lstlisting}
  3531. movq |$\Arg$|, %rdi
  3532. callq print_int
  3533. \end{lstlisting}
  3534. \end{transformation}
  3535. %
  3536. \fi}
  3537. {\if\edition\racketEd
  3538. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3539. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3540. assignment to the \key{rax} register followed by a jump to the
  3541. conclusion of the program (so the conclusion needs to be labeled).
  3542. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3543. recursively and then append the resulting instructions.
  3544. \fi}
  3545. {\if\edition\pythonEd\pythonColor
  3546. We recommend that you use the function \code{utils.label\_name} to
  3547. transform strings into labels, for example, in
  3548. the target of the \code{callq} instruction. This practice makes your
  3549. compiler portable across Linux and Mac OS X, which requires an underscore
  3550. prefixed to all labels.
  3551. \fi}
  3552. \begin{exercise}
  3553. \normalfont\normalsize
  3554. {\if\edition\racketEd
  3555. Implement the \code{select\_instructions} pass in
  3556. \code{compiler.rkt}. Create three new example programs that are
  3557. designed to exercise all the interesting cases in this pass.
  3558. %
  3559. In the \code{run-tests.rkt} script, add the following entry to the
  3560. list of \code{passes} and then run the script to test your compiler.
  3561. \begin{lstlisting}
  3562. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3563. \end{lstlisting}
  3564. \fi}
  3565. {\if\edition\pythonEd\pythonColor
  3566. Implement the \key{select\_instructions} pass in
  3567. \code{compiler.py}. Create three new example programs that are
  3568. designed to exercise all the interesting cases in this pass.
  3569. Run the \code{run-tests.py} script to check
  3570. whether the output programs produce the same result as the input
  3571. programs.
  3572. \fi}
  3573. \end{exercise}
  3574. \section{Assign Homes}
  3575. \label{sec:assign-Lvar}
  3576. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3577. \LangXVar{} programs that no longer use program variables. Thus, the
  3578. \code{assign\_homes} pass is responsible for placing all the program
  3579. variables in registers or on the stack. For runtime efficiency, it is
  3580. better to place variables in registers, but because there are only
  3581. sixteen registers, some programs must necessarily resort to placing
  3582. some variables on the stack. In this chapter we focus on the mechanics
  3583. of placing variables on the stack. We study an algorithm for placing
  3584. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3585. Consider again the following \LangVar{} program from
  3586. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3587. % var_test_20.rkt
  3588. \begin{minipage}{0.96\textwidth}
  3589. {\if\edition\racketEd
  3590. \begin{lstlisting}
  3591. (let ([a 42])
  3592. (let ([b a])
  3593. b))
  3594. \end{lstlisting}
  3595. \fi}
  3596. {\if\edition\pythonEd\pythonColor
  3597. \begin{lstlisting}
  3598. a = 42
  3599. b = a
  3600. print(b)
  3601. \end{lstlisting}
  3602. \fi}
  3603. \end{minipage}\\
  3604. %
  3605. The output of \code{select\_instructions} is shown next, on the left,
  3606. and the output of \code{assign\_homes} is on the right. In this
  3607. example, we assign variable \code{a} to stack location
  3608. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3609. \begin{transformation}
  3610. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3611. movq $42, a
  3612. movq a, b
  3613. movq b, %rax
  3614. \end{lstlisting}
  3615. \compilesto
  3616. %stack-space: 16
  3617. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3618. movq $42, -8(%rbp)
  3619. movq -8(%rbp), -16(%rbp)
  3620. movq -16(%rbp), %rax
  3621. \end{lstlisting}
  3622. \end{transformation}
  3623. \racket{
  3624. The \code{assign\_homes} pass should replace all variables
  3625. with stack locations.
  3626. The list of variables can be obtained from
  3627. the \code{locals-types} entry in the $\itm{info}$ of the
  3628. \code{X86Program} node. The \code{locals-types} entry is an alist
  3629. mapping all the variables in the program to their types
  3630. (for now, just \code{Integer}).
  3631. As an aside, the \code{locals-types} entry is
  3632. computed by \code{type-check-Cvar} in the support code, which
  3633. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3634. which you should propagate to the \code{X86Program} node.}
  3635. %
  3636. \python{The \code{assign\_homes} pass should replace all uses of
  3637. variables with stack locations.}
  3638. %
  3639. In the process of assigning variables to stack locations, it is
  3640. convenient for you to compute and store the size of the frame (in
  3641. bytes) in
  3642. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3643. %
  3644. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3645. %
  3646. which is needed later to generate the conclusion of the \code{main}
  3647. procedure. The x86-64 standard requires the frame size to be a
  3648. multiple of 16 bytes.\index{subject}{frame}
  3649. % TODO: store the number of variables instead? -Jeremy
  3650. \begin{exercise}\normalfont\normalsize
  3651. Implement the \code{assign\_homes} pass in
  3652. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3653. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3654. grammar. We recommend that the auxiliary functions take an extra
  3655. parameter that maps variable names to homes (stack locations for now).
  3656. %
  3657. {\if\edition\racketEd
  3658. In the \code{run-tests.rkt} script, add the following entry to the
  3659. list of \code{passes} and then run the script to test your compiler.
  3660. \begin{lstlisting}
  3661. (list "assign homes" assign-homes interp_x86-0)
  3662. \end{lstlisting}
  3663. \fi}
  3664. {\if\edition\pythonEd\pythonColor
  3665. Run the \code{run-tests.py} script to check
  3666. whether the output programs produce the same result as the input
  3667. programs.
  3668. \fi}
  3669. \end{exercise}
  3670. \section{Patch Instructions}
  3671. \label{sec:patch-s0}
  3672. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3673. \LangXInt{} by making sure that each instruction adheres to the
  3674. restriction that at most one argument of an instruction may be a
  3675. memory reference.
  3676. We return to the following example.\\
  3677. \begin{minipage}{0.5\textwidth}
  3678. % var_test_20.rkt
  3679. {\if\edition\racketEd
  3680. \begin{lstlisting}
  3681. (let ([a 42])
  3682. (let ([b a])
  3683. b))
  3684. \end{lstlisting}
  3685. \fi}
  3686. {\if\edition\pythonEd\pythonColor
  3687. \begin{lstlisting}
  3688. a = 42
  3689. b = a
  3690. print(b)
  3691. \end{lstlisting}
  3692. \fi}
  3693. \end{minipage}\\
  3694. The \code{assign\_homes} pass produces the following translation. \\
  3695. \begin{minipage}{0.5\textwidth}
  3696. {\if\edition\racketEd
  3697. \begin{lstlisting}
  3698. movq $42, -8(%rbp)
  3699. movq -8(%rbp), -16(%rbp)
  3700. movq -16(%rbp), %rax
  3701. \end{lstlisting}
  3702. \fi}
  3703. {\if\edition\pythonEd\pythonColor
  3704. \begin{lstlisting}
  3705. movq $42, -8(%rbp)
  3706. movq -8(%rbp), -16(%rbp)
  3707. movq -16(%rbp), %rdi
  3708. callq print_int
  3709. \end{lstlisting}
  3710. \fi}
  3711. \end{minipage}\\
  3712. The second \key{movq} instruction is problematic because both
  3713. arguments are stack locations. We suggest fixing this problem by
  3714. moving from the source location to the register \key{rax} and then
  3715. from \key{rax} to the destination location, as follows.
  3716. \begin{lstlisting}
  3717. movq -8(%rbp), %rax
  3718. movq %rax, -16(%rbp)
  3719. \end{lstlisting}
  3720. There is a similar corner case that also needs to be dealt with. If
  3721. one argument is an immediate integer larger than $2^{16}$ and the
  3722. other is a memory reference, then the instruction is invalid. One can
  3723. fix this, for example, by first moving the immediate integer into
  3724. \key{rax} and then using \key{rax} in place of the integer.
  3725. \begin{exercise}
  3726. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3727. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3728. Create three new example programs that are
  3729. designed to exercise all the interesting cases in this pass.
  3730. %
  3731. {\if\edition\racketEd
  3732. In the \code{run-tests.rkt} script, add the following entry to the
  3733. list of \code{passes} and then run the script to test your compiler.
  3734. \begin{lstlisting}
  3735. (list "patch instructions" patch_instructions interp_x86-0)
  3736. \end{lstlisting}
  3737. \fi}
  3738. {\if\edition\pythonEd\pythonColor
  3739. Run the \code{run-tests.py} script to check
  3740. whether the output programs produce the same result as the input
  3741. programs.
  3742. \fi}
  3743. \end{exercise}
  3744. \section{Generate Prelude and Conclusion}
  3745. \label{sec:print-x86}
  3746. \index{subject}{prelude}\index{subject}{conclusion}
  3747. The last step of the compiler from \LangVar{} to x86 is to generate
  3748. the \code{main} function with a prelude and conclusion wrapped around
  3749. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3750. discussed in section~\ref{sec:x86}.
  3751. When running on Mac OS X, your compiler should prefix an underscore to
  3752. all labels (for example, changing \key{main} to \key{\_main}).
  3753. %
  3754. \racket{The Racket call \code{(system-type 'os)} is useful for
  3755. determining which operating system the compiler is running on. It
  3756. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3757. %
  3758. \python{The Python \code{platform.system}
  3759. function returns \code{\textquotesingle Linux\textquotesingle},
  3760. \code{\textquotesingle Windows\textquotesingle}, or
  3761. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3762. \begin{exercise}\normalfont\normalsize
  3763. %
  3764. Implement the \key{prelude\_and\_conclusion} pass in
  3765. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3766. %
  3767. {\if\edition\racketEd
  3768. In the \code{run-tests.rkt} script, add the following entry to the
  3769. list of \code{passes} and then run the script to test your compiler.
  3770. \begin{lstlisting}
  3771. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3772. \end{lstlisting}
  3773. %
  3774. Uncomment the call to the \key{compiler-tests} function
  3775. (appendix~\ref{appendix:utilities}), which tests your complete
  3776. compiler by executing the generated x86 code. It translates the x86
  3777. AST that you produce into a string by invoking the \code{print-x86}
  3778. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3779. the provided \key{runtime.c} file to \key{runtime.o} using
  3780. \key{gcc}. Run the script to test your compiler.
  3781. %
  3782. \fi}
  3783. {\if\edition\pythonEd\pythonColor
  3784. %
  3785. Run the \code{run-tests.py} script to check whether the output
  3786. programs produce the same result as the input programs. That script
  3787. translates the x86 AST that you produce into a string by invoking the
  3788. \code{repr} method that is implemented by the x86 AST classes in
  3789. \code{x86\_ast.py}.
  3790. %
  3791. \fi}
  3792. \end{exercise}
  3793. \section{Challenge: Partial Evaluator for \LangVar{}}
  3794. \label{sec:pe-Lvar}
  3795. \index{subject}{partialevaluation@partial evaluation}
  3796. This section describes two optional challenge exercises that involve
  3797. adapting and improving the partial evaluator for \LangInt{} that was
  3798. introduced in section~\ref{sec:partial-evaluation}.
  3799. \begin{exercise}\label{ex:pe-Lvar}
  3800. \normalfont\normalsize
  3801. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3802. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3803. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3804. %
  3805. \racket{\key{let} binding}\python{assignment}
  3806. %
  3807. to the \LangInt{} language, so you will need to add cases for them in
  3808. the \code{pe\_exp}
  3809. %
  3810. \racket{function.}
  3811. %
  3812. \python{and \code{pe\_stmt} functions.}
  3813. %
  3814. Once complete, add the partial evaluation pass to the front of your
  3815. compiler, and check that your compiler still passes all the
  3816. tests.
  3817. \end{exercise}
  3818. \begin{exercise}
  3819. \normalfont\normalsize
  3820. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3821. \code{pe\_add} auxiliary functions with functions that know more about
  3822. arithmetic. For example, your partial evaluator should translate
  3823. {\if\edition\racketEd
  3824. \[
  3825. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3826. \code{(+ 2 (read))}
  3827. \]
  3828. \fi}
  3829. {\if\edition\pythonEd\pythonColor
  3830. \[
  3831. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3832. \code{2 + input\_int()}
  3833. \]
  3834. \fi}
  3835. %
  3836. To accomplish this, the \code{pe\_exp} function should produce output
  3837. in the form of the $\itm{residual}$ nonterminal of the following
  3838. grammar. The idea is that when processing an addition expression, we
  3839. can always produce one of the following: (1) an integer constant, (2)
  3840. an addition expression with an integer constant on the left-hand side
  3841. but not the right-hand side, or (3) an addition expression in which
  3842. neither subexpression is a constant.
  3843. %
  3844. {\if\edition\racketEd
  3845. \[
  3846. \begin{array}{lcl}
  3847. \itm{inert} &::=& \Var
  3848. \MID \LP\key{read}\RP
  3849. \MID \LP\key{-} ~\Var\RP
  3850. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3851. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3852. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3853. \itm{residual} &::=& \Int
  3854. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3855. \MID \itm{inert}
  3856. \end{array}
  3857. \]
  3858. \fi}
  3859. {\if\edition\pythonEd\pythonColor
  3860. \[
  3861. \begin{array}{lcl}
  3862. \itm{inert} &::=& \Var
  3863. \MID \key{input\_int}\LP\RP
  3864. \MID \key{-} \Var
  3865. \MID \key{-} \key{input\_int}\LP\RP
  3866. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3867. \itm{residual} &::=& \Int
  3868. \MID \Int ~ \key{+} ~ \itm{inert}
  3869. \MID \itm{inert}
  3870. \end{array}
  3871. \]
  3872. \fi}
  3873. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3874. inputs are $\itm{residual}$ expressions and they should return
  3875. $\itm{residual}$ expressions. Once the improvements are complete,
  3876. make sure that your compiler still passes all the tests. After
  3877. all, fast code is useless if it produces incorrect results!
  3878. \end{exercise}
  3879. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3880. {\if\edition\pythonEd\pythonColor
  3881. \chapter{Parsing}
  3882. \label{ch:parsing}
  3883. \setcounter{footnote}{0}
  3884. \index{subject}{parsing}
  3885. In this chapter we learn how to use the Lark parser
  3886. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3887. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3888. You are then asked to create a parser for \LangVar{} using Lark.
  3889. We also describe the parsing algorithms used inside Lark, studying the
  3890. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3891. A parser framework such as Lark takes in a specification of the
  3892. concrete syntax and an input program and produces a parse tree. Even
  3893. though a parser framework does most of the work for us, using one
  3894. properly requires some knowledge. In particular, we must learn about
  3895. its specification languages and we must learn how to deal with
  3896. ambiguity in our language specifications. Also, some algorithms, such
  3897. as LALR(1), place restrictions on the grammars they can handle, in
  3898. which case knowing the algorithm helps with trying to decipher the
  3899. error messages.
  3900. The process of parsing is traditionally subdivided into two phases:
  3901. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3902. analysis} (also called parsing). The lexical analysis phase
  3903. translates the sequence of characters into a sequence of
  3904. \emph{tokens}, that is, words consisting of several characters. The
  3905. parsing phase organizes the tokens into a \emph{parse tree} that
  3906. captures how the tokens were matched by rules in the grammar of the
  3907. language. The reason for the subdivision into two phases is to enable
  3908. the use of a faster but less powerful algorithm for lexical analysis
  3909. and the use of a slower but more powerful algorithm for parsing.
  3910. %
  3911. %% Likewise, parser generators typical come in pairs, with separate
  3912. %% generators for the lexical analyzer (or lexer for short) and for the
  3913. %% parser. A particularly influential pair of generators were
  3914. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3915. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3916. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3917. %% Compiler Compiler.
  3918. %
  3919. The Lark parser framework that we use in this chapter includes both
  3920. lexical analyzers and parsers. The next section discusses lexical
  3921. analysis, and the remainder of the chapter discusses parsing.
  3922. \section{Lexical Analysis and Regular Expressions}
  3923. \label{sec:lex}
  3924. The lexical analyzers produced by Lark turn a sequence of characters
  3925. (a string) into a sequence of token objects. For example, a Lark
  3926. generated lexer for \LangInt{} converts the string
  3927. \begin{lstlisting}
  3928. 'print(1 + 3)'
  3929. \end{lstlisting}
  3930. \noindent into the following sequence of token objects:
  3931. \begin{center}
  3932. \begin{minipage}{0.95\textwidth}
  3933. \begin{lstlisting}
  3934. Token('PRINT', 'print')
  3935. Token('LPAR', '(')
  3936. Token('INT', '1')
  3937. Token('PLUS', '+')
  3938. Token('INT', '3')
  3939. Token('RPAR', ')')
  3940. Token('NEWLINE', '\n')
  3941. \end{lstlisting}
  3942. \end{minipage}
  3943. \end{center}
  3944. Each token includes a field for its \code{type}, such as \skey{INT},
  3945. and a field for its \code{value}, such as \skey{1}.
  3946. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3947. specification language for Lark's lexer is one regular expression for
  3948. each type of token. The term \emph{regular} comes from the term
  3949. \emph{regular languages}, which are the languages that can be
  3950. recognized by a finite state machine. A \emph{regular expression} is a
  3951. pattern formed of the following core elements:\index{subject}{regular
  3952. expression}\footnote{Regular expressions traditionally include the
  3953. empty regular expression that matches any zero-length part of a
  3954. string, but Lark does not support the empty regular expression.}
  3955. \begin{itemize}
  3956. \item A single character $c$ is a regular expression, and it matches
  3957. only itself. For example, the regular expression \code{a} matches
  3958. only the string \skey{a}.
  3959. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3960. R_2$ form a regular expression that matches any string that matches
  3961. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3962. matches the string \skey{a} and the string \skey{c}.
  3963. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3964. expression that matches any string that can be formed by
  3965. concatenating two strings, where the first string matches $R_1$ and
  3966. the second string matches $R_2$. For example, the regular expression
  3967. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3968. (Parentheses can be used to control the grouping of operators within
  3969. a regular expression.)
  3970. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3971. Kleene closure) is a regular expression that matches any string that
  3972. can be formed by concatenating zero or more strings that each match
  3973. the regular expression $R$. For example, the regular expression
  3974. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3975. \skey{abc}.
  3976. \end{itemize}
  3977. For our convenience, Lark also accepts the following extended set of
  3978. regular expressions that are automatically translated into the core
  3979. regular expressions.
  3980. \begin{itemize}
  3981. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3982. c_n]$ is a regular expression that matches any one of the
  3983. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3984. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3985. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3986. a regular expression that matches any character between $c_1$ and
  3987. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3988. letter in the alphabet.
  3989. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3990. is a regular expression that matches any string that can
  3991. be formed by concatenating one or more strings that each match $R$.
  3992. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3993. matches \skey{b} and \skey{bzca}.
  3994. \item A regular expression followed by a question mark $R\ttm{?}$
  3995. is a regular expression that matches any string that either
  3996. matches $R$ or is the empty string.
  3997. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3998. \end{itemize}
  3999. In a Lark grammar file, each kind of token is specified by a
  4000. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4001. that consists of the name of the terminal followed by a colon followed
  4002. by a sequence of literals. The literals include strings such as
  4003. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4004. terminal names, and literals composed using the regular expression
  4005. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4006. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4007. \begin{center}
  4008. \begin{minipage}{0.95\textwidth}
  4009. \begin{lstlisting}
  4010. DIGIT: /[0-9]/
  4011. INT: "-"? DIGIT+
  4012. NEWLINE: (/\r/? /\n/)+
  4013. \end{lstlisting}
  4014. \end{minipage}
  4015. \end{center}
  4016. \section{Grammars and Parse Trees}
  4017. \label{sec:CFG}
  4018. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4019. specify the abstract syntax of a language. We now take a closer look
  4020. at using grammar rules to specify the concrete syntax. Recall that
  4021. each rule has a left-hand side and a right-hand side, where the
  4022. left-hand side is a nonterminal and the right-hand side is a pattern
  4023. that defines what can be parsed as that nonterminal. For concrete
  4024. syntax, each right-hand side expresses a pattern for a string instead
  4025. of a pattern for an abstract syntax tree. In particular, each
  4026. right-hand side is a sequence of
  4027. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4028. terminal or a nonterminal. The nonterminals play the same role as in
  4029. the abstract syntax, defining categories of syntax. The nonterminals
  4030. of a grammar include the tokens defined in the lexer and all the
  4031. nonterminals defined by the grammar rules.
  4032. As an example, let us take a closer look at the concrete syntax of the
  4033. \LangInt{} language, repeated here.
  4034. \[
  4035. \begin{array}{l}
  4036. \LintGrammarPython \\
  4037. \begin{array}{rcl}
  4038. \LangInt{} &::=& \Stmt^{*}
  4039. \end{array}
  4040. \end{array}
  4041. \]
  4042. The Lark syntax for grammar rules differs slightly from the variant of
  4043. BNF that we use in this book. In particular, the notation $::=$ is
  4044. replaced by a single colon, and the use of typewriter font for string
  4045. literals is replaced by quotation marks. The following grammar serves
  4046. as a first draft of a Lark grammar for \LangInt{}.
  4047. \begin{center}
  4048. \begin{minipage}{0.95\textwidth}
  4049. \begin{lstlisting}[escapechar=$]
  4050. exp: INT
  4051. | "input_int" "(" ")"
  4052. | "-" exp
  4053. | exp "+" exp
  4054. | exp "-" exp
  4055. | "(" exp ")"
  4056. stmt_list:
  4057. | stmt NEWLINE stmt_list
  4058. lang_int: stmt_list
  4059. \end{lstlisting}
  4060. \end{minipage}
  4061. \end{center}
  4062. Let us begin by discussing the rule \code{exp: INT}, which says that
  4063. if the lexer matches a string to \code{INT}, then the parser also
  4064. categorizes the string as an \code{exp}. Recall that in
  4065. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4066. nonterminal with a sentence in English. Here we specify \code{INT}
  4067. more formally using a type of token \code{INT} and its regular
  4068. expression \code{"-"? DIGIT+}.
  4069. The rule \code{exp: exp "+" exp} says that any string that matches
  4070. \code{exp}, followed by the \code{+} character, followed by another
  4071. string that matches \code{exp}, is itself an \code{exp}. For example,
  4072. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4073. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4074. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4075. \code{exp}. We can visualize the application of grammar rules to parse
  4076. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4077. internal node in the tree is an application of a grammar rule and is
  4078. labeled with its left-hand side nonterminal. Each leaf node is a
  4079. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4080. shown in figure~\ref{fig:simple-parse-tree}.
  4081. \begin{figure}[tbp]
  4082. \begin{tcolorbox}[colback=white]
  4083. \centering
  4084. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4085. \end{tcolorbox}
  4086. \caption{The parse tree for \lstinline{'1+3'}.}
  4087. \label{fig:simple-parse-tree}
  4088. \end{figure}
  4089. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4090. following parse tree as represented by \code{Tree} and \code{Token}
  4091. objects.
  4092. \begin{lstlisting}
  4093. Tree('lang_int',
  4094. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4095. Tree('exp', [Token('INT', '3')])])]),
  4096. Token('NEWLINE', '\n')])
  4097. \end{lstlisting}
  4098. The nodes that come from the lexer are \code{Token} objects, whereas
  4099. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4100. object has a \code{data} field containing the name of the nonterminal
  4101. for the grammar rule that was applied. Each \code{Tree} object also
  4102. has a \code{children} field that is a list containing trees and/or
  4103. tokens. Note that Lark does not produce nodes for string literals in
  4104. the grammar. For example, the \code{Tree} node for the addition
  4105. expression has only two children for the two integers but is missing
  4106. its middle child for the \code{"+"} terminal. This would be
  4107. problematic except that Lark provides a mechanism for customizing the
  4108. \code{data} field of each \code{Tree} node on the basis of which rule was
  4109. applied. Next to each alternative in a grammar rule, write \code{->}
  4110. followed by a string that you want to appear in the \code{data}
  4111. field. The following is a second draft of a Lark grammar for
  4112. \LangInt{}, this time with more specific labels on the \code{Tree}
  4113. nodes.
  4114. \begin{center}
  4115. \begin{minipage}{0.95\textwidth}
  4116. \begin{lstlisting}[escapechar=$]
  4117. exp: INT -> int
  4118. | "input_int" "(" ")" -> input_int
  4119. | "-" exp -> usub
  4120. | exp "+" exp -> add
  4121. | exp "-" exp -> sub
  4122. | "(" exp ")" -> paren
  4123. stmt: "print" "(" exp ")" -> print
  4124. | exp -> expr
  4125. stmt_list: -> empty_stmt
  4126. | stmt NEWLINE stmt_list -> add_stmt
  4127. lang_int: stmt_list -> module
  4128. \end{lstlisting}
  4129. \end{minipage}
  4130. \end{center}
  4131. Here is the resulting parse tree.
  4132. \begin{lstlisting}
  4133. Tree('module',
  4134. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4135. Tree('int', [Token('INT', '3')])])]),
  4136. Token('NEWLINE', '\n')])
  4137. \end{lstlisting}
  4138. \section{Ambiguous Grammars}
  4139. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4140. can be parsed in more than one way. For example, consider the string
  4141. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4142. our draft grammar, resulting in the two parse trees shown in
  4143. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4144. interpreting the second parse tree would yield \code{-4} even through
  4145. the correct answer is \code{2}.
  4146. \begin{figure}[tbp]
  4147. \begin{tcolorbox}[colback=white]
  4148. \centering
  4149. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4150. \end{tcolorbox}
  4151. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4152. \label{fig:ambig-parse-tree}
  4153. \end{figure}
  4154. To deal with this problem we can change the grammar by categorizing
  4155. the syntax in a more fine-grained fashion. In this case we want to
  4156. disallow the application of the rule \code{exp: exp "-" exp} when the
  4157. child on the right is an addition. To do this we can replace the
  4158. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4159. the expressions except for addition, as in the following.
  4160. \begin{center}
  4161. \begin{minipage}{0.95\textwidth}
  4162. \begin{lstlisting}[escapechar=$]
  4163. exp: exp "-" exp_no_add -> sub
  4164. | exp "+" exp -> add
  4165. | exp_no_add
  4166. exp_no_add: INT -> int
  4167. | "input_int" "(" ")" -> input_int
  4168. | "-" exp -> usub
  4169. | exp "-" exp_no_add -> sub
  4170. | "(" exp ")" -> paren
  4171. \end{lstlisting}
  4172. \end{minipage}
  4173. \end{center}
  4174. However, there remains some ambiguity in the grammar. For example, the
  4175. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4176. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4177. (incorrect). That is, subtraction is left associative. Likewise,
  4178. addition in Python is left associative. We also need to consider the
  4179. interaction of unary subtraction with both addition and
  4180. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4181. has higher \emph{precedence}\index{subject}{precedence} than addition
  4182. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4183. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4184. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4185. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4186. all the other expressions, and it uses \code{exp\_hi} for the second
  4187. child in the rules for addition and subtraction. Furthermore, unary
  4188. subtraction uses \code{exp\_hi} for its child.
  4189. For languages with more operators and more precedence levels, one must
  4190. refine the \code{exp} nonterminal into several nonterminals, one for
  4191. each precedence level.
  4192. \begin{figure}[tbp]
  4193. \begin{tcolorbox}[colback=white]
  4194. \centering
  4195. \begin{lstlisting}[escapechar=$]
  4196. exp: exp "+" exp_hi -> add
  4197. | exp "-" exp_hi -> sub
  4198. | exp_hi
  4199. exp_hi: INT -> int
  4200. | "input_int" "(" ")" -> input_int
  4201. | "-" exp_hi -> usub
  4202. | "(" exp ")" -> paren
  4203. stmt: "print" "(" exp ")" -> print
  4204. | exp -> expr
  4205. stmt_list: -> empty_stmt
  4206. | stmt NEWLINE stmt_list -> add_stmt
  4207. lang_int: stmt_list -> module
  4208. \end{lstlisting}
  4209. \end{tcolorbox}
  4210. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4211. \label{fig:Lint-lark-grammar}
  4212. \end{figure}
  4213. \section{From Parse Trees to Abstract Syntax Trees}
  4214. As we have seen, the output of a Lark parser is a parse tree, that is,
  4215. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4216. step is to convert the parse tree to an abstract syntax tree. This can
  4217. be accomplished with a recursive function that inspects the
  4218. \code{data} field of each node and then constructs the corresponding
  4219. AST node, using recursion to handle its children. The following is an
  4220. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4221. \begin{center}
  4222. \begin{minipage}{0.95\textwidth}
  4223. \begin{lstlisting}
  4224. def parse_tree_to_ast(e):
  4225. if e.data == 'int':
  4226. return Constant(int(e.children[0].value))
  4227. elif e.data == 'input_int':
  4228. return Call(Name('input_int'), [])
  4229. elif e.data == 'add':
  4230. e1, e2 = e.children
  4231. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4232. ...
  4233. else:
  4234. raise Exception('unhandled parse tree', e)
  4235. \end{lstlisting}
  4236. \end{minipage}
  4237. \end{center}
  4238. \begin{exercise}
  4239. \normalfont\normalsize
  4240. %
  4241. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4242. default parsing algorithm (Earley) with the \code{ambiguity} option
  4243. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4244. output will include multiple parse trees that will indicate to you
  4245. that there is a problem with your grammar. Your parser should ignore
  4246. white space, so we recommend using Lark's \code{\%ignore} directive
  4247. as follows.
  4248. \begin{lstlisting}
  4249. WS: /[ \t\f\r\n]/+
  4250. %ignore WS
  4251. \end{lstlisting}
  4252. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4253. Lark parser instead of using the \code{parse} function from
  4254. the \code{ast} module. Test your compiler on all the \LangVar{}
  4255. programs that you have created, and create four additional programs
  4256. that test for ambiguities in your grammar.
  4257. \end{exercise}
  4258. \section{Earley's Algorithm}
  4259. \label{sec:earley}
  4260. In this section we discuss the parsing algorithm of
  4261. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4262. algorithm is powerful in that it can handle any context-free grammar,
  4263. which makes it easy to use, but it is not a particularly
  4264. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4265. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4266. the number of tokens in the input
  4267. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4268. learn about the LALR(1) algorithm, which is more efficient but cannot
  4269. handle all context-free grammars.
  4270. Earley's algorithm can be viewed as an interpreter; it treats the
  4271. grammar as the program being interpreted, and it treats the concrete
  4272. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4273. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4274. keep track of its progress and to store its results. The chart is an
  4275. array with one slot for each position in the input string, where
  4276. position $0$ is before the first character and position $n$ is
  4277. immediately after the last character. So, the array has length $n+1$
  4278. for an input string of length $n$. Each slot in the chart contains a
  4279. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4280. with a period indicating how much of its right-hand side has already
  4281. been parsed. For example, the dotted rule
  4282. \begin{lstlisting}
  4283. exp: exp "+" . exp_hi
  4284. \end{lstlisting}
  4285. represents a partial parse that has matched an \code{exp} followed by
  4286. \code{+} but has not yet parsed an \code{exp} to the right of
  4287. \code{+}.
  4288. %
  4289. Earley's algorithm starts with an initialization phase and then
  4290. repeats three actions---prediction, scanning, and completion---for as
  4291. long as opportunities arise. We demonstrate Earley's algorithm on a
  4292. running example, parsing the following program:
  4293. \begin{lstlisting}
  4294. print(1 + 3)
  4295. \end{lstlisting}
  4296. The algorithm's initialization phase creates dotted rules for all the
  4297. grammar rules whose left-hand side is the start symbol and places them
  4298. in slot $0$ of the chart. We also record the starting position of the
  4299. dotted rule in parentheses on the right. For example, given the
  4300. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4301. \begin{lstlisting}
  4302. lang_int: . stmt_list (0)
  4303. \end{lstlisting}
  4304. in slot $0$ of the chart. The algorithm then proceeds with
  4305. \emph{prediction} actions in which it adds more dotted rules to the
  4306. chart based on the nonterminals that come immediately after a period. In
  4307. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4308. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4309. period at the beginning of their right-hand sides, as follows:
  4310. \begin{lstlisting}
  4311. stmt_list: . (0)
  4312. stmt_list: . stmt NEWLINE stmt_list (0)
  4313. \end{lstlisting}
  4314. We continue to perform prediction actions as more opportunities
  4315. arise. For example, the \code{stmt} nonterminal now appears after a
  4316. period, so we add all the rules for \code{stmt}.
  4317. \begin{lstlisting}
  4318. stmt: . "print" "(" exp ")" (0)
  4319. stmt: . exp (0)
  4320. \end{lstlisting}
  4321. This reveals yet more opportunities for prediction, so we add the grammar
  4322. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4323. \begin{lstlisting}[escapechar=$]
  4324. exp: . exp "+" exp_hi (0)
  4325. exp: . exp "-" exp_hi (0)
  4326. exp: . exp_hi (0)
  4327. exp_hi: . INT (0)
  4328. exp_hi: . "input_int" "(" ")" (0)
  4329. exp_hi: . "-" exp_hi (0)
  4330. exp_hi: . "(" exp ")" (0)
  4331. \end{lstlisting}
  4332. We have exhausted the opportunities for prediction, so the algorithm
  4333. proceeds to \emph{scanning}, in which we inspect the next input token
  4334. and look for a dotted rule at the current position that has a matching
  4335. terminal immediately following the period. In our running example, the
  4336. first input token is \code{"print"}, so we identify the rule in slot
  4337. $0$ of the chart where \code{"print"} follows the period:
  4338. \begin{lstlisting}
  4339. stmt: . "print" "(" exp ")" (0)
  4340. \end{lstlisting}
  4341. We advance the period past \code{"print"} and add the resulting rule
  4342. to slot $1$:
  4343. \begin{lstlisting}
  4344. stmt: "print" . "(" exp ")" (0)
  4345. \end{lstlisting}
  4346. If the new dotted rule had a nonterminal after the period, we would
  4347. need to carry out a prediction action, adding more dotted rules to
  4348. slot $1$. That is not the case, so we continue scanning. The next
  4349. input token is \code{"("}, so we add the following to slot $2$ of the
  4350. chart.
  4351. \begin{lstlisting}
  4352. stmt: "print" "(" . exp ")" (0)
  4353. \end{lstlisting}
  4354. Now we have a nonterminal after the period, so we carry out several
  4355. prediction actions, adding dotted rules for \code{exp} and
  4356. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4357. starting position $2$.
  4358. \begin{lstlisting}[escapechar=$]
  4359. exp: . exp "+" exp_hi (2)
  4360. exp: . exp "-" exp_hi (2)
  4361. exp: . exp_hi (2)
  4362. exp_hi: . INT (2)
  4363. exp_hi: . "input_int" "(" ")" (2)
  4364. exp_hi: . "-" exp_hi (2)
  4365. exp_hi: . "(" exp ")" (2)
  4366. \end{lstlisting}
  4367. With this prediction complete, we return to scanning, noting that the
  4368. next input token is \code{"1"}, which the lexer parses as an
  4369. \code{INT}. There is a matching rule in slot $2$:
  4370. \begin{lstlisting}
  4371. exp_hi: . INT (2)
  4372. \end{lstlisting}
  4373. so we advance the period and put the following rule into slot $3$.
  4374. \begin{lstlisting}
  4375. exp_hi: INT . (2)
  4376. \end{lstlisting}
  4377. This brings us to \emph{completion} actions. When the period reaches
  4378. the end of a dotted rule, we recognize that the substring
  4379. has matched the nonterminal on the left-hand side of the rule, in this case
  4380. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4381. rules into slot $2$ (the starting position for the finished rule) if
  4382. the period is immediately followed by \code{exp\_hi}. So we identify
  4383. \begin{lstlisting}
  4384. exp: . exp_hi (2)
  4385. \end{lstlisting}
  4386. and add the following dotted rule to slot $3$
  4387. \begin{lstlisting}
  4388. exp: exp_hi . (2)
  4389. \end{lstlisting}
  4390. This triggers another completion step for the nonterminal \code{exp},
  4391. adding two more dotted rules to slot $3$.
  4392. \begin{lstlisting}[escapechar=$]
  4393. exp: exp . "+" exp_hi (2)
  4394. exp: exp . "-" exp_hi (2)
  4395. \end{lstlisting}
  4396. Returning to scanning, the next input token is \code{"+"}, so
  4397. we add the following to slot $4$.
  4398. \begin{lstlisting}[escapechar=$]
  4399. exp: exp "+" . exp_hi (2)
  4400. \end{lstlisting}
  4401. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4402. the following dotted rules to slot $4$ of the chart.
  4403. \begin{lstlisting}[escapechar=$]
  4404. exp_hi: . INT (4)
  4405. exp_hi: . "input_int" "(" ")" (4)
  4406. exp_hi: . "-" exp_hi (4)
  4407. exp_hi: . "(" exp ")" (4)
  4408. \end{lstlisting}
  4409. The next input token is \code{"3"} which the lexer categorized as an
  4410. \code{INT}, so we advance the period past \code{INT} for the rules in
  4411. slot $4$, of which there is just one, and put the following into slot $5$.
  4412. \begin{lstlisting}[escapechar=$]
  4413. exp_hi: INT . (4)
  4414. \end{lstlisting}
  4415. The period at the end of the rule triggers a completion action for the
  4416. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4417. So we advance the period and put the following into slot $5$.
  4418. \begin{lstlisting}[escapechar=$]
  4419. exp: exp "+" exp_hi . (2)
  4420. \end{lstlisting}
  4421. This triggers another completion action for the rules in slot $2$ that
  4422. have a period before \code{exp}.
  4423. \begin{lstlisting}[escapechar=$]
  4424. stmt: "print" "(" exp . ")" (0)
  4425. exp: exp . "+" exp_hi (2)
  4426. exp: exp . "-" exp_hi (2)
  4427. \end{lstlisting}
  4428. We scan the next input token \code{")"}, placing the following dotted
  4429. rule into slot $6$.
  4430. \begin{lstlisting}[escapechar=$]
  4431. stmt: "print" "(" exp ")" . (0)
  4432. \end{lstlisting}
  4433. This triggers the completion of \code{stmt} in slot $0$
  4434. \begin{lstlisting}
  4435. stmt_list: stmt . NEWLINE stmt_list (0)
  4436. \end{lstlisting}
  4437. The last input token is a \code{NEWLINE}, so we advance the period
  4438. and place the new dotted rule into slot $7$.
  4439. \begin{lstlisting}
  4440. stmt_list: stmt NEWLINE . stmt_list (0)
  4441. \end{lstlisting}
  4442. We are close to the end of parsing the input!
  4443. The period is before the \code{stmt\_list} nonterminal, so we
  4444. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4445. \begin{lstlisting}
  4446. stmt_list: . (7)
  4447. stmt_list: . stmt NEWLINE stmt_list (7)
  4448. stmt: . "print" "(" exp ")" (7)
  4449. stmt: . exp (7)
  4450. \end{lstlisting}
  4451. There is immediately an opportunity for completion of \code{stmt\_list},
  4452. so we add the following to slot $7$.
  4453. \begin{lstlisting}
  4454. stmt_list: stmt NEWLINE stmt_list . (0)
  4455. \end{lstlisting}
  4456. This triggers another completion action for \code{stmt\_list} in slot $0$
  4457. \begin{lstlisting}
  4458. lang_int: stmt_list . (0)
  4459. \end{lstlisting}
  4460. which in turn completes \code{lang\_int}, the start symbol of the
  4461. grammar, so the parsing of the input is complete.
  4462. For reference, we give a general description of Earley's
  4463. algorithm.
  4464. \begin{enumerate}
  4465. \item The algorithm begins by initializing slot $0$ of the chart with the
  4466. grammar rule for the start symbol, placing a period at the beginning
  4467. of the right-hand side, and recording its starting position as $0$.
  4468. \item The algorithm repeatedly applies the following three kinds of
  4469. actions for as long as there are opportunities to do so.
  4470. \begin{itemize}
  4471. \item Prediction: If there is a rule in slot $k$ whose period comes
  4472. before a nonterminal, add the rules for that nonterminal into slot
  4473. $k$, placing a period at the beginning of their right-hand sides
  4474. and recording their starting position as $k$.
  4475. \item Scanning: If the token at position $k$ of the input string
  4476. matches the symbol after the period in a dotted rule in slot $k$
  4477. of the chart, advance the period in the dotted rule, adding
  4478. the result to slot $k+1$.
  4479. \item Completion: If a dotted rule in slot $k$ has a period at the
  4480. end, inspect the rules in the slot corresponding to the starting
  4481. position of the completed rule. If any of those rules have a
  4482. nonterminal following their period that matches the left-hand side
  4483. of the completed rule, then advance their period, placing the new
  4484. dotted rule in slot $k$.
  4485. \end{itemize}
  4486. While repeating these three actions, take care never to add
  4487. duplicate dotted rules to the chart.
  4488. \end{enumerate}
  4489. We have described how Earley's algorithm recognizes that an input
  4490. string matches a grammar, but we have not described how it builds a
  4491. parse tree. The basic idea is simple, but building parse trees in an
  4492. efficient way is more complex, requiring a data structure called a
  4493. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4494. to attach a partial parse tree to every dotted rule in the chart.
  4495. Initially, the node associated with a dotted rule has no
  4496. children. As the period moves to the right, the nodes from the
  4497. subparses are added as children to the node.
  4498. As mentioned at the beginning of this section, Earley's algorithm is
  4499. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4500. files that contain thousands of tokens in a reasonable amount of time,
  4501. but not millions.
  4502. %
  4503. In the next section we discuss the LALR(1) parsing algorithm, which is
  4504. efficient enough to use with even the largest of input files.
  4505. \section{The LALR(1) Algorithm}
  4506. \label{sec:lalr}
  4507. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4508. two-phase approach in which it first compiles the grammar into a state
  4509. machine and then runs the state machine to parse an input string. The
  4510. second phase has time complexity $O(n)$ where $n$ is the number of
  4511. tokens in the input, so LALR(1) is the best one could hope for with
  4512. respect to efficiency.
  4513. %
  4514. A particularly influential implementation of LALR(1) is the
  4515. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4516. \texttt{yacc} stands for ``yet another compiler compiler.''
  4517. %
  4518. The LALR(1) state machine uses a stack to record its progress in
  4519. parsing the input string. Each element of the stack is a pair: a
  4520. state number and a grammar symbol (a terminal or a nonterminal). The
  4521. symbol characterizes the input that has been parsed so far, and the
  4522. state number is used to remember how to proceed once the next
  4523. symbol's worth of input has been parsed. Each state in the machine
  4524. represents where the parser stands in the parsing process with respect
  4525. to certain grammar rules. In particular, each state is associated with
  4526. a set of dotted rules.
  4527. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4528. (also called parse table) for the following simple but ambiguous
  4529. grammar:
  4530. \begin{lstlisting}[escapechar=$]
  4531. exp: INT
  4532. | exp "+" exp
  4533. stmt: "print" exp
  4534. start: stmt
  4535. \end{lstlisting}
  4536. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4537. read in a \lstinline{"print"} token, so the top of the stack is
  4538. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4539. the input according to grammar rule 1, which is signified by showing
  4540. rule 1 with a period after the \code{"print"} token and before the
  4541. \code{exp} nonterminal. There are two rules that could apply next,
  4542. rules 2 and 3, so state 1 also shows those rules with a period at
  4543. the beginning of their right-hand sides. The edges between states
  4544. indicate which transitions the machine should make depending on the
  4545. next input token. So, for example, if the next input token is
  4546. \code{INT} then the parser will push \code{INT} and the target state 4
  4547. on the stack and transition to state 4. Suppose that we are now at the end
  4548. of the input. State 4 says that we should reduce by rule 3, so we pop
  4549. from the stack the same number of items as the number of symbols in
  4550. the right-hand side of the rule, in this case just one. We then
  4551. momentarily jump to the state at the top of the stack (state 1) and
  4552. then follow the goto edge that corresponds to the left-hand side of
  4553. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4554. state 3. (A slightly longer example parse is shown in
  4555. figure~\ref{fig:shift-reduce}.)
  4556. \begin{figure}[tbp]
  4557. \centering
  4558. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4559. \caption{An LALR(1) parse table and a trace of an example run.}
  4560. \label{fig:shift-reduce}
  4561. \end{figure}
  4562. In general, the algorithm works as follows. First, set the current state to
  4563. state $0$. Then repeat the following, looking at the next input token.
  4564. \begin{itemize}
  4565. \item If there there is a shift edge for the input token in the
  4566. current state, push the edge's target state and the input token onto
  4567. the stack and proceed to the edge's target state.
  4568. \item If there is a reduce action for the input token in the current
  4569. state, pop $k$ elements from the stack, where $k$ is the number of
  4570. symbols in the right-hand side of the rule being reduced. Jump to
  4571. the state at the top of the stack and then follow the goto edge for
  4572. the nonterminal that matches the left-hand side of the rule that we
  4573. are reducing by. Push the edge's target state and the nonterminal on the
  4574. stack.
  4575. \end{itemize}
  4576. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4577. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4578. algorithm does not know which action to take in this case. When a
  4579. state has both a shift and a reduce action for the same token, we say
  4580. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4581. will arise, for example, in trying to parse the input
  4582. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4583. the parser will be in state 6 and will not know whether to
  4584. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4585. to proceed by shifting the next \lstinline{+} from the input.
  4586. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4587. arises when there are two reduce actions in a state for the same
  4588. token. To understand which grammars give rise to shift/reduce and
  4589. reduce/reduce conflicts, it helps to know how the parse table is
  4590. generated from the grammar, which we discuss next.
  4591. The parse table is generated one state at a time. State 0 represents
  4592. the start of the parser. We add the grammar rule for the start symbol
  4593. to this state with a period at the beginning of the right-hand side,
  4594. similarly to the initialization phase of the Earley parser. If the
  4595. period appears immediately before another nonterminal, we add all the
  4596. rules with that nonterminal on the left-hand side. Again, we place a
  4597. period at the beginning of the right-hand side of each new
  4598. rule. This process, called \emph{state closure}, is continued
  4599. until there are no more rules to add (similarly to the prediction
  4600. actions of an Earley parser). We then examine each dotted rule in the
  4601. current state $I$. Suppose that a dotted rule has the form $A ::=
  4602. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4603. are sequences of symbols. We create a new state and call it $J$. If $X$
  4604. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4605. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4606. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4607. state $J$. We start by adding all dotted rules from state $I$ that
  4608. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4609. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4610. the period moved past the $X$. (This is analogous to completion in
  4611. Earley's algorithm.) We then perform state closure on $J$. This
  4612. process repeats until there are no more states or edges to add.
  4613. We then mark states as accepting states if they have a dotted rule
  4614. that is the start rule with a period at the end. Also, to add
  4615. the reduce actions, we look for any state containing a dotted rule
  4616. with a period at the end. Let $n$ be the rule number for this dotted
  4617. rule. We then put a reduce $n$ action into that state for every token
  4618. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4619. dotted rule with a period at the end. We therefore put a reduce by
  4620. rule 3 action into state 4 for every
  4621. token.
  4622. When inserting reduce actions, take care to spot any shift/reduce or
  4623. reduce/reduce conflicts. If there are any, abort the construction of
  4624. the parse table.
  4625. \begin{exercise}
  4626. \normalfont\normalsize
  4627. %
  4628. Working on paper, walk through the parse table generation process for
  4629. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4630. your results against the parse table shown in
  4631. figure~\ref{fig:shift-reduce}.
  4632. \end{exercise}
  4633. \begin{exercise}
  4634. \normalfont\normalsize
  4635. %
  4636. Change the parser in your compiler for \LangVar{} to set the
  4637. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4638. all the \LangVar{} programs that you have created. In doing so, Lark
  4639. may signal an error due to shift/reduce or reduce/reduce conflicts
  4640. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4641. remove those conflicts.
  4642. \end{exercise}
  4643. \section{Further Reading}
  4644. In this chapter we have just scratched the surface of the field of
  4645. parsing, with the study of a very general but less efficient algorithm
  4646. (Earley) and with a more limited but highly efficient algorithm
  4647. (LALR). There are many more algorithms and classes of grammars that
  4648. fall between these two ends of the spectrum. We recommend to the reader
  4649. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4650. Regarding lexical analysis, we have described the specification
  4651. language, which are the regular expressions, but not the algorithms
  4652. for recognizing them. In short, regular expressions can be translated
  4653. to nondeterministic finite automata, which in turn are translated to
  4654. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4655. all the details on lexical analysis.
  4656. \fi}
  4657. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4658. \chapter{Register Allocation}
  4659. \label{ch:register-allocation-Lvar}
  4660. \setcounter{footnote}{0}
  4661. \index{subject}{register allocation}
  4662. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4663. storing variables on the procedure call stack. The CPU may require tens
  4664. to hundreds of cycles to access a location on the stack, whereas
  4665. accessing a register takes only a single cycle. In this chapter we
  4666. improve the efficiency of our generated code by storing some variables
  4667. in registers. The goal of register allocation is to fit as many
  4668. variables into registers as possible. Some programs have more
  4669. variables than registers, so we cannot always map each variable to a
  4670. different register. Fortunately, it is common for different variables
  4671. to be in use during different periods of time during program
  4672. execution, and in those cases we can map multiple variables to the
  4673. same register.
  4674. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4675. example. The source program is on the left and the output of
  4676. instruction selection\index{subject}{instruction selection}
  4677. is on the right. The program is almost
  4678. completely in the x86 assembly language, but it still uses variables.
  4679. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4680. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4681. the other hand, is used only after this point, so \code{x} and
  4682. \code{z} could share the same register.
  4683. \begin{figure}
  4684. \begin{tcolorbox}[colback=white]
  4685. \begin{minipage}{0.45\textwidth}
  4686. Example \LangVar{} program:
  4687. % var_test_28.rkt
  4688. {\if\edition\racketEd
  4689. \begin{lstlisting}
  4690. (let ([v 1])
  4691. (let ([w 42])
  4692. (let ([x (+ v 7)])
  4693. (let ([y x])
  4694. (let ([z (+ x w)])
  4695. (+ z (- y)))))))
  4696. \end{lstlisting}
  4697. \fi}
  4698. {\if\edition\pythonEd\pythonColor
  4699. \begin{lstlisting}
  4700. v = 1
  4701. w = 42
  4702. x = v + 7
  4703. y = x
  4704. z = x + w
  4705. print(z + (- y))
  4706. \end{lstlisting}
  4707. \fi}
  4708. \end{minipage}
  4709. \begin{minipage}{0.45\textwidth}
  4710. After instruction selection:
  4711. {\if\edition\racketEd
  4712. \begin{lstlisting}
  4713. locals-types:
  4714. x : Integer, y : Integer,
  4715. z : Integer, t : Integer,
  4716. v : Integer, w : Integer
  4717. start:
  4718. movq $1, v
  4719. movq $42, w
  4720. movq v, x
  4721. addq $7, x
  4722. movq x, y
  4723. movq x, z
  4724. addq w, z
  4725. movq y, t
  4726. negq t
  4727. movq z, %rax
  4728. addq t, %rax
  4729. jmp conclusion
  4730. \end{lstlisting}
  4731. \fi}
  4732. {\if\edition\pythonEd\pythonColor
  4733. \begin{lstlisting}
  4734. movq $1, v
  4735. movq $42, w
  4736. movq v, x
  4737. addq $7, x
  4738. movq x, y
  4739. movq x, z
  4740. addq w, z
  4741. movq y, tmp_0
  4742. negq tmp_0
  4743. movq z, tmp_1
  4744. addq tmp_0, tmp_1
  4745. movq tmp_1, %rdi
  4746. callq print_int
  4747. \end{lstlisting}
  4748. \fi}
  4749. \end{minipage}
  4750. \end{tcolorbox}
  4751. \caption{A running example for register allocation.}
  4752. \label{fig:reg-eg}
  4753. \end{figure}
  4754. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4755. compute where a variable is in use. Once we have that information, we
  4756. compute which variables are in use at the same time, that is, which ones
  4757. \emph{interfere}\index{subject}{interfere} with each other, and
  4758. represent this relation as an undirected graph whose vertices are
  4759. variables and edges indicate when two variables interfere
  4760. (section~\ref{sec:build-interference}). We then model register
  4761. allocation as a graph coloring problem
  4762. (section~\ref{sec:graph-coloring}).
  4763. If we run out of registers despite these efforts, we place the
  4764. remaining variables on the stack, similarly to how we handled
  4765. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4766. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4767. location. The decision to spill a variable is handled as part of the
  4768. graph coloring process.
  4769. We make the simplifying assumption that each variable is assigned to
  4770. one location (a register or stack address). A more sophisticated
  4771. approach is to assign a variable to one or more locations in different
  4772. regions of the program. For example, if a variable is used many times
  4773. in short sequence and then used again only after many other
  4774. instructions, it could be more efficient to assign the variable to a
  4775. register during the initial sequence and then move it to the stack for
  4776. the rest of its lifetime. We refer the interested reader to
  4777. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4778. approach.
  4779. % discuss prioritizing variables based on how much they are used.
  4780. \section{Registers and Calling Conventions}
  4781. \label{sec:calling-conventions}
  4782. \index{subject}{calling conventions}
  4783. As we perform register allocation, we must be aware of the
  4784. \emph{calling conventions} \index{subject}{calling conventions} that
  4785. govern how function calls are performed in x86.
  4786. %
  4787. Even though \LangVar{} does not include programmer-defined functions,
  4788. our generated code includes a \code{main} function that is called by
  4789. the operating system and our generated code contains calls to the
  4790. \code{read\_int} function.
  4791. Function calls require coordination between two pieces of code that
  4792. may be written by different programmers or generated by different
  4793. compilers. Here we follow the System V calling conventions that are
  4794. used by the GNU C compiler on Linux and
  4795. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4796. %
  4797. The calling conventions include rules about how functions share the
  4798. use of registers. In particular, the caller is responsible for freeing
  4799. some registers prior to the function call for use by the callee.
  4800. These are called the \emph{caller-saved registers}
  4801. \index{subject}{caller-saved registers}
  4802. and they are
  4803. \begin{lstlisting}
  4804. rax rcx rdx rsi rdi r8 r9 r10 r11
  4805. \end{lstlisting}
  4806. On the other hand, the callee is responsible for preserving the values
  4807. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4808. which are
  4809. \begin{lstlisting}
  4810. rsp rbp rbx r12 r13 r14 r15
  4811. \end{lstlisting}
  4812. We can think about this caller/callee convention from two points of
  4813. view, the caller view and the callee view, as follows:
  4814. \begin{itemize}
  4815. \item The caller should assume that all the caller-saved registers get
  4816. overwritten with arbitrary values by the callee. On the other hand,
  4817. the caller can safely assume that all the callee-saved registers
  4818. retain their original values.
  4819. \item The callee can freely use any of the caller-saved registers.
  4820. However, if the callee wants to use a callee-saved register, the
  4821. callee must arrange to put the original value back in the register
  4822. prior to returning to the caller. This can be accomplished by saving
  4823. the value to the stack in the prelude of the function and restoring
  4824. the value in the conclusion of the function.
  4825. \end{itemize}
  4826. In x86, registers are also used for passing arguments to a function
  4827. and for the return value. In particular, the first six arguments of a
  4828. function are passed in the following six registers, in this order.
  4829. \begin{lstlisting}
  4830. rdi rsi rdx rcx r8 r9
  4831. \end{lstlisting}
  4832. We refer to these six registers are the argument-passing registers
  4833. \index{subject}{argument-passing registers}.
  4834. If there are more than six arguments, the convention is to use space
  4835. on the frame of the caller for the rest of the arguments. In
  4836. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4837. argument and the rest of the arguments, which simplifies the treatment
  4838. of efficient tail calls.
  4839. %
  4840. \racket{For now, the only function we care about is \code{read\_int},
  4841. which takes zero arguments.}
  4842. %
  4843. \python{For now, the only functions we care about are \code{read\_int}
  4844. and \code{print\_int}, which take zero and one argument, respectively.}
  4845. %
  4846. The register \code{rax} is used for the return value of a function.
  4847. The next question is how these calling conventions impact register
  4848. allocation. Consider the \LangVar{} program presented in
  4849. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4850. example from the caller point of view and then from the callee point
  4851. of view. We refer to a variable that is in use during a function call
  4852. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4853. The program makes two calls to \READOP{}. The variable \code{x} is
  4854. call-live because it is in use during the second call to \READOP{}; we
  4855. must ensure that the value in \code{x} does not get overwritten during
  4856. the call to \READOP{}. One obvious approach is to save all the values
  4857. that reside in caller-saved registers to the stack prior to each
  4858. function call and to restore them after each call. That way, if the
  4859. register allocator chooses to assign \code{x} to a caller-saved
  4860. register, its value will be preserved across the call to \READOP{}.
  4861. However, saving and restoring to the stack is relatively slow. If
  4862. \code{x} is not used many times, it may be better to assign \code{x}
  4863. to a stack location in the first place. Or better yet, if we can
  4864. arrange for \code{x} to be placed in a callee-saved register, then it
  4865. won't need to be saved and restored during function calls.
  4866. We recommend an approach that captures these issues in the
  4867. interference graph, without complicating the graph coloring algorithm.
  4868. During liveness analysis we know which variables are call-live because
  4869. we compute which variables are in use at every instruction
  4870. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4871. interference graph (section~\ref{sec:build-interference}), we can
  4872. place an edge in the interference graph between each call-live
  4873. variable and the caller-saved registers. This will prevent the graph
  4874. coloring algorithm from assigning call-live variables to caller-saved
  4875. registers.
  4876. On the other hand, for variables that are not call-live, we prefer
  4877. placing them in caller-saved registers to leave more room for
  4878. call-live variables in the callee-saved registers. This can also be
  4879. implemented without complicating the graph coloring algorithm. We
  4880. recommend that the graph coloring algorithm assign variables to
  4881. natural numbers, choosing the lowest number for which there is no
  4882. interference. After the coloring is complete, we map the numbers to
  4883. registers and stack locations: mapping the lowest numbers to
  4884. caller-saved registers, the next lowest to callee-saved registers, and
  4885. the largest numbers to stack locations. This ordering gives preference
  4886. to registers over stack locations and to caller-saved registers over
  4887. callee-saved registers.
  4888. Returning to the example in
  4889. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4890. generated x86 code on the right-hand side. Variable \code{x} is
  4891. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4892. in a safe place during the second call to \code{read\_int}. Next,
  4893. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4894. because \code{y} is not a call-live variable.
  4895. We have completed the analysis from the caller point of view, so now
  4896. we switch to the callee point of view, focusing on the prelude and
  4897. conclusion of the \code{main} function. As usual, the prelude begins
  4898. with saving the \code{rbp} register to the stack and setting the
  4899. \code{rbp} to the current stack pointer. We now know why it is
  4900. necessary to save the \code{rbp}: it is a callee-saved register. The
  4901. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4902. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4903. (\code{x}). The other callee-saved registers are not saved in the
  4904. prelude because they are not used. The prelude subtracts 8 bytes from
  4905. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4906. conclusion, we see that \code{rbx} is restored from the stack with a
  4907. \code{popq} instruction.
  4908. \index{subject}{prelude}\index{subject}{conclusion}
  4909. \begin{figure}[tp]
  4910. \begin{tcolorbox}[colback=white]
  4911. \begin{minipage}{0.45\textwidth}
  4912. Example \LangVar{} program:
  4913. %var_test_14.rkt
  4914. {\if\edition\racketEd
  4915. \begin{lstlisting}
  4916. (let ([x (read)])
  4917. (let ([y (read)])
  4918. (+ (+ x y) 42)))
  4919. \end{lstlisting}
  4920. \fi}
  4921. {\if\edition\pythonEd\pythonColor
  4922. \begin{lstlisting}
  4923. x = input_int()
  4924. y = input_int()
  4925. print((x + y) + 42)
  4926. \end{lstlisting}
  4927. \fi}
  4928. \end{minipage}
  4929. \begin{minipage}{0.45\textwidth}
  4930. Generated x86 assembly:
  4931. {\if\edition\racketEd
  4932. \begin{lstlisting}
  4933. start:
  4934. callq read_int
  4935. movq %rax, %rbx
  4936. callq read_int
  4937. movq %rax, %rcx
  4938. addq %rcx, %rbx
  4939. movq %rbx, %rax
  4940. addq $42, %rax
  4941. jmp _conclusion
  4942. .globl main
  4943. main:
  4944. pushq %rbp
  4945. movq %rsp, %rbp
  4946. pushq %rbx
  4947. subq $8, %rsp
  4948. jmp start
  4949. conclusion:
  4950. addq $8, %rsp
  4951. popq %rbx
  4952. popq %rbp
  4953. retq
  4954. \end{lstlisting}
  4955. \fi}
  4956. {\if\edition\pythonEd\pythonColor
  4957. \begin{lstlisting}
  4958. .globl main
  4959. main:
  4960. pushq %rbp
  4961. movq %rsp, %rbp
  4962. pushq %rbx
  4963. subq $8, %rsp
  4964. callq read_int
  4965. movq %rax, %rbx
  4966. callq read_int
  4967. movq %rax, %rcx
  4968. movq %rbx, %rdx
  4969. addq %rcx, %rdx
  4970. movq %rdx, %rcx
  4971. addq $42, %rcx
  4972. movq %rcx, %rdi
  4973. callq print_int
  4974. addq $8, %rsp
  4975. popq %rbx
  4976. popq %rbp
  4977. retq
  4978. \end{lstlisting}
  4979. \fi}
  4980. \end{minipage}
  4981. \end{tcolorbox}
  4982. \caption{An example with function calls.}
  4983. \label{fig:example-calling-conventions}
  4984. \end{figure}
  4985. %\clearpage
  4986. \section{Liveness Analysis}
  4987. \label{sec:liveness-analysis-Lvar}
  4988. \index{subject}{liveness analysis}
  4989. The \code{uncover\_live} \racket{pass}\python{function} performs
  4990. \emph{liveness analysis}; that is, it discovers which variables are
  4991. in use in different regions of a program.
  4992. %
  4993. A variable or register is \emph{live} at a program point if its
  4994. current value is used at some later point in the program. We refer to
  4995. variables, stack locations, and registers collectively as
  4996. \emph{locations}.
  4997. %
  4998. Consider the following code fragment in which there are two writes to
  4999. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5000. time?
  5001. \begin{center}
  5002. \begin{minipage}{0.85\textwidth}
  5003. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5004. movq $5, a
  5005. movq $30, b
  5006. movq a, c
  5007. movq $10, b
  5008. addq b, c
  5009. \end{lstlisting}
  5010. \end{minipage}
  5011. \end{center}
  5012. The answer is no, because \code{a} is live from line 1 to 3 and
  5013. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5014. line 2 is never used because it is overwritten (line 4) before the
  5015. next read (line 5).
  5016. The live locations for each instruction can be computed by traversing
  5017. the instruction sequence back to front (i.e., backward in execution
  5018. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5019. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5020. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5021. locations before instruction $I_k$. \racket{We recommend representing
  5022. these sets with the Racket \code{set} data structure described in
  5023. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5024. with the Python
  5025. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5026. data structure.}
  5027. {\if\edition\racketEd
  5028. \begin{figure}[tp]
  5029. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5030. \small
  5031. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5032. A \emph{set} is an unordered collection of elements without duplicates.
  5033. Here are some of the operations defined on sets.
  5034. \index{subject}{set}
  5035. \begin{description}
  5036. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5037. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5038. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5039. difference of the two sets.
  5040. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5041. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5042. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5043. \end{description}
  5044. \end{tcolorbox}
  5045. %\end{wrapfigure}
  5046. \caption{The \code{set} data structure.}
  5047. \label{fig:set}
  5048. \end{figure}
  5049. \fi}
  5050. % TODO: add a python version of the reference box for sets. -Jeremy
  5051. The locations that are live after an instruction are its
  5052. \emph{live-after}\index{subject}{live-after} set, and the locations
  5053. that are live before an instruction are its
  5054. \emph{live-before}\index{subject}{live-before} set. The live-after
  5055. set of an instruction is always the same as the live-before set of the
  5056. next instruction.
  5057. \begin{equation} \label{eq:live-after-before-next}
  5058. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5059. \end{equation}
  5060. To start things off, there are no live locations after the last
  5061. instruction, so
  5062. \begin{equation}\label{eq:live-last-empty}
  5063. L_{\mathsf{after}}(n) = \emptyset
  5064. \end{equation}
  5065. We then apply the following rule repeatedly, traversing the
  5066. instruction sequence back to front.
  5067. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5068. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5069. \end{equation}
  5070. where $W(k)$ are the locations written to by instruction $I_k$, and
  5071. $R(k)$ are the locations read by instruction $I_k$.
  5072. {\if\edition\racketEd
  5073. %
  5074. There is a special case for \code{jmp} instructions. The locations
  5075. that are live before a \code{jmp} should be the locations in
  5076. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5077. maintaining an alist named \code{label->live} that maps each label to
  5078. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5079. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5080. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5081. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5082. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5083. %
  5084. \fi}
  5085. Let us walk through the previous example, applying these formulas
  5086. starting with the instruction on line 5 of the code fragment. We
  5087. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5088. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5089. $\emptyset$ because it is the last instruction
  5090. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5091. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5092. variables \code{b} and \code{c}
  5093. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5094. \[
  5095. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5096. \]
  5097. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5098. the live-before set from line 5 to be the live-after set for this
  5099. instruction (formula~\eqref{eq:live-after-before-next}).
  5100. \[
  5101. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5102. \]
  5103. This move instruction writes to \code{b} and does not read from any
  5104. variables, so we have the following live-before set
  5105. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5106. \[
  5107. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5108. \]
  5109. The live-before for instruction \code{movq a, c}
  5110. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5111. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5112. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5113. variable that is not live and does not read from a variable.
  5114. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5115. because it writes to variable \code{a}.
  5116. \begin{figure}[tbp]
  5117. \centering
  5118. \begin{tcolorbox}[colback=white]
  5119. \hspace{10pt}
  5120. \begin{minipage}{0.4\textwidth}
  5121. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5122. movq $5, a
  5123. movq $30, b
  5124. movq a, c
  5125. movq $10, b
  5126. addq b, c
  5127. \end{lstlisting}
  5128. \end{minipage}
  5129. \vrule\hspace{10pt}
  5130. \begin{minipage}{0.45\textwidth}
  5131. \begin{align*}
  5132. L_{\mathsf{before}}(1)= \emptyset,
  5133. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5134. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5135. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5136. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5137. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5138. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5139. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5140. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5141. L_{\mathsf{after}}(5)= \emptyset
  5142. \end{align*}
  5143. \end{minipage}
  5144. \end{tcolorbox}
  5145. \caption{Example output of liveness analysis on a short example.}
  5146. \label{fig:liveness-example-0}
  5147. \end{figure}
  5148. \begin{exercise}\normalfont\normalsize
  5149. Perform liveness analysis by hand on the running example in
  5150. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5151. sets for each instruction. Compare your answers to the solution
  5152. shown in figure~\ref{fig:live-eg}.
  5153. \end{exercise}
  5154. \begin{figure}[tp]
  5155. \hspace{20pt}
  5156. \begin{minipage}{0.55\textwidth}
  5157. \begin{tcolorbox}[colback=white]
  5158. {\if\edition\racketEd
  5159. \begin{lstlisting}
  5160. |$\{\ttm{rsp}\}$|
  5161. movq $1, v
  5162. |$\{\ttm{v},\ttm{rsp}\}$|
  5163. movq $42, w
  5164. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5165. movq v, x
  5166. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5167. addq $7, x
  5168. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5169. movq x, y
  5170. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5171. movq x, z
  5172. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5173. addq w, z
  5174. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5175. movq y, t
  5176. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5177. negq t
  5178. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5179. movq z, %rax
  5180. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5181. addq t, %rax
  5182. |$\{\ttm{rax},\ttm{rsp}\}$|
  5183. jmp conclusion
  5184. \end{lstlisting}
  5185. \fi}
  5186. {\if\edition\pythonEd\pythonColor
  5187. \begin{lstlisting}
  5188. movq $1, v
  5189. |$\{\ttm{v}\}$|
  5190. movq $42, w
  5191. |$\{\ttm{w}, \ttm{v}\}$|
  5192. movq v, x
  5193. |$\{\ttm{w}, \ttm{x}\}$|
  5194. addq $7, x
  5195. |$\{\ttm{w}, \ttm{x}\}$|
  5196. movq x, y
  5197. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5198. movq x, z
  5199. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5200. addq w, z
  5201. |$\{\ttm{y}, \ttm{z}\}$|
  5202. movq y, tmp_0
  5203. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5204. negq tmp_0
  5205. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5206. movq z, tmp_1
  5207. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5208. addq tmp_0, tmp_1
  5209. |$\{\ttm{tmp\_1}\}$|
  5210. movq tmp_1, %rdi
  5211. |$\{\ttm{rdi}\}$|
  5212. callq print_int
  5213. |$\{\}$|
  5214. \end{lstlisting}
  5215. \fi}
  5216. \end{tcolorbox}
  5217. \end{minipage}
  5218. \caption{The running example annotated with live-after sets.}
  5219. \label{fig:live-eg}
  5220. \end{figure}
  5221. \begin{exercise}\normalfont\normalsize
  5222. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5223. %
  5224. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5225. field of the \code{Block} structure.}
  5226. %
  5227. \python{Return a dictionary that maps each instruction to its
  5228. live-after set.}
  5229. %
  5230. \racket{We recommend creating an auxiliary function that takes a list
  5231. of instructions and an initial live-after set (typically empty) and
  5232. returns the list of live-after sets.}
  5233. %
  5234. We recommend creating auxiliary functions to (1) compute the set
  5235. of locations that appear in an \Arg{}, (2) compute the locations read
  5236. by an instruction (the $R$ function), and (3) the locations written by
  5237. an instruction (the $W$ function). The \code{callq} instruction should
  5238. include all the caller-saved registers in its write set $W$ because
  5239. the calling convention says that those registers may be written to
  5240. during the function call. Likewise, the \code{callq} instruction
  5241. should include the appropriate argument-passing registers in its
  5242. read set $R$, depending on the arity of the function being
  5243. called. (This is why the abstract syntax for \code{callq} includes the
  5244. arity.)
  5245. \end{exercise}
  5246. %\clearpage
  5247. \section{Build the Interference Graph}
  5248. \label{sec:build-interference}
  5249. {\if\edition\racketEd
  5250. \begin{figure}[tp]
  5251. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5252. \small
  5253. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5254. A \emph{graph} is a collection of vertices and edges where each
  5255. edge connects two vertices. A graph is \emph{directed} if each
  5256. edge points from a source to a target. Otherwise the graph is
  5257. \emph{undirected}.
  5258. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5259. \begin{description}
  5260. %% We currently don't use directed graphs. We instead use
  5261. %% directed multi-graphs. -Jeremy
  5262. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5263. directed graph from a list of edges. Each edge is a list
  5264. containing the source and target vertex.
  5265. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5266. undirected graph from a list of edges. Each edge is represented by
  5267. a list containing two vertices.
  5268. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5269. inserts a vertex into the graph.
  5270. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5271. inserts an edge between the two vertices.
  5272. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5273. returns a sequence of vertices adjacent to the vertex.
  5274. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5275. returns a sequence of all vertices in the graph.
  5276. \end{description}
  5277. \end{tcolorbox}
  5278. %\end{wrapfigure}
  5279. \caption{The Racket \code{graph} package.}
  5280. \label{fig:graph}
  5281. \end{figure}
  5282. \fi}
  5283. On the basis of the liveness analysis, we know where each location is
  5284. live. However, during register allocation, we need to answer
  5285. questions of the specific form: are locations $u$ and $v$ live at the
  5286. same time? (If so, they cannot be assigned to the same register.) To
  5287. make this question more efficient to answer, we create an explicit
  5288. data structure, an \emph{interference
  5289. graph}\index{subject}{interference graph}. An interference graph is
  5290. an undirected graph that has a node for every variable and register
  5291. and has an edge between two nodes if they are
  5292. live at the same time, that is, if they interfere with each other.
  5293. %
  5294. \racket{We recommend using the Racket \code{graph} package
  5295. (figure~\ref{fig:graph}) to represent the interference graph.}
  5296. %
  5297. \python{We provide implementations of directed and undirected graph
  5298. data structures in the file \code{graph.py} of the support code.}
  5299. A straightforward way to compute the interference graph is to look at
  5300. the set of live locations between each instruction and add an edge to
  5301. the graph for every pair of variables in the same set. This approach
  5302. is less than ideal for two reasons. First, it can be expensive because
  5303. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5304. locations. Second, in the special case in which two locations hold the
  5305. same value (because one was assigned to the other), they can be live
  5306. at the same time without interfering with each other.
  5307. A better way to compute the interference graph is to focus on
  5308. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5309. must not overwrite something in a live location. So for each
  5310. instruction, we create an edge between the locations being written to
  5311. and the live locations. (However, a location never interferes with
  5312. itself.) For the \key{callq} instruction, we consider all the
  5313. caller-saved registers to have been written to, so an edge is added
  5314. between every live variable and every caller-saved register. Also, for
  5315. \key{movq} there is the special case of two variables holding the same
  5316. value. If a live variable $v$ is the same as the source of the
  5317. \key{movq}, then there is no need to add an edge between $v$ and the
  5318. destination, because they both hold the same value.
  5319. %
  5320. Hence we have the following two rules:
  5321. \begin{enumerate}
  5322. \item If instruction $I_k$ is a move instruction of the form
  5323. \key{movq} $s$\key{,} $d$, then for every $v \in
  5324. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5325. $(d,v)$.
  5326. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5327. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5328. $(d,v)$.
  5329. \end{enumerate}
  5330. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5331. these rules to each instruction. We highlight a few of the
  5332. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5333. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5334. so \code{v} interferes with \code{rsp}.}
  5335. %
  5336. \python{The first instruction is \lstinline{movq $1, v}, and the
  5337. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5338. no interference because $\ttm{v}$ is the destination of the move.}
  5339. %
  5340. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5341. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5342. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5343. %
  5344. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5345. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5346. $\ttm{x}$ interferes with \ttm{w}.}
  5347. %
  5348. \racket{The next instruction is \lstinline{movq x, y}, and the
  5349. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5350. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5351. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5352. \ttm{x} and \ttm{y} hold the same value.}
  5353. %
  5354. \python{The next instruction is \lstinline{movq x, y}, and the
  5355. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5356. applies, so \ttm{y} interferes with \ttm{w} but not
  5357. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5358. \ttm{x} and \ttm{y} hold the same value.}
  5359. %
  5360. Figure~\ref{fig:interference-results} lists the interference results
  5361. for all the instructions, and the resulting interference graph is
  5362. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5363. the interference graph in figure~\ref{fig:interfere} because there
  5364. were no interference edges involving registers and we did not wish to
  5365. clutter the graph, but in general one needs to include all the
  5366. registers in the interference graph.
  5367. \begin{figure}[tbp]
  5368. \begin{tcolorbox}[colback=white]
  5369. \begin{quote}
  5370. {\if\edition\racketEd
  5371. \begin{tabular}{ll}
  5372. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5373. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5374. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5375. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5376. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5377. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5378. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5379. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5380. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5381. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5382. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5383. \lstinline!jmp conclusion!& no interference.
  5384. \end{tabular}
  5385. \fi}
  5386. {\if\edition\pythonEd\pythonColor
  5387. \begin{tabular}{ll}
  5388. \lstinline!movq $1, v!& no interference\\
  5389. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5390. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5391. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5392. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5393. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5394. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5395. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5396. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5397. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5398. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5399. \lstinline!movq tmp_1, %rdi! & no interference \\
  5400. \lstinline!callq print_int!& no interference.
  5401. \end{tabular}
  5402. \fi}
  5403. \end{quote}
  5404. \end{tcolorbox}
  5405. \caption{Interference results for the running example.}
  5406. \label{fig:interference-results}
  5407. \end{figure}
  5408. \begin{figure}[tbp]
  5409. \begin{tcolorbox}[colback=white]
  5410. \large
  5411. {\if\edition\racketEd
  5412. \[
  5413. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5414. \node (rax) at (0,0) {$\ttm{rax}$};
  5415. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5416. \node (t1) at (0,2) {$\ttm{t}$};
  5417. \node (z) at (3,2) {$\ttm{z}$};
  5418. \node (x) at (6,2) {$\ttm{x}$};
  5419. \node (y) at (3,0) {$\ttm{y}$};
  5420. \node (w) at (6,0) {$\ttm{w}$};
  5421. \node (v) at (9,0) {$\ttm{v}$};
  5422. \draw (t1) to (rax);
  5423. \draw (t1) to (z);
  5424. \draw (z) to (y);
  5425. \draw (z) to (w);
  5426. \draw (x) to (w);
  5427. \draw (y) to (w);
  5428. \draw (v) to (w);
  5429. \draw (v) to (rsp);
  5430. \draw (w) to (rsp);
  5431. \draw (x) to (rsp);
  5432. \draw (y) to (rsp);
  5433. \path[-.,bend left=15] (z) edge node {} (rsp);
  5434. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5435. \draw (rax) to (rsp);
  5436. \end{tikzpicture}
  5437. \]
  5438. \fi}
  5439. {\if\edition\pythonEd\pythonColor
  5440. \[
  5441. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5442. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5443. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5444. \node (z) at (3,2) {$\ttm{z}$};
  5445. \node (x) at (6,2) {$\ttm{x}$};
  5446. \node (y) at (3,0) {$\ttm{y}$};
  5447. \node (w) at (6,0) {$\ttm{w}$};
  5448. \node (v) at (9,0) {$\ttm{v}$};
  5449. \draw (t0) to (t1);
  5450. \draw (t0) to (z);
  5451. \draw (z) to (y);
  5452. \draw (z) to (w);
  5453. \draw (x) to (w);
  5454. \draw (y) to (w);
  5455. \draw (v) to (w);
  5456. \end{tikzpicture}
  5457. \]
  5458. \fi}
  5459. \end{tcolorbox}
  5460. \caption{The interference graph of the example program.}
  5461. \label{fig:interfere}
  5462. \end{figure}
  5463. \begin{exercise}\normalfont\normalsize
  5464. \racket{Implement the compiler pass named \code{build\_interference} according
  5465. to the algorithm suggested here. We recommend using the Racket
  5466. \code{graph} package to create and inspect the interference graph.
  5467. The output graph of this pass should be stored in the $\itm{info}$ field of
  5468. the program, under the key \code{conflicts}.}
  5469. %
  5470. \python{Implement a function named \code{build\_interference}
  5471. according to the algorithm suggested above that
  5472. returns the interference graph.}
  5473. \end{exercise}
  5474. \section{Graph Coloring via Sudoku}
  5475. \label{sec:graph-coloring}
  5476. \index{subject}{graph coloring}
  5477. \index{subject}{sudoku}
  5478. \index{subject}{color}
  5479. We come to the main event discussed in this chapter, mapping variables
  5480. to registers and stack locations. Variables that interfere with each
  5481. other must be mapped to different locations. In terms of the
  5482. interference graph, this means that adjacent vertices must be mapped
  5483. to different locations. If we think of locations as colors, the
  5484. register allocation problem becomes the graph coloring
  5485. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5486. The reader may be more familiar with the graph coloring problem than he
  5487. or she realizes; the popular game of sudoku is an instance of the
  5488. graph coloring problem. The following describes how to build a graph
  5489. out of an initial sudoku board.
  5490. \begin{itemize}
  5491. \item There is one vertex in the graph for each sudoku square.
  5492. \item There is an edge between two vertices if the corresponding squares
  5493. are in the same row, in the same column, or in the same $3\times 3$ region.
  5494. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5495. \item On the basis of the initial assignment of numbers to squares on the
  5496. sudoku board, assign the corresponding colors to the corresponding
  5497. vertices in the graph.
  5498. \end{itemize}
  5499. If you can color the remaining vertices in the graph with the nine
  5500. colors, then you have also solved the corresponding game of sudoku.
  5501. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5502. the corresponding graph with colored vertices. Here we use a
  5503. monochrome representation of colors, mapping the sudoku number 1 to
  5504. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5505. of the vertices (the colored ones) because showing edges for all the
  5506. vertices would make the graph unreadable.
  5507. \begin{figure}[tbp]
  5508. \begin{tcolorbox}[colback=white]
  5509. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5510. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5511. \end{tcolorbox}
  5512. \caption{A sudoku game board and the corresponding colored graph.}
  5513. \label{fig:sudoku-graph}
  5514. \end{figure}
  5515. Some techniques for playing sudoku correspond to heuristics used in
  5516. graph coloring algorithms. For example, one of the basic techniques
  5517. for sudoku is called Pencil Marks. The idea is to use a process of
  5518. elimination to determine what numbers are no longer available for a
  5519. square and to write those numbers in the square (writing very
  5520. small). For example, if the number $1$ is assigned to a square, then
  5521. write the pencil mark $1$ in all the squares in the same row, column,
  5522. and region to indicate that $1$ is no longer an option for those other
  5523. squares.
  5524. %
  5525. The Pencil Marks technique corresponds to the notion of
  5526. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5527. saturation of a vertex, in sudoku terms, is the set of numbers that
  5528. are no longer available. In graph terminology, we have the following
  5529. definition:
  5530. \begin{equation*}
  5531. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5532. \text{ and } \mathrm{color}(v) = c \}
  5533. \end{equation*}
  5534. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5535. edge with $u$.
  5536. The Pencil Marks technique leads to a simple strategy for filling in
  5537. numbers: if there is a square with only one possible number left, then
  5538. choose that number! But what if there are no squares with only one
  5539. possibility left? One brute-force approach is to try them all: choose
  5540. the first one, and if that ultimately leads to a solution, great. If
  5541. not, backtrack and choose the next possibility. One good thing about
  5542. Pencil Marks is that it reduces the degree of branching in the search
  5543. tree. Nevertheless, backtracking can be terribly time consuming. One
  5544. way to reduce the amount of backtracking is to use the
  5545. most-constrained-first heuristic (aka minimum remaining
  5546. values)~\citep{Russell2003}. That is, in choosing a square, always
  5547. choose one with the fewest possibilities left (the vertex with the
  5548. highest saturation). The idea is that choosing highly constrained
  5549. squares earlier rather than later is better, because later on there may
  5550. not be any possibilities left in the highly saturated squares.
  5551. However, register allocation is easier than sudoku, because the
  5552. register allocator can fall back to assigning variables to stack
  5553. locations when the registers run out. Thus, it makes sense to replace
  5554. backtracking with greedy search: make the best choice at the time and
  5555. keep going. We still wish to minimize the number of colors needed, so
  5556. we use the most-constrained-first heuristic in the greedy search.
  5557. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5558. algorithm for register allocation based on saturation and the
  5559. most-constrained-first heuristic. It is roughly equivalent to the
  5560. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5561. sudoku, the algorithm represents colors with integers. The integers
  5562. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5563. register allocation. In particular, we recommend the following
  5564. correspondence, with $k=11$.
  5565. \begin{lstlisting}
  5566. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5567. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5568. \end{lstlisting}
  5569. The integers $k$ and larger correspond to stack locations. The
  5570. registers that are not used for register allocation, such as
  5571. \code{rax}, are assigned to negative integers. In particular, we
  5572. recommend the following correspondence.
  5573. \begin{lstlisting}
  5574. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5575. \end{lstlisting}
  5576. \begin{figure}[btp]
  5577. \begin{tcolorbox}[colback=white]
  5578. \centering
  5579. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5580. Algorithm: DSATUR
  5581. Input: A graph |$G$|
  5582. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5583. |$W \gets \mathrm{vertices}(G)$|
  5584. while |$W \neq \emptyset$| do
  5585. pick a vertex |$u$| from |$W$| with the highest saturation,
  5586. breaking ties randomly
  5587. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5588. |$\mathrm{color}[u] \gets c$|
  5589. |$W \gets W - \{u\}$|
  5590. \end{lstlisting}
  5591. \end{tcolorbox}
  5592. \caption{The saturation-based greedy graph coloring algorithm.}
  5593. \label{fig:satur-algo}
  5594. \end{figure}
  5595. {\if\edition\racketEd
  5596. With the DSATUR algorithm in hand, let us return to the running
  5597. example and consider how to color the interference graph shown in
  5598. figure~\ref{fig:interfere}.
  5599. %
  5600. We start by assigning each register node to its own color. For
  5601. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5602. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5603. (To reduce clutter in the interference graph, we elide nodes
  5604. that do not have interference edges, such as \code{rcx}.)
  5605. The variables are not yet colored, so they are annotated with a dash. We
  5606. then update the saturation for vertices that are adjacent to a
  5607. register, obtaining the following annotated graph. For example, the
  5608. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5609. \code{rax} and \code{rsp}.
  5610. \[
  5611. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5612. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5613. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5614. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5615. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5616. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5617. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5618. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5619. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5620. \draw (t1) to (rax);
  5621. \draw (t1) to (z);
  5622. \draw (z) to (y);
  5623. \draw (z) to (w);
  5624. \draw (x) to (w);
  5625. \draw (y) to (w);
  5626. \draw (v) to (w);
  5627. \draw (v) to (rsp);
  5628. \draw (w) to (rsp);
  5629. \draw (x) to (rsp);
  5630. \draw (y) to (rsp);
  5631. \path[-.,bend left=15] (z) edge node {} (rsp);
  5632. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5633. \draw (rax) to (rsp);
  5634. \end{tikzpicture}
  5635. \]
  5636. The algorithm says to select a maximally saturated vertex. So, we pick
  5637. $\ttm{t}$ and color it with the first available integer, which is
  5638. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5639. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5640. \[
  5641. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5642. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5643. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5644. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5645. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5646. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5647. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5648. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5649. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5650. \draw (t1) to (rax);
  5651. \draw (t1) to (z);
  5652. \draw (z) to (y);
  5653. \draw (z) to (w);
  5654. \draw (x) to (w);
  5655. \draw (y) to (w);
  5656. \draw (v) to (w);
  5657. \draw (v) to (rsp);
  5658. \draw (w) to (rsp);
  5659. \draw (x) to (rsp);
  5660. \draw (y) to (rsp);
  5661. \path[-.,bend left=15] (z) edge node {} (rsp);
  5662. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5663. \draw (rax) to (rsp);
  5664. \end{tikzpicture}
  5665. \]
  5666. We repeat the process, selecting a maximally saturated vertex,
  5667. choosing \code{z}, and coloring it with the first available number, which
  5668. is $1$. We add $1$ to the saturation for the neighboring vertices
  5669. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5670. \[
  5671. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5672. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5673. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5674. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5675. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5676. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5677. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5678. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5679. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5680. \draw (t1) to (rax);
  5681. \draw (t1) to (z);
  5682. \draw (z) to (y);
  5683. \draw (z) to (w);
  5684. \draw (x) to (w);
  5685. \draw (y) to (w);
  5686. \draw (v) to (w);
  5687. \draw (v) to (rsp);
  5688. \draw (w) to (rsp);
  5689. \draw (x) to (rsp);
  5690. \draw (y) to (rsp);
  5691. \path[-.,bend left=15] (z) edge node {} (rsp);
  5692. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5693. \draw (rax) to (rsp);
  5694. \end{tikzpicture}
  5695. \]
  5696. The most saturated vertices are now \code{w} and \code{y}. We color
  5697. \code{w} with the first available color, which is $0$.
  5698. \[
  5699. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5700. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5701. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5702. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5703. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5704. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5705. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5706. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5707. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5708. \draw (t1) to (rax);
  5709. \draw (t1) to (z);
  5710. \draw (z) to (y);
  5711. \draw (z) to (w);
  5712. \draw (x) to (w);
  5713. \draw (y) to (w);
  5714. \draw (v) to (w);
  5715. \draw (v) to (rsp);
  5716. \draw (w) to (rsp);
  5717. \draw (x) to (rsp);
  5718. \draw (y) to (rsp);
  5719. \path[-.,bend left=15] (z) edge node {} (rsp);
  5720. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5721. \draw (rax) to (rsp);
  5722. \end{tikzpicture}
  5723. \]
  5724. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5725. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5726. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5727. and \code{z}, whose colors are $0$ and $1$ respectively.
  5728. \[
  5729. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5730. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5731. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5732. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5733. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5734. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5735. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5736. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5737. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5738. \draw (t1) to (rax);
  5739. \draw (t1) to (z);
  5740. \draw (z) to (y);
  5741. \draw (z) to (w);
  5742. \draw (x) to (w);
  5743. \draw (y) to (w);
  5744. \draw (v) to (w);
  5745. \draw (v) to (rsp);
  5746. \draw (w) to (rsp);
  5747. \draw (x) to (rsp);
  5748. \draw (y) to (rsp);
  5749. \path[-.,bend left=15] (z) edge node {} (rsp);
  5750. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5751. \draw (rax) to (rsp);
  5752. \end{tikzpicture}
  5753. \]
  5754. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5755. \[
  5756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5757. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5758. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5759. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5760. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5761. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5762. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5763. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5764. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5765. \draw (t1) to (rax);
  5766. \draw (t1) to (z);
  5767. \draw (z) to (y);
  5768. \draw (z) to (w);
  5769. \draw (x) to (w);
  5770. \draw (y) to (w);
  5771. \draw (v) to (w);
  5772. \draw (v) to (rsp);
  5773. \draw (w) to (rsp);
  5774. \draw (x) to (rsp);
  5775. \draw (y) to (rsp);
  5776. \path[-.,bend left=15] (z) edge node {} (rsp);
  5777. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5778. \draw (rax) to (rsp);
  5779. \end{tikzpicture}
  5780. \]
  5781. In the last step of the algorithm, we color \code{x} with $1$.
  5782. \[
  5783. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5784. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5785. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5786. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5787. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5788. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5789. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5790. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5791. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5792. \draw (t1) to (rax);
  5793. \draw (t1) to (z);
  5794. \draw (z) to (y);
  5795. \draw (z) to (w);
  5796. \draw (x) to (w);
  5797. \draw (y) to (w);
  5798. \draw (v) to (w);
  5799. \draw (v) to (rsp);
  5800. \draw (w) to (rsp);
  5801. \draw (x) to (rsp);
  5802. \draw (y) to (rsp);
  5803. \path[-.,bend left=15] (z) edge node {} (rsp);
  5804. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5805. \draw (rax) to (rsp);
  5806. \end{tikzpicture}
  5807. \]
  5808. So, we obtain the following coloring:
  5809. \[
  5810. \{
  5811. \ttm{rax} \mapsto -1,
  5812. \ttm{rsp} \mapsto -2,
  5813. \ttm{t} \mapsto 0,
  5814. \ttm{z} \mapsto 1,
  5815. \ttm{x} \mapsto 1,
  5816. \ttm{y} \mapsto 2,
  5817. \ttm{w} \mapsto 0,
  5818. \ttm{v} \mapsto 1
  5819. \}
  5820. \]
  5821. \fi}
  5822. %
  5823. {\if\edition\pythonEd\pythonColor
  5824. %
  5825. With the DSATUR algorithm in hand, let us return to the running
  5826. example and consider how to color the interference graph shown in
  5827. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5828. to indicate that it has not yet been assigned a color. Each register
  5829. node (not shown) should be assigned the number that the register
  5830. corresponds to, for example, color \code{rcx} with the number \code{0}
  5831. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5832. each node; all of them start as the empty set.
  5833. %
  5834. \[
  5835. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5836. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5837. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5838. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5839. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5840. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5841. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5842. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5843. \draw (t0) to (t1);
  5844. \draw (t0) to (z);
  5845. \draw (z) to (y);
  5846. \draw (z) to (w);
  5847. \draw (x) to (w);
  5848. \draw (y) to (w);
  5849. \draw (v) to (w);
  5850. \end{tikzpicture}
  5851. \]
  5852. The algorithm says to select a maximally saturated vertex, but they
  5853. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5854. and then we color it with the first available integer, which is $0$. We mark
  5855. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5856. they interfere with $\ttm{tmp\_0}$.
  5857. \[
  5858. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5859. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5860. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5861. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5862. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5863. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5864. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5865. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5866. \draw (t0) to (t1);
  5867. \draw (t0) to (z);
  5868. \draw (z) to (y);
  5869. \draw (z) to (w);
  5870. \draw (x) to (w);
  5871. \draw (y) to (w);
  5872. \draw (v) to (w);
  5873. \end{tikzpicture}
  5874. \]
  5875. We repeat the process. The most saturated vertices are \code{z} and
  5876. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5877. available number, which is $1$. We add $1$ to the saturation for the
  5878. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5879. \[
  5880. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5881. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5882. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5883. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5884. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5885. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5886. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5887. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5888. \draw (t0) to (t1);
  5889. \draw (t0) to (z);
  5890. \draw (z) to (y);
  5891. \draw (z) to (w);
  5892. \draw (x) to (w);
  5893. \draw (y) to (w);
  5894. \draw (v) to (w);
  5895. \end{tikzpicture}
  5896. \]
  5897. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5898. \code{y}. We color \code{w} with the first available color, which
  5899. is $0$.
  5900. \[
  5901. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5902. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5903. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5904. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5905. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5906. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5907. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5908. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5909. \draw (t0) to (t1);
  5910. \draw (t0) to (z);
  5911. \draw (z) to (y);
  5912. \draw (z) to (w);
  5913. \draw (x) to (w);
  5914. \draw (y) to (w);
  5915. \draw (v) to (w);
  5916. \end{tikzpicture}
  5917. \]
  5918. Now \code{y} is the most saturated, so we color it with $2$.
  5919. \[
  5920. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5921. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5922. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5923. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5924. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5925. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5926. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5927. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5928. \draw (t0) to (t1);
  5929. \draw (t0) to (z);
  5930. \draw (z) to (y);
  5931. \draw (z) to (w);
  5932. \draw (x) to (w);
  5933. \draw (y) to (w);
  5934. \draw (v) to (w);
  5935. \end{tikzpicture}
  5936. \]
  5937. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5938. We choose to color \code{v} with $1$.
  5939. \[
  5940. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5941. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5942. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5943. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5944. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5945. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5946. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5947. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5948. \draw (t0) to (t1);
  5949. \draw (t0) to (z);
  5950. \draw (z) to (y);
  5951. \draw (z) to (w);
  5952. \draw (x) to (w);
  5953. \draw (y) to (w);
  5954. \draw (v) to (w);
  5955. \end{tikzpicture}
  5956. \]
  5957. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5958. \[
  5959. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5960. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5961. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5962. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5963. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5964. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5965. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5966. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5967. \draw (t0) to (t1);
  5968. \draw (t0) to (z);
  5969. \draw (z) to (y);
  5970. \draw (z) to (w);
  5971. \draw (x) to (w);
  5972. \draw (y) to (w);
  5973. \draw (v) to (w);
  5974. \end{tikzpicture}
  5975. \]
  5976. So, we obtain the following coloring:
  5977. \[
  5978. \{ \ttm{tmp\_0} \mapsto 0,
  5979. \ttm{tmp\_1} \mapsto 1,
  5980. \ttm{z} \mapsto 1,
  5981. \ttm{x} \mapsto 1,
  5982. \ttm{y} \mapsto 2,
  5983. \ttm{w} \mapsto 0,
  5984. \ttm{v} \mapsto 1 \}
  5985. \]
  5986. \fi}
  5987. We recommend creating an auxiliary function named \code{color\_graph}
  5988. that takes an interference graph and a list of all the variables in
  5989. the program. This function should return a mapping of variables to
  5990. their colors (represented as natural numbers). By creating this helper
  5991. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5992. when we add support for functions.
  5993. To prioritize the processing of highly saturated nodes inside the
  5994. \code{color\_graph} function, we recommend using the priority queue
  5995. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5996. addition, you will need to maintain a mapping from variables to their
  5997. handles in the priority queue so that you can notify the priority
  5998. queue when their saturation changes.}
  5999. {\if\edition\racketEd
  6000. \begin{figure}[tp]
  6001. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6002. \small
  6003. \begin{tcolorbox}[title=Priority Queue]
  6004. A \emph{priority queue}\index{subject}{priority queue}
  6005. is a collection of items in which the
  6006. removal of items is governed by priority. In a \emph{min} queue,
  6007. lower priority items are removed first. An implementation is in
  6008. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6009. \begin{description}
  6010. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6011. priority queue that uses the $\itm{cmp}$ predicate to determine
  6012. whether its first argument has lower or equal priority to its
  6013. second argument.
  6014. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6015. items in the queue.
  6016. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6017. the item into the queue and returns a handle for the item in the
  6018. queue.
  6019. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6020. the lowest priority.
  6021. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6022. notifies the queue that the priority has decreased for the item
  6023. associated with the given handle.
  6024. \end{description}
  6025. \end{tcolorbox}
  6026. %\end{wrapfigure}
  6027. \caption{The priority queue data structure.}
  6028. \label{fig:priority-queue}
  6029. \end{figure}
  6030. \fi}
  6031. With the coloring complete, we finalize the assignment of variables to
  6032. registers and stack locations. We map the first $k$ colors to the $k$
  6033. registers and the rest of the colors to stack locations. Suppose for
  6034. the moment that we have just one register to use for register
  6035. allocation, \key{rcx}. Then we have the following assignment.
  6036. \[
  6037. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6038. \]
  6039. Composing this mapping with the coloring, we arrive at the following
  6040. assignment of variables to locations.
  6041. {\if\edition\racketEd
  6042. \begin{gather*}
  6043. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6044. \ttm{w} \mapsto \key{\%rcx}, \,
  6045. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6046. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6047. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6048. \ttm{t} \mapsto \key{\%rcx} \}
  6049. \end{gather*}
  6050. \fi}
  6051. {\if\edition\pythonEd\pythonColor
  6052. \begin{gather*}
  6053. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6054. \ttm{w} \mapsto \key{\%rcx}, \,
  6055. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6056. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6057. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6058. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6059. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6060. \end{gather*}
  6061. \fi}
  6062. Adapt the code from the \code{assign\_homes} pass
  6063. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6064. assigned location. Applying this assignment to our running
  6065. example shown next, on the left, yields the program on the right.
  6066. \begin{center}
  6067. {\if\edition\racketEd
  6068. \begin{minipage}{0.35\textwidth}
  6069. \begin{lstlisting}
  6070. movq $1, v
  6071. movq $42, w
  6072. movq v, x
  6073. addq $7, x
  6074. movq x, y
  6075. movq x, z
  6076. addq w, z
  6077. movq y, t
  6078. negq t
  6079. movq z, %rax
  6080. addq t, %rax
  6081. jmp conclusion
  6082. \end{lstlisting}
  6083. \end{minipage}
  6084. $\Rightarrow\qquad$
  6085. \begin{minipage}{0.45\textwidth}
  6086. \begin{lstlisting}
  6087. movq $1, -8(%rbp)
  6088. movq $42, %rcx
  6089. movq -8(%rbp), -8(%rbp)
  6090. addq $7, -8(%rbp)
  6091. movq -8(%rbp), -16(%rbp)
  6092. movq -8(%rbp), -8(%rbp)
  6093. addq %rcx, -8(%rbp)
  6094. movq -16(%rbp), %rcx
  6095. negq %rcx
  6096. movq -8(%rbp), %rax
  6097. addq %rcx, %rax
  6098. jmp conclusion
  6099. \end{lstlisting}
  6100. \end{minipage}
  6101. \fi}
  6102. {\if\edition\pythonEd\pythonColor
  6103. \begin{minipage}{0.35\textwidth}
  6104. \begin{lstlisting}
  6105. movq $1, v
  6106. movq $42, w
  6107. movq v, x
  6108. addq $7, x
  6109. movq x, y
  6110. movq x, z
  6111. addq w, z
  6112. movq y, tmp_0
  6113. negq tmp_0
  6114. movq z, tmp_1
  6115. addq tmp_0, tmp_1
  6116. movq tmp_1, %rdi
  6117. callq print_int
  6118. \end{lstlisting}
  6119. \end{minipage}
  6120. $\Rightarrow\qquad$
  6121. \begin{minipage}{0.45\textwidth}
  6122. \begin{lstlisting}
  6123. movq $1, -8(%rbp)
  6124. movq $42, %rcx
  6125. movq -8(%rbp), -8(%rbp)
  6126. addq $7, -8(%rbp)
  6127. movq -8(%rbp), -16(%rbp)
  6128. movq -8(%rbp), -8(%rbp)
  6129. addq %rcx, -8(%rbp)
  6130. movq -16(%rbp), %rcx
  6131. negq %rcx
  6132. movq -8(%rbp), -8(%rbp)
  6133. addq %rcx, -8(%rbp)
  6134. movq -8(%rbp), %rdi
  6135. callq print_int
  6136. \end{lstlisting}
  6137. \end{minipage}
  6138. \fi}
  6139. \end{center}
  6140. \begin{exercise}\normalfont\normalsize
  6141. Implement the \code{allocate\_registers} pass.
  6142. Create five programs that exercise all aspects of the register
  6143. allocation algorithm, including spilling variables to the stack.
  6144. %
  6145. {\if\edition\racketEd
  6146. Replace \code{assign\_homes} in the list of \code{passes} in the
  6147. \code{run-tests.rkt} script with the three new passes:
  6148. \code{uncover\_live}, \code{build\_interference}, and
  6149. \code{allocate\_registers}.
  6150. Temporarily remove the call to \code{compiler-tests}.
  6151. Run the script to test the register allocator.
  6152. \fi}
  6153. %
  6154. {\if\edition\pythonEd\pythonColor
  6155. Run the \code{run-tests.py} script to check whether the
  6156. output programs produce the same result as the input programs.
  6157. \fi}
  6158. \end{exercise}
  6159. \section{Patch Instructions}
  6160. \label{sec:patch-instructions}
  6161. The remaining step in the compilation to x86 is to ensure that the
  6162. instructions have at most one argument that is a memory access.
  6163. %
  6164. In the running example, the instruction \code{movq -8(\%rbp),
  6165. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6166. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6167. then move \code{rax} into \code{-16(\%rbp)}.
  6168. %
  6169. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6170. problematic, but they can simply be deleted. In general, we recommend
  6171. deleting all the trivial moves whose source and destination are the
  6172. same location.
  6173. %
  6174. The following is the output of \code{patch\_instructions} on the
  6175. running example.
  6176. \begin{center}
  6177. {\if\edition\racketEd
  6178. \begin{minipage}{0.35\textwidth}
  6179. \begin{lstlisting}
  6180. movq $1, -8(%rbp)
  6181. movq $42, %rcx
  6182. movq -8(%rbp), -8(%rbp)
  6183. addq $7, -8(%rbp)
  6184. movq -8(%rbp), -16(%rbp)
  6185. movq -8(%rbp), -8(%rbp)
  6186. addq %rcx, -8(%rbp)
  6187. movq -16(%rbp), %rcx
  6188. negq %rcx
  6189. movq -8(%rbp), %rax
  6190. addq %rcx, %rax
  6191. jmp conclusion
  6192. \end{lstlisting}
  6193. \end{minipage}
  6194. $\Rightarrow\qquad$
  6195. \begin{minipage}{0.45\textwidth}
  6196. \begin{lstlisting}
  6197. movq $1, -8(%rbp)
  6198. movq $42, %rcx
  6199. addq $7, -8(%rbp)
  6200. movq -8(%rbp), %rax
  6201. movq %rax, -16(%rbp)
  6202. addq %rcx, -8(%rbp)
  6203. movq -16(%rbp), %rcx
  6204. negq %rcx
  6205. movq -8(%rbp), %rax
  6206. addq %rcx, %rax
  6207. jmp conclusion
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. \fi}
  6211. {\if\edition\pythonEd\pythonColor
  6212. \begin{minipage}{0.35\textwidth}
  6213. \begin{lstlisting}
  6214. movq $1, -8(%rbp)
  6215. movq $42, %rcx
  6216. movq -8(%rbp), -8(%rbp)
  6217. addq $7, -8(%rbp)
  6218. movq -8(%rbp), -16(%rbp)
  6219. movq -8(%rbp), -8(%rbp)
  6220. addq %rcx, -8(%rbp)
  6221. movq -16(%rbp), %rcx
  6222. negq %rcx
  6223. movq -8(%rbp), -8(%rbp)
  6224. addq %rcx, -8(%rbp)
  6225. movq -8(%rbp), %rdi
  6226. callq print_int
  6227. \end{lstlisting}
  6228. \end{minipage}
  6229. $\Rightarrow\qquad$
  6230. \begin{minipage}{0.45\textwidth}
  6231. \begin{lstlisting}
  6232. movq $1, -8(%rbp)
  6233. movq $42, %rcx
  6234. addq $7, -8(%rbp)
  6235. movq -8(%rbp), %rax
  6236. movq %rax, -16(%rbp)
  6237. addq %rcx, -8(%rbp)
  6238. movq -16(%rbp), %rcx
  6239. negq %rcx
  6240. addq %rcx, -8(%rbp)
  6241. movq -8(%rbp), %rdi
  6242. callq print_int
  6243. \end{lstlisting}
  6244. \end{minipage}
  6245. \fi}
  6246. \end{center}
  6247. \begin{exercise}\normalfont\normalsize
  6248. %
  6249. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6250. %
  6251. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6252. %in the \code{run-tests.rkt} script.
  6253. %
  6254. Run the script to test the \code{patch\_instructions} pass.
  6255. \end{exercise}
  6256. \section{Generate Prelude and Conclusion}
  6257. \label{sec:print-x86-reg-alloc}
  6258. \index{subject}{calling conventions}
  6259. \index{subject}{prelude}\index{subject}{conclusion}
  6260. Recall that this pass generates the prelude and conclusion
  6261. instructions to satisfy the x86 calling conventions
  6262. (section~\ref{sec:calling-conventions}). With the addition of the
  6263. register allocator, the callee-saved registers used by the register
  6264. allocator must be saved in the prelude and restored in the conclusion.
  6265. In the \code{allocate\_registers} pass,
  6266. %
  6267. \racket{add an entry to the \itm{info}
  6268. of \code{X86Program} named \code{used\_callee}}
  6269. %
  6270. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6271. %
  6272. that stores the set of callee-saved registers that were assigned to
  6273. variables. The \code{prelude\_and\_conclusion} pass can then access
  6274. this information to decide which callee-saved registers need to be
  6275. saved and restored.
  6276. %
  6277. When calculating the amount to adjust the \code{rsp} in the prelude,
  6278. make sure to take into account the space used for saving the
  6279. callee-saved registers. Also, remember that the frame needs to be a
  6280. multiple of 16 bytes! We recommend using the following equation for
  6281. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6282. of stack locations used by spilled variables\footnote{Sometimes two or
  6283. more spilled variables are assigned to the same stack location, so
  6284. $S$ can be less than the number of spilled variables.} and $C$ be
  6285. the number of callee-saved registers that were
  6286. allocated\index{subject}{allocate} to
  6287. variables. The $\itm{align}$ function rounds a number up to the
  6288. nearest 16 bytes.
  6289. \[
  6290. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6291. \]
  6292. The reason we subtract $8\itm{C}$ in this equation is that the
  6293. prelude uses \code{pushq} to save each of the callee-saved registers,
  6294. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6295. \racket{An overview of all the passes involved in register
  6296. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6297. {\if\edition\racketEd
  6298. \begin{figure}[tbp]
  6299. \begin{tcolorbox}[colback=white]
  6300. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6301. \node (Lvar) at (0,2) {\large \LangVar{}};
  6302. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6303. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6304. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6305. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6306. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6307. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6308. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6309. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6310. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6311. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6312. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6313. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6314. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6315. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6316. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6317. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6318. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6319. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6320. \end{tikzpicture}
  6321. \end{tcolorbox}
  6322. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6323. \label{fig:reg-alloc-passes}
  6324. \end{figure}
  6325. \fi}
  6326. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6327. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6328. use of registers and the stack, we limit the register allocator for
  6329. this example to use just two registers: \code{rcx} (color $0$) and
  6330. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6331. \code{main} function, we push \code{rbx} onto the stack because it is
  6332. a callee-saved register and it was assigned to a variable by the
  6333. register allocator. We subtract \code{8} from the \code{rsp} at the
  6334. end of the prelude to reserve space for the one spilled variable.
  6335. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6336. Moving on to the program proper, we see how the registers were
  6337. allocated.
  6338. %
  6339. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6340. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6341. %
  6342. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6343. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6344. were assigned to \code{rbx}.}
  6345. %
  6346. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6347. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6348. callee-save register \code{rbx} onto the stack. The spilled variables
  6349. must be placed lower on the stack than the saved callee-save
  6350. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6351. \code{-16(\%rbp)}.
  6352. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6353. done in the prelude. We move the stack pointer up by \code{8} bytes
  6354. (the room for spilled variables), then pop the old values of
  6355. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6356. \code{retq} to return control to the operating system.
  6357. \begin{figure}[tbp]
  6358. \begin{minipage}{0.55\textwidth}
  6359. \begin{tcolorbox}[colback=white]
  6360. % var_test_28.rkt
  6361. % (use-minimal-set-of-registers! #t)
  6362. % 0 -> rcx
  6363. % 1 -> rbx
  6364. %
  6365. % t 0 rcx
  6366. % z 1 rbx
  6367. % w 0 rcx
  6368. % y 2 rbp -16
  6369. % v 1 rbx
  6370. % x 1 rbx
  6371. {\if\edition\racketEd
  6372. \begin{lstlisting}
  6373. start:
  6374. movq $1, %rbx
  6375. movq $42, %rcx
  6376. addq $7, %rbx
  6377. movq %rbx, -16(%rbp)
  6378. addq %rcx, %rbx
  6379. movq -16(%rbp), %rcx
  6380. negq %rcx
  6381. movq %rbx, %rax
  6382. addq %rcx, %rax
  6383. jmp conclusion
  6384. .globl main
  6385. main:
  6386. pushq %rbp
  6387. movq %rsp, %rbp
  6388. pushq %rbx
  6389. subq $8, %rsp
  6390. jmp start
  6391. conclusion:
  6392. addq $8, %rsp
  6393. popq %rbx
  6394. popq %rbp
  6395. retq
  6396. \end{lstlisting}
  6397. \fi}
  6398. {\if\edition\pythonEd\pythonColor
  6399. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6400. \begin{lstlisting}
  6401. .globl main
  6402. main:
  6403. pushq %rbp
  6404. movq %rsp, %rbp
  6405. pushq %rbx
  6406. subq $8, %rsp
  6407. movq $1, %rcx
  6408. movq $42, %rbx
  6409. addq $7, %rcx
  6410. movq %rcx, -16(%rbp)
  6411. addq %rbx, -16(%rbp)
  6412. negq %rcx
  6413. movq -16(%rbp), %rbx
  6414. addq %rcx, %rbx
  6415. movq %rbx, %rdi
  6416. callq print_int
  6417. addq $8, %rsp
  6418. popq %rbx
  6419. popq %rbp
  6420. retq
  6421. \end{lstlisting}
  6422. \fi}
  6423. \end{tcolorbox}
  6424. \end{minipage}
  6425. \caption{The x86 output from the running example
  6426. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6427. and \code{rcx}.}
  6428. \label{fig:running-example-x86}
  6429. \end{figure}
  6430. \begin{exercise}\normalfont\normalsize
  6431. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6432. %
  6433. \racket{
  6434. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6435. list of passes and the call to \code{compiler-tests}.}
  6436. %
  6437. Run the script to test the complete compiler for \LangVar{} that
  6438. performs register allocation.
  6439. \end{exercise}
  6440. \section{Challenge: Move Biasing}
  6441. \label{sec:move-biasing}
  6442. \index{subject}{move biasing}
  6443. This section describes an enhancement to the register allocator,
  6444. called move biasing, for students who are looking for an extra
  6445. challenge.
  6446. {\if\edition\racketEd
  6447. To motivate the need for move biasing we return to the running example,
  6448. but this time we use all the general purpose registers. So, we have
  6449. the following mapping of color numbers to registers.
  6450. \[
  6451. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6452. \]
  6453. Using the same assignment of variables to color numbers that was
  6454. produced by the register allocator described in the last section, we
  6455. get the following program.
  6456. \begin{center}
  6457. \begin{minipage}{0.35\textwidth}
  6458. \begin{lstlisting}
  6459. movq $1, v
  6460. movq $42, w
  6461. movq v, x
  6462. addq $7, x
  6463. movq x, y
  6464. movq x, z
  6465. addq w, z
  6466. movq y, t
  6467. negq t
  6468. movq z, %rax
  6469. addq t, %rax
  6470. jmp conclusion
  6471. \end{lstlisting}
  6472. \end{minipage}
  6473. $\Rightarrow\qquad$
  6474. \begin{minipage}{0.45\textwidth}
  6475. \begin{lstlisting}
  6476. movq $1, %rdx
  6477. movq $42, %rcx
  6478. movq %rdx, %rdx
  6479. addq $7, %rdx
  6480. movq %rdx, %rsi
  6481. movq %rdx, %rdx
  6482. addq %rcx, %rdx
  6483. movq %rsi, %rcx
  6484. negq %rcx
  6485. movq %rdx, %rax
  6486. addq %rcx, %rax
  6487. jmp conclusion
  6488. \end{lstlisting}
  6489. \end{minipage}
  6490. \end{center}
  6491. In this output code there are two \key{movq} instructions that
  6492. can be removed because their source and target are the same. However,
  6493. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6494. register, we could instead remove three \key{movq} instructions. We
  6495. can accomplish this by taking into account which variables appear in
  6496. \key{movq} instructions with which other variables.
  6497. \fi}
  6498. {\if\edition\pythonEd\pythonColor
  6499. %
  6500. To motivate the need for move biasing we return to the running example
  6501. and recall that in section~\ref{sec:patch-instructions} we were able to
  6502. remove three trivial move instructions from the running
  6503. example. However, we could remove another trivial move if we were able
  6504. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6505. We say that two variables $p$ and $q$ are \emph{move
  6506. related}\index{subject}{move related} if they participate together in
  6507. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6508. \key{movq} $q$\key{,} $p$.
  6509. %
  6510. Recall that we color variables that are more saturated before coloring
  6511. variables that are less saturated, and in the case of equally
  6512. saturated variables, we choose randomly. Now we break such ties by
  6513. giving preference to variables that have an available color that is
  6514. the same as the color of a move-related variable.
  6515. %
  6516. Furthermore, when the register allocator chooses a color for a
  6517. variable, it should prefer a color that has already been used for a
  6518. move-related variable if one exists (and assuming that they do not
  6519. interfere). This preference should not override the preference for
  6520. registers over stack locations. So, this preference should be used as
  6521. a tie breaker in choosing between two registers or in choosing between
  6522. two stack locations.
  6523. We recommend representing the move relationships in a graph, similarly
  6524. to how we represented interference. The following is the \emph{move
  6525. graph} for our example.
  6526. {\if\edition\racketEd
  6527. \[
  6528. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6529. \node (rax) at (0,0) {$\ttm{rax}$};
  6530. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6531. \node (t) at (0,2) {$\ttm{t}$};
  6532. \node (z) at (3,2) {$\ttm{z}$};
  6533. \node (x) at (6,2) {$\ttm{x}$};
  6534. \node (y) at (3,0) {$\ttm{y}$};
  6535. \node (w) at (6,0) {$\ttm{w}$};
  6536. \node (v) at (9,0) {$\ttm{v}$};
  6537. \draw (v) to (x);
  6538. \draw (x) to (y);
  6539. \draw (x) to (z);
  6540. \draw (y) to (t);
  6541. \end{tikzpicture}
  6542. \]
  6543. \fi}
  6544. %
  6545. {\if\edition\pythonEd\pythonColor
  6546. \[
  6547. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6548. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6549. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6550. \node (z) at (3,2) {$\ttm{z}$};
  6551. \node (x) at (6,2) {$\ttm{x}$};
  6552. \node (y) at (3,0) {$\ttm{y}$};
  6553. \node (w) at (6,0) {$\ttm{w}$};
  6554. \node (v) at (9,0) {$\ttm{v}$};
  6555. \draw (y) to (t0);
  6556. \draw (z) to (x);
  6557. \draw (z) to (t1);
  6558. \draw (x) to (y);
  6559. \draw (x) to (v);
  6560. \end{tikzpicture}
  6561. \]
  6562. \fi}
  6563. {\if\edition\racketEd
  6564. Now we replay the graph coloring, pausing to see the coloring of
  6565. \code{y}. Recall the following configuration. The most saturated vertices
  6566. were \code{w} and \code{y}.
  6567. \[
  6568. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6569. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6570. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6571. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6572. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6573. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6574. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6575. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6576. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6577. \draw (t1) to (rax);
  6578. \draw (t1) to (z);
  6579. \draw (z) to (y);
  6580. \draw (z) to (w);
  6581. \draw (x) to (w);
  6582. \draw (y) to (w);
  6583. \draw (v) to (w);
  6584. \draw (v) to (rsp);
  6585. \draw (w) to (rsp);
  6586. \draw (x) to (rsp);
  6587. \draw (y) to (rsp);
  6588. \path[-.,bend left=15] (z) edge node {} (rsp);
  6589. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6590. \draw (rax) to (rsp);
  6591. \end{tikzpicture}
  6592. \]
  6593. %
  6594. The last time, we chose to color \code{w} with $0$. This time, we see
  6595. that \code{w} is not move-related to any vertex, but \code{y} is
  6596. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6597. the same color as \code{t}.
  6598. \[
  6599. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6601. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6602. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6603. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6604. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6605. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6606. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6607. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6608. \draw (t1) to (rax);
  6609. \draw (t1) to (z);
  6610. \draw (z) to (y);
  6611. \draw (z) to (w);
  6612. \draw (x) to (w);
  6613. \draw (y) to (w);
  6614. \draw (v) to (w);
  6615. \draw (v) to (rsp);
  6616. \draw (w) to (rsp);
  6617. \draw (x) to (rsp);
  6618. \draw (y) to (rsp);
  6619. \path[-.,bend left=15] (z) edge node {} (rsp);
  6620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6621. \draw (rax) to (rsp);
  6622. \end{tikzpicture}
  6623. \]
  6624. Now \code{w} is the most saturated, so we color it $2$.
  6625. \[
  6626. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6627. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6628. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6629. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6630. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6631. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6632. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6633. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6634. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6635. \draw (t1) to (rax);
  6636. \draw (t1) to (z);
  6637. \draw (z) to (y);
  6638. \draw (z) to (w);
  6639. \draw (x) to (w);
  6640. \draw (y) to (w);
  6641. \draw (v) to (w);
  6642. \draw (v) to (rsp);
  6643. \draw (w) to (rsp);
  6644. \draw (x) to (rsp);
  6645. \draw (y) to (rsp);
  6646. \path[-.,bend left=15] (z) edge node {} (rsp);
  6647. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6648. \draw (rax) to (rsp);
  6649. \end{tikzpicture}
  6650. \]
  6651. At this point, vertices \code{x} and \code{v} are most saturated, but
  6652. \code{x} is move related to \code{y} and \code{z}, so we color
  6653. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6654. \[
  6655. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6656. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6657. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6658. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6659. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6660. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6661. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6662. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6663. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6664. \draw (t1) to (rax);
  6665. \draw (t) to (z);
  6666. \draw (z) to (y);
  6667. \draw (z) to (w);
  6668. \draw (x) to (w);
  6669. \draw (y) to (w);
  6670. \draw (v) to (w);
  6671. \draw (v) to (rsp);
  6672. \draw (w) to (rsp);
  6673. \draw (x) to (rsp);
  6674. \draw (y) to (rsp);
  6675. \path[-.,bend left=15] (z) edge node {} (rsp);
  6676. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6677. \draw (rax) to (rsp);
  6678. \end{tikzpicture}
  6679. \]
  6680. \fi}
  6681. %
  6682. {\if\edition\pythonEd\pythonColor
  6683. Now we replay the graph coloring, pausing before the coloring of
  6684. \code{w}. Recall the following configuration. The most saturated vertices
  6685. were \code{tmp\_1}, \code{w}, and \code{y}.
  6686. \[
  6687. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6688. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6689. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6690. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6691. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6692. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6693. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6694. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6695. \draw (t0) to (t1);
  6696. \draw (t0) to (z);
  6697. \draw (z) to (y);
  6698. \draw (z) to (w);
  6699. \draw (x) to (w);
  6700. \draw (y) to (w);
  6701. \draw (v) to (w);
  6702. \end{tikzpicture}
  6703. \]
  6704. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6705. or \code{y}. Note, however, that \code{w} is not move related to any
  6706. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6707. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6708. \code{y} and color it $0$, we can delete another move instruction.
  6709. \[
  6710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6711. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6712. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6713. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6714. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6715. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6716. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6717. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6718. \draw (t0) to (t1);
  6719. \draw (t0) to (z);
  6720. \draw (z) to (y);
  6721. \draw (z) to (w);
  6722. \draw (x) to (w);
  6723. \draw (y) to (w);
  6724. \draw (v) to (w);
  6725. \end{tikzpicture}
  6726. \]
  6727. Now \code{w} is the most saturated, so we color it $2$.
  6728. \[
  6729. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6730. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6731. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6732. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6733. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6734. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6735. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6736. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6737. \draw (t0) to (t1);
  6738. \draw (t0) to (z);
  6739. \draw (z) to (y);
  6740. \draw (z) to (w);
  6741. \draw (x) to (w);
  6742. \draw (y) to (w);
  6743. \draw (v) to (w);
  6744. \end{tikzpicture}
  6745. \]
  6746. To finish the coloring, \code{x} and \code{v} get $0$ and
  6747. \code{tmp\_1} gets $1$.
  6748. \[
  6749. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6750. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6751. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6752. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6753. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6754. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6755. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6756. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6757. \draw (t0) to (t1);
  6758. \draw (t0) to (z);
  6759. \draw (z) to (y);
  6760. \draw (z) to (w);
  6761. \draw (x) to (w);
  6762. \draw (y) to (w);
  6763. \draw (v) to (w);
  6764. \end{tikzpicture}
  6765. \]
  6766. \fi}
  6767. So, we have the following assignment of variables to registers.
  6768. {\if\edition\racketEd
  6769. \begin{gather*}
  6770. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6771. \ttm{w} \mapsto \key{\%rsi}, \,
  6772. \ttm{x} \mapsto \key{\%rcx}, \,
  6773. \ttm{y} \mapsto \key{\%rcx}, \,
  6774. \ttm{z} \mapsto \key{\%rdx}, \,
  6775. \ttm{t} \mapsto \key{\%rcx} \}
  6776. \end{gather*}
  6777. \fi}
  6778. {\if\edition\pythonEd\pythonColor
  6779. \begin{gather*}
  6780. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6781. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6782. \ttm{x} \mapsto \key{\%rcx}, \,
  6783. \ttm{y} \mapsto \key{\%rcx}, \\
  6784. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6785. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6786. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6787. \end{gather*}
  6788. \fi}
  6789. %
  6790. We apply this register assignment to the running example shown next,
  6791. on the left, to obtain the code in the middle. The
  6792. \code{patch\_instructions} then deletes the trivial moves to obtain
  6793. the code on the right.
  6794. {\if\edition\racketEd
  6795. \begin{center}
  6796. \begin{minipage}{0.2\textwidth}
  6797. \begin{lstlisting}
  6798. movq $1, v
  6799. movq $42, w
  6800. movq v, x
  6801. addq $7, x
  6802. movq x, y
  6803. movq x, z
  6804. addq w, z
  6805. movq y, t
  6806. negq t
  6807. movq z, %rax
  6808. addq t, %rax
  6809. jmp conclusion
  6810. \end{lstlisting}
  6811. \end{minipage}
  6812. $\Rightarrow\qquad$
  6813. \begin{minipage}{0.25\textwidth}
  6814. \begin{lstlisting}
  6815. movq $1, %rcx
  6816. movq $42, %rsi
  6817. movq %rcx, %rcx
  6818. addq $7, %rcx
  6819. movq %rcx, %rcx
  6820. movq %rcx, %rdx
  6821. addq %rsi, %rdx
  6822. movq %rcx, %rcx
  6823. negq %rcx
  6824. movq %rdx, %rax
  6825. addq %rcx, %rax
  6826. jmp conclusion
  6827. \end{lstlisting}
  6828. \end{minipage}
  6829. $\Rightarrow\qquad$
  6830. \begin{minipage}{0.23\textwidth}
  6831. \begin{lstlisting}
  6832. movq $1, %rcx
  6833. movq $42, %rsi
  6834. addq $7, %rcx
  6835. movq %rcx, %rdx
  6836. addq %rsi, %rdx
  6837. negq %rcx
  6838. movq %rdx, %rax
  6839. addq %rcx, %rax
  6840. jmp conclusion
  6841. \end{lstlisting}
  6842. \end{minipage}
  6843. \end{center}
  6844. \fi}
  6845. {\if\edition\pythonEd\pythonColor
  6846. \begin{center}
  6847. \begin{minipage}{0.20\textwidth}
  6848. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6849. movq $1, v
  6850. movq $42, w
  6851. movq v, x
  6852. addq $7, x
  6853. movq x, y
  6854. movq x, z
  6855. addq w, z
  6856. movq y, tmp_0
  6857. negq tmp_0
  6858. movq z, tmp_1
  6859. addq tmp_0, tmp_1
  6860. movq tmp_1, %rdi
  6861. callq _print_int
  6862. \end{lstlisting}
  6863. \end{minipage}
  6864. ${\Rightarrow\qquad}$
  6865. \begin{minipage}{0.35\textwidth}
  6866. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6867. movq $1, %rcx
  6868. movq $42, -16(%rbp)
  6869. movq %rcx, %rcx
  6870. addq $7, %rcx
  6871. movq %rcx, %rcx
  6872. movq %rcx, -8(%rbp)
  6873. addq -16(%rbp), -8(%rbp)
  6874. movq %rcx, %rcx
  6875. negq %rcx
  6876. movq -8(%rbp), -8(%rbp)
  6877. addq %rcx, -8(%rbp)
  6878. movq -8(%rbp), %rdi
  6879. callq _print_int
  6880. \end{lstlisting}
  6881. \end{minipage}
  6882. ${\Rightarrow\qquad}$
  6883. \begin{minipage}{0.20\textwidth}
  6884. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6885. movq $1, %rcx
  6886. movq $42, -16(%rbp)
  6887. addq $7, %rcx
  6888. movq %rcx, -8(%rbp)
  6889. movq -16(%rbp), %rax
  6890. addq %rax, -8(%rbp)
  6891. negq %rcx
  6892. addq %rcx, -8(%rbp)
  6893. movq -8(%rbp), %rdi
  6894. callq print_int
  6895. \end{lstlisting}
  6896. \end{minipage}
  6897. \end{center}
  6898. \fi}
  6899. \begin{exercise}\normalfont\normalsize
  6900. Change your implementation of \code{allocate\_registers} to take move
  6901. biasing into account. Create two new tests that include at least one
  6902. opportunity for move biasing, and visually inspect the output x86
  6903. programs to make sure that your move biasing is working properly. Make
  6904. sure that your compiler still passes all the tests.
  6905. \end{exercise}
  6906. %To do: another neat challenge would be to do
  6907. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6908. %% \subsection{Output of the Running Example}
  6909. %% \label{sec:reg-alloc-output}
  6910. % challenge: prioritize variables based on execution frequencies
  6911. % and the number of uses of a variable
  6912. % challenge: enhance the coloring algorithm using Chaitin's
  6913. % approach of prioritizing high-degree variables
  6914. % by removing low-degree variables (coloring them later)
  6915. % from the interference graph
  6916. \section{Further Reading}
  6917. \label{sec:register-allocation-further-reading}
  6918. Early register allocation algorithms were developed for Fortran
  6919. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6920. of graph coloring began in the late 1970s and early 1980s with the
  6921. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6922. algorithm is based on the following observation of
  6923. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6924. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6925. $v$ removed is also $k$ colorable. To see why, suppose that the
  6926. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6927. different colors, but because there are fewer than $k$ neighbors, there
  6928. will be one or more colors left over to use for coloring $v$ in $G$.
  6929. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6930. less than $k$ from the graph and recursively colors the rest of the
  6931. graph. Upon returning from the recursion, it colors $v$ with one of
  6932. the available colors and returns. \citet{Chaitin:1982vn} augments
  6933. this algorithm to handle spilling as follows. If there are no vertices
  6934. of degree lower than $k$ then pick a vertex at random, spill it,
  6935. remove it from the graph, and proceed recursively to color the rest of
  6936. the graph.
  6937. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6938. move-related and that don't interfere with each other, in a process
  6939. called \emph{coalescing}. Although coalescing decreases the number of
  6940. moves, it can make the graph more difficult to
  6941. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6942. which two variables are merged only if they have fewer than $k$
  6943. neighbors of high degree. \citet{George:1996aa} observes that
  6944. conservative coalescing is sometimes too conservative and made it more
  6945. aggressive by iterating the coalescing with the removal of low-degree
  6946. vertices.
  6947. %
  6948. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6949. also proposed \emph{biased coloring}, in which a variable is assigned to
  6950. the same color as another move-related variable if possible, as
  6951. discussed in section~\ref{sec:move-biasing}.
  6952. %
  6953. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6954. performs coalescing, graph coloring, and spill code insertion until
  6955. all variables have been assigned a location.
  6956. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6957. spilled variables that don't have to be: a high-degree variable can be
  6958. colorable if many of its neighbors are assigned the same color.
  6959. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6960. high-degree vertex is not immediately spilled. Instead the decision is
  6961. deferred until after the recursive call, when it is apparent whether
  6962. there is an available color or not. We observe that this algorithm is
  6963. equivalent to the smallest-last ordering
  6964. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6965. be registers and the rest to be stack locations.
  6966. %% biased coloring
  6967. Earlier editions of the compiler course at Indiana University
  6968. \citep{Dybvig:2010aa} were based on the algorithm of
  6969. \citet{Briggs:1994kx}.
  6970. The smallest-last ordering algorithm is one of many \emph{greedy}
  6971. coloring algorithms. A greedy coloring algorithm visits all the
  6972. vertices in a particular order and assigns each one the first
  6973. available color. An \emph{offline} greedy algorithm chooses the
  6974. ordering up front, prior to assigning colors. The algorithm of
  6975. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6976. ordering does not depend on the colors assigned. Other orderings are
  6977. possible. For example, \citet{Chow:1984ys} ordered variables according
  6978. to an estimate of runtime cost.
  6979. An \emph{online} greedy coloring algorithm uses information about the
  6980. current assignment of colors to influence the order in which the
  6981. remaining vertices are colored. The saturation-based algorithm
  6982. described in this chapter is one such algorithm. We choose to use
  6983. saturation-based coloring because it is fun to introduce graph
  6984. coloring via sudoku!
  6985. A register allocator may choose to map each variable to just one
  6986. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6987. variable to one or more locations. The latter can be achieved by
  6988. \emph{live range splitting}, where a variable is replaced by several
  6989. variables that each handle part of its live
  6990. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6991. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6992. %% replacement algorithm, bottom-up local
  6993. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6994. %% Cooper: top-down (priority bassed), bottom-up
  6995. %% top-down
  6996. %% order variables by priority (estimated cost)
  6997. %% caveat: split variables into two groups:
  6998. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6999. %% color the constrained ones first
  7000. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7001. %% cite J. Cocke for an algorithm that colors variables
  7002. %% in a high-degree first ordering
  7003. %Register Allocation via Usage Counts, Freiburghouse CACM
  7004. \citet{Palsberg:2007si} observes that many of the interference graphs
  7005. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7006. that is, every cycle with four or more edges has an edge that is not
  7007. part of the cycle but that connects two vertices on the cycle. Such
  7008. graphs can be optimally colored by the greedy algorithm with a vertex
  7009. ordering determined by maximum cardinality search.
  7010. In situations in which compile time is of utmost importance, such as
  7011. in just-in-time compilers, graph coloring algorithms can be too
  7012. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7013. be more appropriate.
  7014. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7015. {\if\edition\racketEd
  7016. \addtocontents{toc}{\newpage}
  7017. \fi}
  7018. \chapter{Booleans and Conditionals}
  7019. \label{ch:Lif}
  7020. \setcounter{footnote}{0}
  7021. The \LangVar{} language has only a single kind of value, the
  7022. integers. In this chapter we add a second kind of value, the Booleans,
  7023. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7024. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7025. are written
  7026. \TRUE{}\index{subject}{True@\TRUE{}} and
  7027. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7028. language includes several operations that involve Booleans
  7029. (\key{and}\index{subject}{and@\ANDNAME{}},
  7030. \key{or}\index{subject}{or@\ORNAME{}},
  7031. \key{not}\index{subject}{not@\NOTNAME{}},
  7032. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7033. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7034. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7035. conditional expression\index{subject}{conditional expression}%
  7036. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7037. With the addition of \key{if}, programs can have
  7038. nontrivial control flow\index{subject}{control flow}, which
  7039. %
  7040. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7041. %
  7042. \python{impacts liveness analysis and motivates a new pass named
  7043. \code{explicate\_control}.}
  7044. %
  7045. Also, because we now have two kinds of values, we need to handle
  7046. programs that apply an operation to the wrong kind of value, such as
  7047. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7048. There are two language design options for such situations. One option
  7049. is to signal an error and the other is to provide a wider
  7050. interpretation of the operation. \racket{The Racket
  7051. language}\python{Python} uses a mixture of these two options,
  7052. depending on the operation and the kind of value. For example, the
  7053. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7054. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7055. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7056. %
  7057. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7058. in Racket because \code{car} expects a pair.}
  7059. %
  7060. \python{On the other hand, \code{1[0]} results in a runtime error
  7061. in Python because an ``\code{int} object is not subscriptable.''}
  7062. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7063. design choices as \racket{Racket}\python{Python}, except that much of the
  7064. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7065. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7066. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7067. \python{MyPy} reports a compile-time error
  7068. %
  7069. \racket{because Racket expects the type of the argument to be of the form
  7070. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7071. %
  7072. \python{stating that a ``value of type \code{int} is not indexable.''}
  7073. The \LangIf{} language performs type checking during compilation just as
  7074. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7075. the alternative choice, that is, a dynamically typed language like
  7076. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7077. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7078. restrictive, for example, rejecting \racket{\code{(not
  7079. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7080. fairly simple because the focus of this book is on compilation and not
  7081. type systems, about which there are already several excellent
  7082. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7083. This chapter is organized as follows. We begin by defining the syntax
  7084. and interpreter for the \LangIf{} language
  7085. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7086. checking (aka semantic analysis\index{subject}{semantic analysis})
  7087. and define a type checker for \LangIf{}
  7088. (section~\ref{sec:type-check-Lif}).
  7089. %
  7090. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7091. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7092. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7093. %
  7094. The remaining sections of this chapter discuss how Booleans and
  7095. conditional control flow require changes to the existing compiler
  7096. passes and the addition of new ones. We introduce the \code{shrink}
  7097. pass to translate some operators into others, thereby reducing the
  7098. number of operators that need to be handled in later passes.
  7099. %
  7100. The main event of this chapter is the \code{explicate\_control} pass
  7101. that is responsible for translating \code{if}s into conditional
  7102. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7103. %
  7104. Regarding register allocation, there is the interesting question of
  7105. how to handle conditional \code{goto}s during liveness analysis.
  7106. \section{The \LangIf{} Language}
  7107. \label{sec:lang-if}
  7108. Definitions of the concrete syntax and abstract syntax of the
  7109. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7110. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7111. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7112. literals\index{subject}{literals}
  7113. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7114. \python{, and the \code{if} statement}. We expand the set of
  7115. operators to include
  7116. \begin{enumerate}
  7117. \item the logical operators \key{and}, \key{or}, and \key{not},
  7118. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7119. for comparing integers or Booleans for equality, and
  7120. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7121. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7122. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7123. comparing integers.
  7124. \end{enumerate}
  7125. \racket{We reorganize the abstract syntax for the primitive
  7126. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7127. rule for all of them. This means that the grammar no longer checks
  7128. whether the arity of an operator matches the number of
  7129. arguments. That responsibility is moved to the type checker for
  7130. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7131. \newcommand{\LifGrammarRacket}{
  7132. \begin{array}{lcl}
  7133. \Type &::=& \key{Boolean} \\
  7134. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7135. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7136. \Exp &::=& \itm{bool}
  7137. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7138. \MID (\key{not}\;\Exp) \\
  7139. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7140. \end{array}
  7141. }
  7142. \newcommand{\LifASTRacket}{
  7143. \begin{array}{lcl}
  7144. \Type &::=& \key{Boolean} \\
  7145. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7146. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7147. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7148. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7149. \end{array}
  7150. }
  7151. \newcommand{\LintOpAST}{
  7152. \begin{array}{rcl}
  7153. \Type &::=& \key{Integer} \\
  7154. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7155. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7156. \end{array}
  7157. }
  7158. \newcommand{\LifGrammarPython}{
  7159. \begin{array}{rcl}
  7160. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7161. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7162. \MID \key{not}~\Exp \\
  7163. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7164. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7165. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7166. \end{array}
  7167. }
  7168. \newcommand{\LifASTPython}{
  7169. \begin{array}{lcl}
  7170. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7171. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7172. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7173. \Exp &::=& \BOOL{\itm{bool}}
  7174. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7175. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7176. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7177. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7178. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7179. \end{array}
  7180. }
  7181. \begin{figure}[tp]
  7182. \centering
  7183. \begin{tcolorbox}[colback=white]
  7184. {\if\edition\racketEd
  7185. \[
  7186. \begin{array}{l}
  7187. \gray{\LintGrammarRacket{}} \\ \hline
  7188. \gray{\LvarGrammarRacket{}} \\ \hline
  7189. \LifGrammarRacket{} \\
  7190. \begin{array}{lcl}
  7191. \LangIfM{} &::=& \Exp
  7192. \end{array}
  7193. \end{array}
  7194. \]
  7195. \fi}
  7196. {\if\edition\pythonEd\pythonColor
  7197. \[
  7198. \begin{array}{l}
  7199. \gray{\LintGrammarPython} \\ \hline
  7200. \gray{\LvarGrammarPython} \\ \hline
  7201. \LifGrammarPython \\
  7202. \begin{array}{rcl}
  7203. \LangIfM{} &::=& \Stmt^{*}
  7204. \end{array}
  7205. \end{array}
  7206. \]
  7207. \fi}
  7208. \end{tcolorbox}
  7209. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7210. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7211. \label{fig:Lif-concrete-syntax}
  7212. \end{figure}
  7213. \begin{figure}[tp]
  7214. %\begin{minipage}{0.66\textwidth}
  7215. \begin{tcolorbox}[colback=white]
  7216. \centering
  7217. {\if\edition\racketEd
  7218. \[
  7219. \begin{array}{l}
  7220. \gray{\LintOpAST} \\ \hline
  7221. \gray{\LvarASTRacket{}} \\ \hline
  7222. \LifASTRacket{} \\
  7223. \begin{array}{lcl}
  7224. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7225. \end{array}
  7226. \end{array}
  7227. \]
  7228. \fi}
  7229. {\if\edition\pythonEd\pythonColor
  7230. \[
  7231. \begin{array}{l}
  7232. \gray{\LintASTPython} \\ \hline
  7233. \gray{\LvarASTPython} \\ \hline
  7234. \LifASTPython \\
  7235. \begin{array}{lcl}
  7236. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7237. \end{array}
  7238. \end{array}
  7239. \]
  7240. \fi}
  7241. \end{tcolorbox}
  7242. %\end{minipage}
  7243. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7244. \python{
  7245. \index{subject}{BoolOp@\texttt{BoolOp}}
  7246. \index{subject}{Compare@\texttt{Compare}}
  7247. \index{subject}{Lt@\texttt{Lt}}
  7248. \index{subject}{LtE@\texttt{LtE}}
  7249. \index{subject}{Gt@\texttt{Gt}}
  7250. \index{subject}{GtE@\texttt{GtE}}
  7251. }
  7252. \caption{The abstract syntax of \LangIf{}.}
  7253. \label{fig:Lif-syntax}
  7254. \end{figure}
  7255. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7256. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7257. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7258. evaluate to the corresponding Boolean values, which is
  7259. inherited from the interpreter for \LangInt{} (figure~\ref{fig:interp-Lint-class}).
  7260. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7261. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7262. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7263. \code{and}, \code{or}, and \code{not} behave according to propositional
  7264. logic. In addition, the \code{and} and \code{or} operations perform
  7265. \emph{short-circuit evaluation}.
  7266. %
  7267. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7268. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7269. %
  7270. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7271. evaluated if $e_1$ evaluates to \TRUE{}.
  7272. \racket{With the increase in the number of primitive operations, the
  7273. interpreter would become repetitive without some care. We refactor
  7274. the case for \code{Prim}, moving the code that differs with each
  7275. operation into the \code{interp\_op} method shown in
  7276. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7277. \code{or} operations separately because of their short-circuiting
  7278. behavior.}
  7279. \begin{figure}[tbp]
  7280. \begin{tcolorbox}[colback=white]
  7281. {\if\edition\racketEd
  7282. \begin{lstlisting}
  7283. (define interp-Lif-class
  7284. (class interp-Lvar-class
  7285. (super-new)
  7286. (define/public (interp_op op) ...)
  7287. (define/override ((interp_exp env) e)
  7288. (define recur (interp_exp env))
  7289. (match e
  7290. [(Bool b) b]
  7291. [(If cnd thn els)
  7292. (match (recur cnd)
  7293. [#t (recur thn)]
  7294. [#f (recur els)])]
  7295. [(Prim 'and (list e1 e2))
  7296. (match (recur e1)
  7297. [#t (match (recur e2) [#t #t] [#f #f])]
  7298. [#f #f])]
  7299. [(Prim 'or (list e1 e2))
  7300. (define v1 (recur e1))
  7301. (match v1
  7302. [#t #t]
  7303. [#f (match (recur e2) [#t #t] [#f #f])])]
  7304. [(Prim op args)
  7305. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7306. [else ((super interp_exp env) e)]))
  7307. ))
  7308. (define (interp_Lif p)
  7309. (send (new interp-Lif-class) interp_program p))
  7310. \end{lstlisting}
  7311. \fi}
  7312. {\if\edition\pythonEd\pythonColor
  7313. \begin{lstlisting}
  7314. class InterpLif(InterpLvar):
  7315. def interp_exp(self, e, env):
  7316. match e:
  7317. case IfExp(test, body, orelse):
  7318. if self.interp_exp(test, env):
  7319. return self.interp_exp(body, env)
  7320. else:
  7321. return self.interp_exp(orelse, env)
  7322. case UnaryOp(Not(), v):
  7323. return not self.interp_exp(v, env)
  7324. case BoolOp(And(), values):
  7325. if self.interp_exp(values[0], env):
  7326. return self.interp_exp(values[1], env)
  7327. else:
  7328. return False
  7329. case BoolOp(Or(), values):
  7330. if self.interp_exp(values[0], env):
  7331. return True
  7332. else:
  7333. return self.interp_exp(values[1], env)
  7334. case Compare(left, [cmp], [right]):
  7335. l = self.interp_exp(left, env)
  7336. r = self.interp_exp(right, env)
  7337. return self.interp_cmp(cmp)(l, r)
  7338. case _:
  7339. return super().interp_exp(e, env)
  7340. def interp_stmt(self, s, env, cont):
  7341. match s:
  7342. case If(test, body, orelse):
  7343. match self.interp_exp(test, env):
  7344. case True:
  7345. return self.interp_stmts(body + cont, env)
  7346. case False:
  7347. return self.interp_stmts(orelse + cont, env)
  7348. case _:
  7349. return super().interp_stmt(s, env, cont)
  7350. ...
  7351. \end{lstlisting}
  7352. \fi}
  7353. \end{tcolorbox}
  7354. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7355. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7356. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7357. \label{fig:interp-Lif}
  7358. \end{figure}
  7359. {\if\edition\racketEd
  7360. \begin{figure}[tbp]
  7361. \begin{tcolorbox}[colback=white]
  7362. \begin{lstlisting}
  7363. (define/public (interp_op op)
  7364. (match op
  7365. ['+ fx+]
  7366. ['- fx-]
  7367. ['read read-fixnum]
  7368. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7369. ['eq? (lambda (v1 v2)
  7370. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7371. (and (boolean? v1) (boolean? v2))
  7372. (and (vector? v1) (vector? v2)))
  7373. (eq? v1 v2)]))]
  7374. ['< (lambda (v1 v2)
  7375. (cond [(and (fixnum? v1) (fixnum? v2))
  7376. (< v1 v2)]))]
  7377. ['<= (lambda (v1 v2)
  7378. (cond [(and (fixnum? v1) (fixnum? v2))
  7379. (<= v1 v2)]))]
  7380. ['> (lambda (v1 v2)
  7381. (cond [(and (fixnum? v1) (fixnum? v2))
  7382. (> v1 v2)]))]
  7383. ['>= (lambda (v1 v2)
  7384. (cond [(and (fixnum? v1) (fixnum? v2))
  7385. (>= v1 v2)]))]
  7386. [else (error 'interp_op "unknown operator")]))
  7387. \end{lstlisting}
  7388. \end{tcolorbox}
  7389. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7390. \label{fig:interp-op-Lif}
  7391. \end{figure}
  7392. \fi}
  7393. {\if\edition\pythonEd\pythonColor
  7394. \begin{figure}
  7395. \begin{tcolorbox}[colback=white]
  7396. \begin{lstlisting}
  7397. class InterpLif(InterpLvar):
  7398. ...
  7399. def interp_cmp(self, cmp):
  7400. match cmp:
  7401. case Lt():
  7402. return lambda x, y: x < y
  7403. case LtE():
  7404. return lambda x, y: x <= y
  7405. case Gt():
  7406. return lambda x, y: x > y
  7407. case GtE():
  7408. return lambda x, y: x >= y
  7409. case Eq():
  7410. return lambda x, y: x == y
  7411. case NotEq():
  7412. return lambda x, y: x != y
  7413. \end{lstlisting}
  7414. \end{tcolorbox}
  7415. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7416. \label{fig:interp-cmp-Lif}
  7417. \end{figure}
  7418. \fi}
  7419. \section{Type Checking \LangIf{} Programs}
  7420. \label{sec:type-check-Lif}
  7421. It is helpful to think about type checking\index{subject}{type
  7422. checking} in two complementary ways. A type checker predicts the
  7423. type of value that will be produced by each expression in the program.
  7424. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7425. type checker should predict that {\if\edition\racketEd
  7426. \begin{lstlisting}
  7427. (+ 10 (- (+ 12 20)))
  7428. \end{lstlisting}
  7429. \fi}
  7430. {\if\edition\pythonEd\pythonColor
  7431. \begin{lstlisting}
  7432. 10 + -(12 + 20)
  7433. \end{lstlisting}
  7434. \fi}
  7435. \noindent produces a value of type \INTTY{}, whereas
  7436. {\if\edition\racketEd
  7437. \begin{lstlisting}
  7438. (and (not #f) #t)
  7439. \end{lstlisting}
  7440. \fi}
  7441. {\if\edition\pythonEd\pythonColor
  7442. \begin{lstlisting}
  7443. (not False) and True
  7444. \end{lstlisting}
  7445. \fi}
  7446. \noindent produces a value of type \BOOLTY{}.
  7447. A second way to think about type checking is that it enforces a set of
  7448. rules about which operators can be applied to which kinds of
  7449. values. For example, our type checker for \LangIf{} signals an error
  7450. for the following expression:
  7451. %
  7452. {\if\edition\racketEd
  7453. \begin{lstlisting}
  7454. (not (+ 10 (- (+ 12 20))))
  7455. \end{lstlisting}
  7456. \fi}
  7457. {\if\edition\pythonEd\pythonColor
  7458. \begin{lstlisting}
  7459. not (10 + -(12 + 20))
  7460. \end{lstlisting}
  7461. \fi}
  7462. \noindent The subexpression
  7463. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7464. \python{\code{(10 + -(12 + 20))}}
  7465. has type \INTTY{}, but the type checker enforces the rule that the
  7466. argument of \code{not} must be an expression of type \BOOLTY{}.
  7467. We implement type checking using classes and methods because they
  7468. provide the open recursion needed to reuse code as we extend the type
  7469. checker in subsequent chapters, analogous to the use of classes and methods
  7470. for the interpreters (section~\ref{sec:extensible-interp}).
  7471. We separate the type checker for the \LangVar{} subset into its own
  7472. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7473. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7474. from the type checker for \LangVar{}. These type checkers are in the
  7475. files
  7476. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7477. and
  7478. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7479. of the support code.
  7480. %
  7481. Each type checker is a structurally recursive function over the AST.
  7482. Given an input expression \code{e}, the type checker either signals an
  7483. error or returns \racket{an expression and its type.}\python{its type.}
  7484. %
  7485. \racket{It returns an expression because there are situations in which
  7486. we want to change or update the expression.}
  7487. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7488. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7489. constant is \INTTY{}. To handle variables, the type checker uses the
  7490. environment \code{env} to map variables to types.
  7491. %
  7492. \racket{Consider the case for \key{let}. We type check the
  7493. initializing expression to obtain its type \key{T} and then
  7494. associate type \code{T} with the variable \code{x} in the
  7495. environment used to type check the body of the \key{let}. Thus,
  7496. when the type checker encounters a use of variable \code{x}, it can
  7497. find its type in the environment.}
  7498. %
  7499. \python{Consider the case for assignment. We type check the
  7500. initializing expression to obtain its type \key{t}. If the variable
  7501. \code{id} is already in the environment because there was a
  7502. prior assignment, we check that this initializer has the same type
  7503. as the prior one. If this is the first assignment to the variable,
  7504. we associate type \code{t} with the variable \code{id} in the
  7505. environment. Thus, when the type checker encounters a use of
  7506. variable \code{x}, it can find its type in the environment.}
  7507. %
  7508. \racket{Regarding primitive operators, we recursively analyze the
  7509. arguments and then invoke \code{type\_check\_op} to check whether
  7510. the argument types are allowed.}
  7511. %
  7512. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7513. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7514. \racket{Several auxiliary methods are used in the type checker. The
  7515. method \code{operator-types} defines a dictionary that maps the
  7516. operator names to their parameter and return types. The
  7517. \code{type-equal?} method determines whether two types are equal,
  7518. which for now simply dispatches to \code{equal?} (deep
  7519. equality). The \code{check-type-equal?} method triggers an error if
  7520. the two types are not equal. The \code{type-check-op} method looks
  7521. up the operator in the \code{operator-types} dictionary and then
  7522. checks whether the argument types are equal to the parameter types.
  7523. The result is the return type of the operator.}
  7524. %
  7525. \python{The auxiliary method \code{check\_type\_equal} triggers
  7526. an error if the two types are not equal.}
  7527. \begin{figure}[tbp]
  7528. \begin{tcolorbox}[colback=white]
  7529. {\if\edition\racketEd
  7530. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7531. (define type-check-Lvar-class
  7532. (class object%
  7533. (super-new)
  7534. (define/public (operator-types)
  7535. '((+ . ((Integer Integer) . Integer))
  7536. (- . ((Integer Integer) . Integer))
  7537. (read . (() . Integer))))
  7538. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7539. (define/public (check-type-equal? t1 t2 e)
  7540. (unless (type-equal? t1 t2)
  7541. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7542. (define/public (type-check-op op arg-types e)
  7543. (match (dict-ref (operator-types) op)
  7544. [`(,param-types . ,return-type)
  7545. (for ([at arg-types] [pt param-types])
  7546. (check-type-equal? at pt e))
  7547. return-type]
  7548. [else (error 'type-check-op "unrecognized ~a" op)]))
  7549. (define/public (type-check-exp env)
  7550. (lambda (e)
  7551. (match e
  7552. [(Int n) (values (Int n) 'Integer)]
  7553. [(Var x) (values (Var x) (dict-ref env x))]
  7554. [(Let x e body)
  7555. (define-values (e^ Te) ((type-check-exp env) e))
  7556. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7557. (values (Let x e^ b) Tb)]
  7558. [(Prim op es)
  7559. (define-values (new-es ts)
  7560. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7561. (values (Prim op new-es) (type-check-op op ts e))]
  7562. [else (error 'type-check-exp "couldn't match" e)])))
  7563. (define/public (type-check-program e)
  7564. (match e
  7565. [(Program info body)
  7566. (define-values (body^ Tb) ((type-check-exp '()) body))
  7567. (check-type-equal? Tb 'Integer body)
  7568. (Program info body^)]
  7569. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7570. ))
  7571. (define (type-check-Lvar p)
  7572. (send (new type-check-Lvar-class) type-check-program p))
  7573. \end{lstlisting}
  7574. \fi}
  7575. {\if\edition\pythonEd\pythonColor
  7576. \begin{lstlisting}[escapechar=`]
  7577. class TypeCheckLvar:
  7578. def check_type_equal(self, t1, t2, e):
  7579. if t1 != t2:
  7580. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7581. raise Exception(msg)
  7582. def type_check_exp(self, e, env):
  7583. match e:
  7584. case BinOp(left, (Add() | Sub()), right):
  7585. l = self.type_check_exp(left, env)
  7586. check_type_equal(l, int, left)
  7587. r = self.type_check_exp(right, env)
  7588. check_type_equal(r, int, right)
  7589. return int
  7590. case UnaryOp(USub(), v):
  7591. t = self.type_check_exp(v, env)
  7592. check_type_equal(t, int, v)
  7593. return int
  7594. case Name(id):
  7595. return env[id]
  7596. case Constant(value) if isinstance(value, int):
  7597. return int
  7598. case Call(Name('input_int'), []):
  7599. return int
  7600. def type_check_stmts(self, ss, env):
  7601. if len(ss) == 0:
  7602. return
  7603. match ss[0]:
  7604. case Assign([Name(id)], value):
  7605. t = self.type_check_exp(value, env)
  7606. if id in env:
  7607. check_type_equal(env[id], t, value)
  7608. else:
  7609. env[id] = t
  7610. return self.type_check_stmts(ss[1:], env)
  7611. case Expr(Call(Name('print'), [arg])):
  7612. t = self.type_check_exp(arg, env)
  7613. check_type_equal(t, int, arg)
  7614. return self.type_check_stmts(ss[1:], env)
  7615. case Expr(value):
  7616. self.type_check_exp(value, env)
  7617. return self.type_check_stmts(ss[1:], env)
  7618. def type_check_P(self, p):
  7619. match p:
  7620. case Module(body):
  7621. self.type_check_stmts(body, {})
  7622. \end{lstlisting}
  7623. \fi}
  7624. \end{tcolorbox}
  7625. \caption{Type checker for the \LangVar{} language.}
  7626. \label{fig:type-check-Lvar}
  7627. \end{figure}
  7628. \begin{figure}[tbp]
  7629. \begin{tcolorbox}[colback=white]
  7630. {\if\edition\racketEd
  7631. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7632. (define type-check-Lif-class
  7633. (class type-check-Lvar-class
  7634. (super-new)
  7635. (inherit check-type-equal?)
  7636. (define/override (operator-types)
  7637. (append '((and . ((Boolean Boolean) . Boolean))
  7638. (or . ((Boolean Boolean) . Boolean))
  7639. (< . ((Integer Integer) . Boolean))
  7640. (<= . ((Integer Integer) . Boolean))
  7641. (> . ((Integer Integer) . Boolean))
  7642. (>= . ((Integer Integer) . Boolean))
  7643. (not . ((Boolean) . Boolean)))
  7644. (super operator-types)))
  7645. (define/override (type-check-exp env)
  7646. (lambda (e)
  7647. (match e
  7648. [(Bool b) (values (Bool b) 'Boolean)]
  7649. [(Prim 'eq? (list e1 e2))
  7650. (define-values (e1^ T1) ((type-check-exp env) e1))
  7651. (define-values (e2^ T2) ((type-check-exp env) e2))
  7652. (check-type-equal? T1 T2 e)
  7653. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7654. [(If cnd thn els)
  7655. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7656. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7657. (define-values (els^ Te) ((type-check-exp env) els))
  7658. (check-type-equal? Tc 'Boolean e)
  7659. (check-type-equal? Tt Te e)
  7660. (values (If cnd^ thn^ els^) Te)]
  7661. [else ((super type-check-exp env) e)])))
  7662. ))
  7663. (define (type-check-Lif p)
  7664. (send (new type-check-Lif-class) type-check-program p))
  7665. \end{lstlisting}
  7666. \fi}
  7667. {\if\edition\pythonEd\pythonColor
  7668. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7669. class TypeCheckLif(TypeCheckLvar):
  7670. def type_check_exp(self, e, env):
  7671. match e:
  7672. case Constant(value) if isinstance(value, bool):
  7673. return bool
  7674. case BinOp(left, Sub(), right):
  7675. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7676. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7677. return int
  7678. case UnaryOp(Not(), v):
  7679. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7680. return bool
  7681. case BoolOp(op, values):
  7682. left = values[0] ; right = values[1]
  7683. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7684. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7685. return bool
  7686. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7687. or isinstance(cmp, NotEq):
  7688. l = self.type_check_exp(left, env)
  7689. r = self.type_check_exp(right, env)
  7690. check_type_equal(l, r, e)
  7691. return bool
  7692. case Compare(left, [cmp], [right]):
  7693. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7694. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7695. return bool
  7696. case IfExp(test, body, orelse):
  7697. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7698. b = self.type_check_exp(body, env)
  7699. o = self.type_check_exp(orelse, env)
  7700. check_type_equal(b, o, e)
  7701. return b
  7702. case _:
  7703. return super().type_check_exp(e, env)
  7704. def type_check_stmts(self, ss, env):
  7705. if len(ss) == 0:
  7706. return
  7707. match ss[0]:
  7708. case If(test, body, orelse):
  7709. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7710. b = self.type_check_stmts(body, env)
  7711. o = self.type_check_stmts(orelse, env)
  7712. check_type_equal(b, o, ss[0])
  7713. return self.type_check_stmts(ss[1:], env)
  7714. case _:
  7715. return super().type_check_stmts(ss, env)
  7716. \end{lstlisting}
  7717. \fi}
  7718. \end{tcolorbox}
  7719. \caption{Type checker for the \LangIf{} language.}
  7720. \label{fig:type-check-Lif}
  7721. \end{figure}
  7722. The definition of the type checker for \LangIf{} is shown in
  7723. figure~\ref{fig:type-check-Lif}.
  7724. %
  7725. The type of a Boolean constant is \BOOLTY{}.
  7726. %
  7727. \racket{The \code{operator-types} function adds dictionary entries for
  7728. the new operators.}
  7729. %
  7730. \python{The logical \code{not} operator requires its argument to be a
  7731. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7732. and logical \code{or} operators.}
  7733. %
  7734. The equality operator requires the two arguments to have the same type,
  7735. and therefore we handle it separately from the other operators.
  7736. %
  7737. \python{The other comparisons (less-than, etc.) require their
  7738. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7739. %
  7740. The condition of an \code{if} must
  7741. be of \BOOLTY{} type, and the two branches must have the same type.
  7742. \begin{exercise}\normalfont\normalsize
  7743. Create ten new test programs in \LangIf{}. Half the programs should
  7744. have a type error.
  7745. \racket{For those programs, create an empty file with the
  7746. same base name and with file extension \code{.tyerr}. For example, if
  7747. the test \code{cond\_test\_14.rkt}
  7748. is expected to error, then create
  7749. an empty file named \code{cond\_test\_14.tyerr}.
  7750. This indicates to \code{interp-tests} and
  7751. \code{compiler-tests} that a type error is expected.}
  7752. %
  7753. The other half of the test programs should not have type errors.
  7754. %
  7755. \racket{In the \code{run-tests.rkt} script, change the second argument
  7756. of \code{interp-tests} and \code{compiler-tests} to
  7757. \code{type-check-Lif}, which causes the type checker to run prior to
  7758. the compiler passes. Temporarily change the \code{passes} to an
  7759. empty list and run the script, thereby checking that the new test
  7760. programs either type check or do not, as intended.}
  7761. %
  7762. Run the test script to check that these test programs type check as
  7763. expected.
  7764. \end{exercise}
  7765. \clearpage
  7766. \section{The \LangCIf{} Intermediate Language}
  7767. \label{sec:Cif}
  7768. {\if\edition\racketEd
  7769. %
  7770. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7771. comparison operators to the \Exp{} nonterminal and the literals
  7772. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7773. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7774. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7775. comparison operation and the branches are \code{goto} statements,
  7776. making it straightforward to compile \code{if} statements to x86. The
  7777. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7778. expressions. A \code{goto} statement transfers control to the $\Tail$
  7779. expression corresponding to its label.
  7780. %
  7781. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7782. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7783. defines its abstract syntax.
  7784. %
  7785. \fi}
  7786. %
  7787. {\if\edition\pythonEd\pythonColor
  7788. %
  7789. The output of \key{explicate\_control} is a language similar to the
  7790. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7791. \code{goto} statements, so we name it \LangCIf{}.
  7792. %
  7793. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7794. the arguments of operators are restricted to atomic expressions. The
  7795. \LangCIf{} language does not include \code{if} expressions, but it does
  7796. include a restricted form of \code{if} statement. The condition must be
  7797. a comparison, and the two branches may contain only \code{goto}
  7798. statements. These restrictions make it easier to translate \code{if}
  7799. statements to x86. The \LangCIf{} language also adds a \code{return}
  7800. statement to finish the program with a specified value.
  7801. %
  7802. The \key{CProgram} construct contains a dictionary mapping labels to
  7803. lists of statements that end with a \emph{tail} statement, which is
  7804. either a \code{return} statement, a \code{goto}, or an
  7805. \code{if} statement.
  7806. %
  7807. A \code{goto} transfers control to the sequence of statements
  7808. associated with its label.
  7809. %
  7810. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7811. and figure~\ref{fig:c1-syntax} shows its
  7812. abstract syntax.
  7813. %
  7814. \fi}
  7815. %
  7816. \newcommand{\CifGrammarRacket}{
  7817. \begin{array}{lcl}
  7818. \Atm &::=& \itm{bool} \\
  7819. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7820. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7821. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7822. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7823. \end{array}
  7824. }
  7825. \newcommand{\CifASTRacket}{
  7826. \begin{array}{lcl}
  7827. \Atm &::=& \BOOL{\itm{bool}} \\
  7828. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7829. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7830. \Tail &::= & \GOTO{\itm{label}} \\
  7831. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7832. \end{array}
  7833. }
  7834. \newcommand{\CifGrammarPython}{
  7835. \begin{array}{lcl}
  7836. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7837. \Exp &::= & \Atm \MID \CREAD{}
  7838. \MID \CUNIOP{\key{-}}{\Atm}
  7839. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7840. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7841. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7842. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7843. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7844. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7845. \end{array}
  7846. }
  7847. \newcommand{\CifASTPython}{
  7848. \begin{array}{lcl}
  7849. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7850. \Exp &::= & \Atm \MID \READ{}
  7851. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7852. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7853. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7854. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7855. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7856. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7857. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7858. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7859. \end{array}
  7860. }
  7861. \begin{figure}[tbp]
  7862. \begin{tcolorbox}[colback=white]
  7863. \small
  7864. {\if\edition\racketEd
  7865. \[
  7866. \begin{array}{l}
  7867. \gray{\CvarGrammarRacket} \\ \hline
  7868. \CifGrammarRacket \\
  7869. \begin{array}{lcl}
  7870. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7871. \end{array}
  7872. \end{array}
  7873. \]
  7874. \fi}
  7875. {\if\edition\pythonEd\pythonColor
  7876. \[
  7877. \begin{array}{l}
  7878. \CifGrammarPython \\
  7879. \begin{array}{lcl}
  7880. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7881. \end{array}
  7882. \end{array}
  7883. \]
  7884. \fi}
  7885. \end{tcolorbox}
  7886. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7887. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7888. \label{fig:c1-concrete-syntax}
  7889. \end{figure}
  7890. \begin{figure}[tp]
  7891. \begin{tcolorbox}[colback=white]
  7892. \small
  7893. {\if\edition\racketEd
  7894. \[
  7895. \begin{array}{l}
  7896. \gray{\CvarASTRacket} \\ \hline
  7897. \CifASTRacket \\
  7898. \begin{array}{lcl}
  7899. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7900. \end{array}
  7901. \end{array}
  7902. \]
  7903. \fi}
  7904. {\if\edition\pythonEd\pythonColor
  7905. \[
  7906. \begin{array}{l}
  7907. \CifASTPython \\
  7908. \begin{array}{lcl}
  7909. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7910. \end{array}
  7911. \end{array}
  7912. \]
  7913. \fi}
  7914. \end{tcolorbox}
  7915. \racket{
  7916. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7917. }
  7918. \index{subject}{Goto@\texttt{Goto}}
  7919. \index{subject}{Return@\texttt{Return}}
  7920. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7921. (figure~\ref{fig:c0-syntax})}.}
  7922. \label{fig:c1-syntax}
  7923. \end{figure}
  7924. \section{The \LangXIf{} Language}
  7925. \label{sec:x86-if}
  7926. \index{subject}{x86}
  7927. To implement Booleans, the new logical operations, the
  7928. comparison operations, and the \key{if} expression\python{ and
  7929. statement}, we delve further into the x86
  7930. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7931. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7932. subset of x86, which includes instructions for logical operations,
  7933. comparisons, and \racket{conditional} jumps.
  7934. %
  7935. \python{The abstract syntax for an \LangXIf{} program contains a
  7936. dictionary mapping labels to sequences of instructions, each of
  7937. which we refer to as a \emph{basic block}\index{subject}{basic
  7938. block}.}
  7939. As x86 does not provide direct support for Booleans, we take the usual
  7940. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7941. \code{False} as $0$.
  7942. Furthermore, x86 does not provide an instruction that directly
  7943. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7944. However, the \code{xorq} instruction can be used to encode \code{not}.
  7945. The \key{xorq} instruction takes two arguments, performs a pairwise
  7946. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7947. and writes the results into its second argument. Recall the following
  7948. truth table for exclusive-or:
  7949. \begin{center}
  7950. \begin{tabular}{l|cc}
  7951. & 0 & 1 \\ \hline
  7952. 0 & 0 & 1 \\
  7953. 1 & 1 & 0
  7954. \end{tabular}
  7955. \end{center}
  7956. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7957. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7958. for the bit $1$, the result is the opposite of the second bit. Thus,
  7959. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7960. the first argument, as follows, where $\Arg$ is the translation of
  7961. $\Atm$ to x86:
  7962. \[
  7963. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7964. \qquad\Rightarrow\qquad
  7965. \begin{array}{l}
  7966. \key{movq}~ \Arg\key{,} \Var\\
  7967. \key{xorq}~ \key{\$1,} \Var
  7968. \end{array}
  7969. \]
  7970. \newcommand{\GrammarXIf}{
  7971. \begin{array}{lcl}
  7972. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7973. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7974. \Arg &::=& \key{\%}\itm{bytereg}\\
  7975. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7976. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7977. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7978. \MID \key{set}cc~\Arg
  7979. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7980. &\MID& \key{j}cc~\itm{label} \\
  7981. \end{array}
  7982. }
  7983. \begin{figure}[tp]
  7984. \begin{tcolorbox}[colback=white]
  7985. \[
  7986. \begin{array}{l}
  7987. \gray{\GrammarXInt} \\ \hline
  7988. \GrammarXIf \\
  7989. \begin{array}{lcl}
  7990. \LangXIfM{} &::= & \key{.globl main} \\
  7991. & & \key{main:} \; \Instr\ldots
  7992. \end{array}
  7993. \end{array}
  7994. \]
  7995. \end{tcolorbox}
  7996. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7997. \label{fig:x86-1-concrete}
  7998. \end{figure}
  7999. \newcommand{\ASTXIfRacket}{
  8000. \begin{array}{lcl}
  8001. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8002. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8003. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8004. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8005. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8006. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8007. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8008. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8009. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8010. \end{array}
  8011. }
  8012. \newcommand{\ASTXIfPython}{
  8013. \begin{array}{lcl}
  8014. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8015. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8016. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8017. \MID \BYTEREG{\itm{bytereg}} \\
  8018. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8019. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8020. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8021. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8022. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8023. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8024. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8025. \end{array}
  8026. }
  8027. \begin{figure}[tp]
  8028. \begin{tcolorbox}[colback=white]
  8029. \small
  8030. {\if\edition\racketEd
  8031. \[\arraycolsep=3pt
  8032. \begin{array}{l}
  8033. \gray{\ASTXIntRacket} \\ \hline
  8034. \ASTXIfRacket \\
  8035. \begin{array}{lcl}
  8036. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8037. \end{array}
  8038. \end{array}
  8039. \]
  8040. \fi}
  8041. %
  8042. {\if\edition\pythonEd\pythonColor
  8043. \[
  8044. \begin{array}{l}
  8045. \gray{\ASTXIntPython} \\ \hline
  8046. \ASTXIfPython \\
  8047. \begin{array}{lcl}
  8048. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8049. \end{array}
  8050. \end{array}
  8051. \]
  8052. \fi}
  8053. \end{tcolorbox}
  8054. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8055. \label{fig:x86-1}
  8056. \end{figure}
  8057. Next we consider the x86 instructions that are relevant for compiling
  8058. the comparison operations. The \key{cmpq} instruction compares its two
  8059. arguments to determine whether one argument is less than, equal to, or
  8060. greater than the other argument. The \key{cmpq} instruction is unusual
  8061. regarding the order of its arguments and where the result is
  8062. placed. The argument order is backward: if you want to test whether
  8063. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8064. \key{cmpq} is placed in the special EFLAGS register. This register
  8065. cannot be accessed directly, but it can be queried by a number of
  8066. instructions, including the \key{set} instruction. The instruction
  8067. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8068. depending on whether the contents of the EFLAGS register matches the
  8069. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8070. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8071. The \key{set} instruction has a quirk in that its destination argument
  8072. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8073. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8074. register. Thankfully, the \key{movzbq} instruction can be used to
  8075. move from a single-byte register to a normal 64-bit register. The
  8076. abstract syntax for the \code{set} instruction differs from the
  8077. concrete syntax in that it separates the instruction name from the
  8078. condition code.
  8079. \python{The x86 instructions for jumping are relevant to the
  8080. compilation of \key{if} expressions.}
  8081. %
  8082. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8083. counter to the address of the instruction after the specified
  8084. label.}
  8085. %
  8086. \racket{The x86 instruction for conditional jump is relevant to the
  8087. compilation of \key{if} expressions.}
  8088. %
  8089. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8090. counter to point to the instruction after \itm{label}, depending on
  8091. whether the result in the EFLAGS register matches the condition code
  8092. \itm{cc}; otherwise, the jump instruction falls through to the next
  8093. instruction. Like the abstract syntax for \code{set}, the abstract
  8094. syntax for conditional jump separates the instruction name from the
  8095. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8096. corresponds to \code{jle foo}. Because the conditional jump instruction
  8097. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8098. a \key{cmpq} instruction to set the EFLAGS register.
  8099. \section{Shrink the \LangIf{} Language}
  8100. \label{sec:shrink-Lif}
  8101. The \code{shrink} pass translates some of the language features into
  8102. other features, thereby reducing the kinds of expressions in the
  8103. language. For example, the short-circuiting nature of the \code{and}
  8104. and \code{or} logical operators can be expressed using \code{if} as
  8105. follows.
  8106. \begin{align*}
  8107. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8108. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8109. \end{align*}
  8110. By performing these translations in the front end of the compiler,
  8111. subsequent passes of the compiler can be shorter.
  8112. On the other hand, translations sometimes reduce the efficiency of the
  8113. generated code by increasing the number of instructions. For example,
  8114. expressing subtraction in terms of addition and negation
  8115. \[
  8116. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8117. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8118. \]
  8119. produces code with two x86 instructions (\code{negq} and \code{addq})
  8120. instead of just one (\code{subq}). Thus, we do not recommend
  8121. translating subtraction into addition and negation.
  8122. \begin{exercise}\normalfont\normalsize
  8123. %
  8124. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8125. the language by translating them to \code{if} expressions in \LangIf{}.
  8126. %
  8127. Create four test programs that involve these operators.
  8128. %
  8129. {\if\edition\racketEd
  8130. In the \code{run-tests.rkt} script, add the following entry for
  8131. \code{shrink} to the list of passes (it should be the only pass at
  8132. this point).
  8133. \begin{lstlisting}
  8134. (list "shrink" shrink interp_Lif type-check-Lif)
  8135. \end{lstlisting}
  8136. This instructs \code{interp-tests} to run the interpreter
  8137. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8138. output of \code{shrink}.
  8139. \fi}
  8140. %
  8141. Run the script to test your compiler on all the test programs.
  8142. \end{exercise}
  8143. {\if\edition\racketEd
  8144. \section{Uniquify Variables}
  8145. \label{sec:uniquify-Lif}
  8146. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8147. \code{if} expressions.
  8148. \begin{exercise}\normalfont\normalsize
  8149. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8150. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8151. \begin{lstlisting}
  8152. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8153. \end{lstlisting}
  8154. Run the script to test your compiler.
  8155. \end{exercise}
  8156. \fi}
  8157. \section{Remove Complex Operands}
  8158. \label{sec:remove-complex-opera-Lif}
  8159. The output language of \code{remove\_complex\_operands} is
  8160. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8161. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8162. but the \code{if} expression is not. All three subexpressions of an
  8163. \code{if} are allowed to be complex expressions, but the operands of
  8164. the \code{not} operator and comparison operators must be atomic.
  8165. %
  8166. \python{We add a new language form, the \code{Begin} expression, to aid
  8167. in the translation of \code{if} expressions. When we recursively
  8168. process the two branches of the \code{if}, we generate temporary
  8169. variables and their initializing expressions. However, these
  8170. expressions may contain side effects and should be executed only
  8171. when the condition of the \code{if} is true (for the ``then''
  8172. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8173. provides a way to initialize the temporary variables within the two branches
  8174. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8175. form executes the statements $ss$ and then returns the result of
  8176. expression $e$.}
  8177. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8178. the new features in \LangIf{}. In recursively processing
  8179. subexpressions, recall that you should invoke \code{rco\_atom} when
  8180. the output needs to be an \Atm{} (as specified in the grammar for
  8181. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8182. \Exp{}. Regarding \code{if}, it is particularly important
  8183. \emph{not} to replace its condition with a temporary variable, because
  8184. that would interfere with the generation of high-quality output in the
  8185. upcoming \code{explicate\_control} pass.
  8186. \newcommand{\LifMonadASTRacket}{
  8187. \begin{array}{rcl}
  8188. \Atm &::=& \BOOL{\itm{bool}}\\
  8189. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8190. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8191. \MID \IF{\Exp}{\Exp}{\Exp}
  8192. \end{array}
  8193. }
  8194. \newcommand{\LifMonadASTPython}{
  8195. \begin{array}{rcl}
  8196. \Atm &::=& \BOOL{\itm{bool}}\\
  8197. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8198. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8199. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8200. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8201. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8202. \end{array}
  8203. }
  8204. \begin{figure}[tp]
  8205. \centering
  8206. \begin{tcolorbox}[colback=white]
  8207. {\if\edition\racketEd
  8208. \[
  8209. \begin{array}{l}
  8210. \gray{\LvarMonadASTRacket} \\ \hline
  8211. \LifMonadASTRacket \\
  8212. \begin{array}{rcl}
  8213. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8214. \end{array}
  8215. \end{array}
  8216. \]
  8217. \fi}
  8218. {\if\edition\pythonEd\pythonColor
  8219. \[
  8220. \begin{array}{l}
  8221. \gray{\LvarMonadASTPython} \\ \hline
  8222. \LifMonadASTPython \\
  8223. \begin{array}{rcl}
  8224. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8225. \end{array}
  8226. \end{array}
  8227. \]
  8228. \fi}
  8229. \end{tcolorbox}
  8230. \python{\index{subject}{Begin@\texttt{Begin}}}
  8231. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8232. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8233. \label{fig:Lif-anf-syntax}
  8234. \end{figure}
  8235. \begin{exercise}\normalfont\normalsize
  8236. %
  8237. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8238. and \code{rco\_exp} functions.
  8239. %
  8240. Create three new \LangIf{} programs that exercise the interesting
  8241. code in this pass.
  8242. %
  8243. {\if\edition\racketEd
  8244. In the \code{run-tests.rkt} script, add the following entry to the
  8245. list of \code{passes} and then run the script to test your compiler.
  8246. \begin{lstlisting}
  8247. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8248. \end{lstlisting}
  8249. \fi}
  8250. \end{exercise}
  8251. \section{Explicate Control}
  8252. \label{sec:explicate-control-Lif}
  8253. \racket{Recall that the purpose of \code{explicate\_control} is to
  8254. make the order of evaluation explicit in the syntax of the program.
  8255. With the addition of \key{if}, this becomes more interesting.}
  8256. %
  8257. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8258. %
  8259. The main challenge to overcome is that the condition of an \key{if}
  8260. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8261. condition must be a comparison.
  8262. As a motivating example, consider the following program that has an
  8263. \key{if} expression nested in the condition of another \key{if}:%
  8264. \python{\footnote{Programmers rarely write nested \code{if}
  8265. expressions, but they do write nested expressions involving
  8266. logical \code{and}, which, as we have seen, translates to
  8267. \code{if}.}}
  8268. % cond_test_41.rkt, if_lt_eq.py
  8269. \begin{center}
  8270. \begin{minipage}{0.96\textwidth}
  8271. {\if\edition\racketEd
  8272. \begin{lstlisting}
  8273. (let ([x (read)])
  8274. (let ([y (read)])
  8275. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8276. (+ y 2)
  8277. (+ y 10))))
  8278. \end{lstlisting}
  8279. \fi}
  8280. {\if\edition\pythonEd\pythonColor
  8281. \begin{lstlisting}
  8282. x = input_int()
  8283. y = input_int()
  8284. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8285. \end{lstlisting}
  8286. \fi}
  8287. \end{minipage}
  8288. \end{center}
  8289. %
  8290. The naive way to compile \key{if} and the comparison operations would
  8291. be to handle each of them in isolation, regardless of their context.
  8292. Each comparison would be translated into a \key{cmpq} instruction
  8293. followed by several instructions to move the result from the EFLAGS
  8294. register into a general purpose register or stack location. Each
  8295. \key{if} would be translated into a \key{cmpq} instruction followed by
  8296. a conditional jump. The generated code for the inner \key{if} in this
  8297. example would be as follows:
  8298. \begin{center}
  8299. \begin{minipage}{0.96\textwidth}
  8300. \begin{lstlisting}
  8301. cmpq $1, x
  8302. setl %al
  8303. movzbq %al, tmp
  8304. cmpq $1, tmp
  8305. je then_branch_1
  8306. jmp else_branch_1
  8307. \end{lstlisting}
  8308. \end{minipage}
  8309. \end{center}
  8310. Notice that the three instructions starting with \code{setl} are
  8311. redundant; the conditional jump could come immediately after the first
  8312. \code{cmpq}.
  8313. Our goal is to compile \key{if} expressions so that the relevant
  8314. comparison instruction appears directly before the conditional jump.
  8315. For example, we want to generate the following code for the inner
  8316. \code{if}:
  8317. \begin{center}
  8318. \begin{minipage}{0.96\textwidth}
  8319. \begin{lstlisting}
  8320. cmpq $1, x
  8321. jl then_branch_1
  8322. jmp else_branch_1
  8323. \end{lstlisting}
  8324. \end{minipage}
  8325. \end{center}
  8326. One way to achieve this goal is to reorganize the code at the level of
  8327. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8328. the following code:
  8329. \begin{center}
  8330. \begin{minipage}{0.96\textwidth}
  8331. {\if\edition\racketEd
  8332. \begin{lstlisting}
  8333. (let ([x (read)])
  8334. (let ([y (read)])
  8335. (if (< x 1)
  8336. (if (eq? x 0)
  8337. (+ y 2)
  8338. (+ y 10))
  8339. (if (eq? x 2)
  8340. (+ y 2)
  8341. (+ y 10)))))
  8342. \end{lstlisting}
  8343. \fi}
  8344. {\if\edition\pythonEd\pythonColor
  8345. \begin{lstlisting}
  8346. x = input_int()
  8347. y = input_int()
  8348. print(((y + 2) if x == 0 else (y + 10)) \
  8349. if (x < 1) \
  8350. else ((y + 2) if (x == 2) else (y + 10)))
  8351. \end{lstlisting}
  8352. \fi}
  8353. \end{minipage}
  8354. \end{center}
  8355. Unfortunately, this approach duplicates the two branches from the
  8356. outer \code{if}, and a compiler must never duplicate code! After all,
  8357. the two branches could be very large expressions.
  8358. How can we apply this transformation without duplicating code? In
  8359. other words, how can two different parts of a program refer to one
  8360. piece of code?
  8361. %
  8362. The answer is that we must move away from abstract syntax \emph{trees}
  8363. and instead use \emph{graphs}.
  8364. %
  8365. At the level of x86 assembly, this is straightforward because we can
  8366. label the code for each branch and insert jumps in all the places that
  8367. need to execute the branch. In this way, jump instructions are edges
  8368. in the graph and the basic blocks are the nodes.
  8369. %
  8370. Likewise, our language \LangCIf{} provides the ability to label a
  8371. sequence of statements and to jump to a label via \code{goto}.
  8372. As a preview of what \code{explicate\_control} will do,
  8373. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8374. \code{explicate\_control} on this example. Note how the condition of
  8375. every \code{if} is a comparison operation and that we have not
  8376. duplicated any code but instead have used labels and \code{goto} to
  8377. enable sharing of code.
  8378. \begin{figure}[tbp]
  8379. \begin{tcolorbox}[colback=white]
  8380. {\if\edition\racketEd
  8381. \begin{tabular}{lll}
  8382. \begin{minipage}{0.4\textwidth}
  8383. % cond_test_41.rkt
  8384. \begin{lstlisting}
  8385. (let ([x (read)])
  8386. (let ([y (read)])
  8387. (if (if (< x 1)
  8388. (eq? x 0)
  8389. (eq? x 2))
  8390. (+ y 2)
  8391. (+ y 10))))
  8392. \end{lstlisting}
  8393. \end{minipage}
  8394. &
  8395. $\Rightarrow$
  8396. &
  8397. \begin{minipage}{0.55\textwidth}
  8398. \begin{lstlisting}
  8399. start:
  8400. x = (read);
  8401. y = (read);
  8402. if (< x 1)
  8403. goto block_4;
  8404. else
  8405. goto block_5;
  8406. block_4:
  8407. if (eq? x 0)
  8408. goto block_2;
  8409. else
  8410. goto block_3;
  8411. block_5:
  8412. if (eq? x 2)
  8413. goto block_2;
  8414. else
  8415. goto block_3;
  8416. block_2:
  8417. return (+ y 2);
  8418. block_3:
  8419. return (+ y 10);
  8420. \end{lstlisting}
  8421. \end{minipage}
  8422. \end{tabular}
  8423. \fi}
  8424. {\if\edition\pythonEd\pythonColor
  8425. \begin{tabular}{lll}
  8426. \begin{minipage}{0.4\textwidth}
  8427. % tests/if/if_lt_eq.py
  8428. \begin{lstlisting}
  8429. x = input_int()
  8430. y = input_int()
  8431. print(y + 2 \
  8432. if (x == 0 \
  8433. if x < 1 \
  8434. else x == 2) \
  8435. else y + 10)
  8436. \end{lstlisting}
  8437. \end{minipage}
  8438. &
  8439. $\Rightarrow\qquad$
  8440. &
  8441. \begin{minipage}{0.55\textwidth}
  8442. \begin{lstlisting}
  8443. start:
  8444. x = input_int()
  8445. y = input_int()
  8446. if x < 1:
  8447. goto block_6
  8448. else:
  8449. goto block_7
  8450. block_6:
  8451. if x == 0:
  8452. goto block_4
  8453. else:
  8454. goto block_5
  8455. block_7:
  8456. if x == 2:
  8457. goto block_4
  8458. else:
  8459. goto block_5
  8460. block_4:
  8461. tmp.82 = (y + 2)
  8462. goto block_3
  8463. block_5:
  8464. tmp.82 = (y + 10)
  8465. goto block_3
  8466. block_3:
  8467. print(tmp.82)
  8468. return 0
  8469. \end{lstlisting}
  8470. \end{minipage}
  8471. \end{tabular}
  8472. \fi}
  8473. \end{tcolorbox}
  8474. \caption{Translation from \LangIf{} to \LangCIf{}
  8475. via the \code{explicate\_control}.}
  8476. \label{fig:explicate-control-s1-38}
  8477. \end{figure}
  8478. {\if\edition\racketEd
  8479. %
  8480. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8481. \code{explicate\_control} for \LangVar{} using two recursive
  8482. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8483. former function translates expressions in tail position, whereas the
  8484. latter function translates expressions on the right-hand side of a
  8485. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8486. have a new kind of position to deal with: the predicate position of
  8487. the \key{if}. We need another function, \code{explicate\_pred}, that
  8488. decides how to compile an \key{if} by analyzing its condition. So,
  8489. \code{explicate\_pred} takes an \LangIf{} expression and two
  8490. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8491. and outputs a tail. In the following paragraphs we discuss specific
  8492. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8493. \code{explicate\_pred} functions.
  8494. %
  8495. \fi}
  8496. %
  8497. {\if\edition\pythonEd\pythonColor
  8498. %
  8499. We recommend implementing \code{explicate\_control} using the
  8500. following four auxiliary functions.
  8501. \begin{description}
  8502. \item[\code{explicate\_effect}] generates code for expressions as
  8503. statements, so their result is ignored and only their side effects
  8504. matter.
  8505. \item[\code{explicate\_assign}] generates code for expressions
  8506. on the right-hand side of an assignment.
  8507. \item[\code{explicate\_pred}] generates code for an \code{if}
  8508. expression or statement by analyzing the condition expression.
  8509. \item[\code{explicate\_stmt}] generates code for statements.
  8510. \end{description}
  8511. These four functions should build the dictionary of basic blocks. The
  8512. following auxiliary function \code{create\_block} is used to create a
  8513. new basic block from a list of statements. If the list just contains a
  8514. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8515. \code{create\_block} creates a new basic block and returns a
  8516. \code{goto} to its label.
  8517. \begin{center}
  8518. \begin{minipage}{\textwidth}
  8519. \begin{lstlisting}
  8520. def create_block(stmts, basic_blocks):
  8521. match stmts:
  8522. case [Goto(l)]:
  8523. return stmts
  8524. case _:
  8525. label = label_name(generate_name('block'))
  8526. basic_blocks[label] = stmts
  8527. return [Goto(label)]
  8528. \end{lstlisting}
  8529. \end{minipage}
  8530. \end{center}
  8531. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8532. \code{explicate\_control} pass.
  8533. The \code{explicate\_effect} function has three parameters: (1) the
  8534. expression to be compiled; (2) the already-compiled code for this
  8535. expression's \emph{continuation}, that is, the list of statements that
  8536. should execute after this expression; and (3) the dictionary of
  8537. generated basic blocks. The \code{explicate\_effect} function returns
  8538. a list of \LangCIf{} statements and it may add to the dictionary of
  8539. basic blocks.
  8540. %
  8541. Let's consider a few of the cases for the expression to be compiled.
  8542. If the expression to be compiled is a constant, then it can be
  8543. discarded because it has no side effects. If it's a \CREAD{}, then it
  8544. has a side effect and should be preserved. So the expression should be
  8545. translated into a statement using the \code{Expr} AST class. If the
  8546. expression to be compiled is an \code{if} expression, we translate the
  8547. two branches using \code{explicate\_effect} and then translate the
  8548. condition expression using \code{explicate\_pred}, which generates
  8549. code for the entire \code{if}.
  8550. The \code{explicate\_assign} function has four parameters: (1) the
  8551. right-hand side of the assignment, (2) the left-hand side of the
  8552. assignment (the variable), (3) the continuation, and (4) the dictionary
  8553. of basic blocks. The \code{explicate\_assign} function returns a list
  8554. of \LangCIf{} statements, and it may add to the dictionary of basic
  8555. blocks.
  8556. When the right-hand side is an \code{if} expression, there is some
  8557. work to do. In particular, the two branches should be translated using
  8558. \code{explicate\_assign}, and the condition expression should be
  8559. translated using \code{explicate\_pred}. Otherwise we can simply
  8560. generate an assignment statement, with the given left- and right-hand
  8561. sides, concatenated with its continuation.
  8562. \begin{figure}[tbp]
  8563. \begin{tcolorbox}[colback=white]
  8564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8565. def explicate_effect(e, cont, basic_blocks):
  8566. match e:
  8567. case IfExp(test, body, orelse):
  8568. ...
  8569. case Call(func, args):
  8570. ...
  8571. case Begin(body, result):
  8572. ...
  8573. case _:
  8574. ...
  8575. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8576. match rhs:
  8577. case IfExp(test, body, orelse):
  8578. ...
  8579. case Begin(body, result):
  8580. ...
  8581. case _:
  8582. return [Assign([lhs], rhs)] + cont
  8583. def explicate_pred(cnd, thn, els, basic_blocks):
  8584. match cnd:
  8585. case Compare(left, [op], [right]):
  8586. goto_thn = create_block(thn, basic_blocks)
  8587. goto_els = create_block(els, basic_blocks)
  8588. return [If(cnd, goto_thn, goto_els)]
  8589. case Constant(True):
  8590. return thn;
  8591. case Constant(False):
  8592. return els;
  8593. case UnaryOp(Not(), operand):
  8594. ...
  8595. case IfExp(test, body, orelse):
  8596. ...
  8597. case Begin(body, result):
  8598. ...
  8599. case _:
  8600. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8601. create_block(els, basic_blocks),
  8602. create_block(thn, basic_blocks))]
  8603. def explicate_stmt(s, cont, basic_blocks):
  8604. match s:
  8605. case Assign([lhs], rhs):
  8606. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8607. case Expr(value):
  8608. return explicate_effect(value, cont, basic_blocks)
  8609. case If(test, body, orelse):
  8610. ...
  8611. def explicate_control(p):
  8612. match p:
  8613. case Module(body):
  8614. new_body = [Return(Constant(0))]
  8615. basic_blocks = {}
  8616. for s in reversed(body):
  8617. new_body = explicate_stmt(s, new_body, basic_blocks)
  8618. basic_blocks[label_name('start')] = new_body
  8619. return CProgram(basic_blocks)
  8620. \end{lstlisting}
  8621. \end{tcolorbox}
  8622. \caption{Skeleton for the \code{explicate\_control} pass.}
  8623. \label{fig:explicate-control-Lif}
  8624. \end{figure}
  8625. \fi}
  8626. {\if\edition\racketEd
  8627. \subsection{Explicate Tail and Assign}
  8628. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8629. additional cases for Boolean constants and \key{if}. The cases for
  8630. \code{if} should recursively compile the two branches using either
  8631. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8632. cases should then invoke \code{explicate\_pred} on the condition
  8633. expression, passing in the generated code for the two branches. For
  8634. example, consider the following program with an \code{if} in tail
  8635. position.
  8636. % cond_test_6.rkt
  8637. \begin{lstlisting}
  8638. (let ([x (read)])
  8639. (if (eq? x 0) 42 777))
  8640. \end{lstlisting}
  8641. The two branches are recursively compiled to return statements. We
  8642. then delegate to \code{explicate\_pred}, passing the condition
  8643. \code{(eq? x 0)} and the two return statements. We return to this
  8644. example shortly when we discuss \code{explicate\_pred}.
  8645. Next let us consider a program with an \code{if} on the right-hand
  8646. side of a \code{let}.
  8647. \begin{lstlisting}
  8648. (let ([y (read)])
  8649. (let ([x (if (eq? y 0) 40 777)])
  8650. (+ x 2)))
  8651. \end{lstlisting}
  8652. Note that the body of the inner \code{let} will have already been
  8653. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8654. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8655. to recursively process both branches of the \code{if}, and we do not
  8656. want to duplicate code, so we generate the following block using an
  8657. auxiliary function named \code{create\_block}, discussed in the next
  8658. section.
  8659. \begin{lstlisting}
  8660. block_6:
  8661. return (+ x 2)
  8662. \end{lstlisting}
  8663. We then use \code{goto block\_6;} as the \code{cont} argument for
  8664. compiling the branches. So the two branches compile to
  8665. \begin{center}
  8666. \begin{minipage}{0.2\textwidth}
  8667. \begin{lstlisting}
  8668. x = 40;
  8669. goto block_6;
  8670. \end{lstlisting}
  8671. \end{minipage}
  8672. \hspace{0.5in} and \hspace{0.5in}
  8673. \begin{minipage}{0.2\textwidth}
  8674. \begin{lstlisting}
  8675. x = 777;
  8676. goto block_6;
  8677. \end{lstlisting}
  8678. \end{minipage}
  8679. \end{center}
  8680. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8681. \code{(eq? y 0)} and the previously presented code for the branches.
  8682. \subsection{Create Block}
  8683. We recommend implementing the \code{create\_block} auxiliary function
  8684. as follows, using a global variable \code{basic-blocks} to store a
  8685. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8686. that \code{create\_block} generates a new label and then associates
  8687. the given \code{tail} with the new label in the \code{basic-blocks}
  8688. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8689. new label. However, if the given \code{tail} is already a \code{Goto},
  8690. then there is no need to generate a new label and entry in
  8691. \code{basic-blocks}; we can simply return that \code{Goto}.
  8692. %
  8693. \begin{lstlisting}
  8694. (define (create_block tail)
  8695. (match tail
  8696. [(Goto label) (Goto label)]
  8697. [else
  8698. (let ([label (gensym 'block)])
  8699. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8700. (Goto label))]))
  8701. \end{lstlisting}
  8702. \fi}
  8703. {\if\edition\racketEd
  8704. \subsection{Explicate Predicate}
  8705. The skeleton for the \code{explicate\_pred} function is given in
  8706. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8707. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8708. the code generated by explicate for the \emph{then} branch; and (3)
  8709. \code{els}, the code generated by explicate for the \emph{else}
  8710. branch. The \code{explicate\_pred} function should match on
  8711. \code{cnd} with a case for every kind of expression that can have type
  8712. \BOOLTY{}.
  8713. \begin{figure}[tbp]
  8714. \begin{tcolorbox}[colback=white]
  8715. \begin{lstlisting}
  8716. (define (explicate_pred cnd thn els)
  8717. (match cnd
  8718. [(Var x) ___]
  8719. [(Let x rhs body) ___]
  8720. [(Prim 'not (list e)) ___]
  8721. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8722. (IfStmt (Prim op es) (create_block thn)
  8723. (create_block els))]
  8724. [(Bool b) (if b thn els)]
  8725. [(If cnd^ thn^ els^) ___]
  8726. [else (error "explicate_pred unhandled case" cnd)]))
  8727. \end{lstlisting}
  8728. \end{tcolorbox}
  8729. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8730. \label{fig:explicate-pred}
  8731. \end{figure}
  8732. \fi}
  8733. %
  8734. {\if\edition\pythonEd\pythonColor
  8735. The \code{explicate\_pred} function has four parameters: (1) the
  8736. condition expression, (2) the generated statements for the \emph{then}
  8737. branch, (3) the generated statements for the \emph{else} branch, and
  8738. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8739. function returns a list of statements, and it adds to the dictionary
  8740. of basic blocks.
  8741. \fi}
  8742. Consider the case for comparison operators. We translate the
  8743. comparison to an \code{if} statement whose branches are \code{goto}
  8744. statements created by applying \code{create\_block} to the \code{thn}
  8745. and \code{els} parameters. Let us illustrate this translation by
  8746. returning to the program with an \code{if} expression in tail
  8747. position, shown next. We invoke \code{explicate\_pred} on its
  8748. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8749. %
  8750. {\if\edition\racketEd
  8751. \begin{lstlisting}
  8752. (let ([x (read)])
  8753. (if (eq? x 0) 42 777))
  8754. \end{lstlisting}
  8755. \fi}
  8756. %
  8757. {\if\edition\pythonEd\pythonColor
  8758. \begin{lstlisting}
  8759. x = input_int()
  8760. 42 if x == 0 else 777
  8761. \end{lstlisting}
  8762. \fi}
  8763. %
  8764. \noindent The two branches \code{42} and \code{777} were already
  8765. compiled to \code{return} statements, from which we now create the
  8766. following blocks:
  8767. %
  8768. \begin{center}
  8769. \begin{minipage}{\textwidth}
  8770. \begin{lstlisting}
  8771. block_1:
  8772. return 42;
  8773. block_2:
  8774. return 777;
  8775. \end{lstlisting}
  8776. \end{minipage}
  8777. \end{center}
  8778. %
  8779. After that, \code{explicate\_pred} compiles the comparison
  8780. \racket{\code{(eq? x 0)}}
  8781. \python{\code{x == 0}}
  8782. to the following \code{if} statement:
  8783. %
  8784. {\if\edition\racketEd
  8785. \begin{center}
  8786. \begin{minipage}{\textwidth}
  8787. \begin{lstlisting}
  8788. if (eq? x 0)
  8789. goto block_1;
  8790. else
  8791. goto block_2;
  8792. \end{lstlisting}
  8793. \end{minipage}
  8794. \end{center}
  8795. \fi}
  8796. {\if\edition\pythonEd\pythonColor
  8797. \begin{center}
  8798. \begin{minipage}{\textwidth}
  8799. \begin{lstlisting}
  8800. if x == 0:
  8801. goto block_1;
  8802. else
  8803. goto block_2;
  8804. \end{lstlisting}
  8805. \end{minipage}
  8806. \end{center}
  8807. \fi}
  8808. Next consider the case for Boolean constants. We perform a kind of
  8809. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8810. either the \code{thn} or \code{els} parameter, depending on whether the
  8811. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8812. following program:
  8813. {\if\edition\racketEd
  8814. \begin{lstlisting}
  8815. (if #t 42 777)
  8816. \end{lstlisting}
  8817. \fi}
  8818. {\if\edition\pythonEd\pythonColor
  8819. \begin{lstlisting}
  8820. 42 if True else 777
  8821. \end{lstlisting}
  8822. \fi}
  8823. %
  8824. \noindent Again, the two branches \code{42} and \code{777} were
  8825. compiled to \code{return} statements, so \code{explicate\_pred}
  8826. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8827. code for the \emph{then} branch.
  8828. \begin{lstlisting}
  8829. return 42;
  8830. \end{lstlisting}
  8831. This case demonstrates that we sometimes discard the \code{thn} or
  8832. \code{els} blocks that are input to \code{explicate\_pred}.
  8833. The case for \key{if} expressions in \code{explicate\_pred} is
  8834. particularly illuminating because it deals with the challenges
  8835. discussed previously regarding nested \key{if} expressions
  8836. (figure~\ref{fig:explicate-control-s1-38}). The
  8837. \racket{\lstinline{thn^}}\python{\code{body}} and
  8838. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8839. \key{if} inherit their context from the current one, that is,
  8840. predicate context. So, you should recursively apply
  8841. \code{explicate\_pred} to the
  8842. \racket{\lstinline{thn^}}\python{\code{body}} and
  8843. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8844. those recursive calls, pass \code{thn} and \code{els} as the extra
  8845. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8846. inside each recursive call. As discussed previously, to avoid
  8847. duplicating code, we need to add them to the dictionary of basic
  8848. blocks so that we can instead refer to them by name and execute them
  8849. with a \key{goto}.
  8850. {\if\edition\pythonEd\pythonColor
  8851. %
  8852. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8853. three parameters: (1) the statement to be compiled, (2) the code for its
  8854. continuation, and (3) the dictionary of basic blocks. The
  8855. \code{explicate\_stmt} returns a list of statements, and it may add to
  8856. the dictionary of basic blocks. The cases for assignment and an
  8857. expression-statement are given in full in the skeleton code: they
  8858. simply dispatch to \code{explicate\_assign} and
  8859. \code{explicate\_effect}, respectively. The case for \code{if}
  8860. statements is not given; it is similar to the case for \code{if}
  8861. expressions.
  8862. The \code{explicate\_control} function itself is given in
  8863. figure~\ref{fig:explicate-control-Lif}. It applies
  8864. \code{explicate\_stmt} to each statement in the program, from back to
  8865. front. Thus, the result so far, stored in \code{new\_body}, can be
  8866. used as the continuation parameter in the next call to
  8867. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8868. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8869. the dictionary of basic blocks, labeling it the ``start'' block.
  8870. %
  8871. \fi}
  8872. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8873. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8874. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8875. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8876. %% results from the two recursive calls. We complete the case for
  8877. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8878. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8879. %% the result $B_5$.
  8880. %% \[
  8881. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8882. %% \quad\Rightarrow\quad
  8883. %% B_5
  8884. %% \]
  8885. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8886. %% inherit the current context, so they are in tail position. Thus, the
  8887. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8888. %% \code{explicate\_tail}.
  8889. %% %
  8890. %% We need to pass $B_0$ as the accumulator argument for both of these
  8891. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8892. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8893. %% to the control-flow graph and obtain a promised goto $G_0$.
  8894. %% %
  8895. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8896. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8897. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8898. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8899. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8900. %% \[
  8901. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8902. %% \]
  8903. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8904. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8905. %% should not be confused with the labels for the blocks that appear in
  8906. %% the generated code. We initially construct unlabeled blocks; we only
  8907. %% attach labels to blocks when we add them to the control-flow graph, as
  8908. %% we see in the next case.
  8909. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8910. %% function. The context of the \key{if} is an assignment to some
  8911. %% variable $x$ and then the control continues to some promised block
  8912. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8913. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8914. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8915. %% branches of the \key{if} inherit the current context, so they are in
  8916. %% assignment positions. Let $B_2$ be the result of applying
  8917. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8918. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8919. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8920. %% the result of applying \code{explicate\_pred} to the predicate
  8921. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8922. %% translates to the promise $B_4$.
  8923. %% \[
  8924. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8925. %% \]
  8926. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8927. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8928. \code{remove\_complex\_operands} pass and then the
  8929. \code{explicate\_control} pass on the example program. We walk through
  8930. the output program.
  8931. %
  8932. Following the order of evaluation in the output of
  8933. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8934. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8935. in the predicate of the inner \key{if}. In the output of
  8936. \code{explicate\_control}, in the
  8937. block labeled \code{start}, two assignment statements are followed by an
  8938. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8939. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8940. The blocks associated with those labels contain the
  8941. translations of the code
  8942. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8943. and
  8944. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8945. respectively. In particular, we start
  8946. \racket{\code{block\_4}}\python{\code{block\_6}}
  8947. with the comparison
  8948. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8949. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8950. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8951. which correspond to the two branches of the outer \key{if}, that is,
  8952. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8953. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8954. %
  8955. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8956. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8957. %
  8958. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8959. {\if\edition\racketEd
  8960. \subsection{Interactions between Explicate and Shrink}
  8961. The way in which the \code{shrink} pass transforms logical operations
  8962. such as \code{and} and \code{or} can impact the quality of code
  8963. generated by \code{explicate\_control}. For example, consider the
  8964. following program:
  8965. % cond_test_21.rkt, and_eq_input.py
  8966. \begin{lstlisting}
  8967. (if (and (eq? (read) 0) (eq? (read) 1))
  8968. 0
  8969. 42)
  8970. \end{lstlisting}
  8971. The \code{and} operation should transform into something that the
  8972. \code{explicate\_pred} function can analyze and descend through to
  8973. reach the underlying \code{eq?} conditions. Ideally, for this program
  8974. your \code{explicate\_control} pass should generate code similar to
  8975. the following:
  8976. \begin{center}
  8977. \begin{minipage}{\textwidth}
  8978. \begin{lstlisting}
  8979. start:
  8980. tmp1 = (read);
  8981. if (eq? tmp1 0) goto block40;
  8982. else goto block39;
  8983. block40:
  8984. tmp2 = (read);
  8985. if (eq? tmp2 1) goto block38;
  8986. else goto block39;
  8987. block38:
  8988. return 0;
  8989. block39:
  8990. return 42;
  8991. \end{lstlisting}
  8992. \end{minipage}
  8993. \end{center}
  8994. \fi}
  8995. \begin{exercise}\normalfont\normalsize
  8996. \racket{
  8997. Implement the pass \code{explicate\_control} by adding the cases for
  8998. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8999. \code{explicate\_assign} functions. Implement the auxiliary function
  9000. \code{explicate\_pred} for predicate contexts.}
  9001. \python{Implement \code{explicate\_control} pass with its
  9002. four auxiliary functions.}
  9003. %
  9004. Create test cases that exercise all the new cases in the code for
  9005. this pass.
  9006. %
  9007. {\if\edition\racketEd
  9008. Add the following entry to the list of \code{passes} in
  9009. \code{run-tests.rkt}:
  9010. \begin{lstlisting}
  9011. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9012. \end{lstlisting}
  9013. and then run \code{run-tests.rkt} to test your compiler.
  9014. \fi}
  9015. \end{exercise}
  9016. \section{Select Instructions}
  9017. \label{sec:select-Lif}
  9018. \index{subject}{select instructions}
  9019. The \code{select\_instructions} pass translates \LangCIf{} to
  9020. \LangXIfVar{}.
  9021. %
  9022. \racket{Recall that we implement this pass using three auxiliary
  9023. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9024. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9025. %
  9026. \racket{For $\Atm$, we have new cases for the Booleans.}
  9027. %
  9028. \python{We begin with the Boolean constants.}
  9029. As previously discussed, we encode them as integers.
  9030. \[
  9031. \TRUE{} \quad\Rightarrow\quad \key{1}
  9032. \qquad\qquad
  9033. \FALSE{} \quad\Rightarrow\quad \key{0}
  9034. \]
  9035. For translating statements, we discuss some of the cases. The
  9036. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9037. discussed at the beginning of this section. Given an assignment, if
  9038. the left-hand-side variable is the same as the argument of \code{not},
  9039. then just the \code{xorq} instruction suffices.
  9040. \[
  9041. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9042. \quad\Rightarrow\quad
  9043. \key{xorq}~\key{\$}1\key{,}~\Var
  9044. \]
  9045. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9046. semantics of x86. In the following translation, let $\Arg$ be the
  9047. result of translating $\Atm$ to x86.
  9048. \[
  9049. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9050. \quad\Rightarrow\quad
  9051. \begin{array}{l}
  9052. \key{movq}~\Arg\key{,}~\Var\\
  9053. \key{xorq}~\key{\$}1\key{,}~\Var
  9054. \end{array}
  9055. \]
  9056. Next consider the cases for equality comparisons. Translating this
  9057. operation to x86 is slightly involved due to the unusual nature of the
  9058. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9059. We recommend translating an assignment with an equality on the
  9060. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9061. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9062. \begin{tabular}{lll}
  9063. \begin{minipage}{0.4\textwidth}
  9064. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9065. \end{minipage}
  9066. &
  9067. $\Rightarrow$
  9068. &
  9069. \begin{minipage}{0.4\textwidth}
  9070. \begin{lstlisting}
  9071. cmpq |$\Arg_2$|, |$\Arg_1$|
  9072. sete %al
  9073. movzbq %al, |$\Var$|
  9074. \end{lstlisting}
  9075. \end{minipage}
  9076. \end{tabular} \\
  9077. The translations for the other comparison operators are similar to
  9078. this but use different condition codes for the \code{set} instruction.
  9079. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9080. \key{goto} and \key{if} statements. Both are straightforward to
  9081. translate to x86.}
  9082. %
  9083. A \key{goto} statement becomes a jump instruction.
  9084. \[
  9085. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9086. \]
  9087. %
  9088. An \key{if} statement becomes a compare instruction followed by a
  9089. conditional jump (for the \emph{then} branch), and the fall-through is to
  9090. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9091. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9092. \begin{tabular}{lll}
  9093. \begin{minipage}{0.4\textwidth}
  9094. \begin{lstlisting}
  9095. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9096. goto |$\ell_1$||$\racket{\key{;}}$|
  9097. else|$\python{\key{:}}$|
  9098. goto |$\ell_2$||$\racket{\key{;}}$|
  9099. \end{lstlisting}
  9100. \end{minipage}
  9101. &
  9102. $\Rightarrow$
  9103. &
  9104. \begin{minipage}{0.4\textwidth}
  9105. \begin{lstlisting}
  9106. cmpq |$\Arg_2$|, |$\Arg_1$|
  9107. je |$\ell_1$|
  9108. jmp |$\ell_2$|
  9109. \end{lstlisting}
  9110. \end{minipage}
  9111. \end{tabular} \\
  9112. Again, the translations for the other comparison operators are similar to this
  9113. but use different condition codes for the conditional jump instruction.
  9114. \python{Regarding the \key{return} statement, we recommend treating it
  9115. as an assignment to the \key{rax} register followed by a jump to the
  9116. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9117. \begin{exercise}\normalfont\normalsize
  9118. Expand your \code{select\_instructions} pass to handle the new
  9119. features of the \LangCIf{} language.
  9120. %
  9121. {\if\edition\racketEd
  9122. Add the following entry to the list of \code{passes} in
  9123. \code{run-tests.rkt}
  9124. \begin{lstlisting}
  9125. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9126. \end{lstlisting}
  9127. \fi}
  9128. %
  9129. Run the script to test your compiler on all the test programs.
  9130. \end{exercise}
  9131. \section{Register Allocation}
  9132. \label{sec:register-allocation-Lif}
  9133. \index{subject}{register allocation}
  9134. The changes required for compiling \LangIf{} affect liveness analysis,
  9135. building the interference graph, and assigning homes, but the graph
  9136. coloring algorithm itself does not change.
  9137. \subsection{Liveness Analysis}
  9138. \label{sec:liveness-analysis-Lif}
  9139. \index{subject}{liveness analysis}
  9140. Recall that for \LangVar{} we implemented liveness analysis for a
  9141. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9142. the addition of \key{if} expressions to \LangIf{},
  9143. \code{explicate\_control} produces many basic blocks.
  9144. %% We recommend that you create a new auxiliary function named
  9145. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9146. %% control-flow graph.
  9147. The first question is, in what order should we process the basic blocks?
  9148. Recall that to perform liveness analysis on a basic block we need to
  9149. know the live-after set for the last instruction in the block. If a
  9150. basic block has no successors (i.e., contains no jumps to other
  9151. blocks), then it has an empty live-after set and we can immediately
  9152. apply liveness analysis to it. If a basic block has some successors,
  9153. then we need to complete liveness analysis on those blocks
  9154. first. These ordering constraints are the reverse of a
  9155. \emph{topological order}\index{subject}{topological order} on a graph
  9156. representation of the program. In particular, the \emph{control flow
  9157. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9158. of a program has a node for each basic block and an edge for each jump
  9159. from one block to another. It is straightforward to generate a CFG
  9160. from the dictionary of basic blocks. One then transposes the CFG and
  9161. applies the topological sort algorithm.
  9162. %
  9163. %
  9164. \racket{We recommend using the \code{tsort} and \code{transpose}
  9165. functions of the Racket \code{graph} package to accomplish this.}
  9166. %
  9167. \python{We provide implementations of \code{topological\_sort} and
  9168. \code{transpose} in the file \code{graph.py} of the support code.}
  9169. %
  9170. As an aside, a topological ordering is only guaranteed to exist if the
  9171. graph does not contain any cycles. This is the case for the
  9172. control-flow graphs that we generate from \LangIf{} programs.
  9173. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9174. and learn how to handle cycles in the control-flow graph.
  9175. \racket{You need to construct a directed graph to represent the
  9176. control-flow graph. Do not use the \code{directed-graph} of the
  9177. \code{graph} package because that allows at most one edge
  9178. between each pair of vertices, whereas a control-flow graph may have
  9179. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9180. file in the support code implements a graph representation that
  9181. allows multiple edges between a pair of vertices.}
  9182. {\if\edition\racketEd
  9183. The next question is how to analyze jump instructions. Recall that in
  9184. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9185. \code{label->live} that maps each label to the set of live locations
  9186. at the beginning of its block. We use \code{label->live} to determine
  9187. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9188. that we have many basic blocks, \code{label->live} needs to be updated
  9189. as we process the blocks. In particular, after performing liveness
  9190. analysis on a block, we take the live-before set of its first
  9191. instruction and associate that with the block's label in the
  9192. \code{label->live} alist.
  9193. \fi}
  9194. %
  9195. {\if\edition\pythonEd\pythonColor
  9196. %
  9197. The next question is how to analyze jump instructions. The locations
  9198. that are live before a \code{jmp} should be the locations in
  9199. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9200. maintaining a dictionary named \code{live\_before\_block} that maps each
  9201. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9202. block. After performing liveness analysis on each block, we take the
  9203. live-before set of its first instruction and associate that with the
  9204. block's label in the \code{live\_before\_block} dictionary.
  9205. %
  9206. \fi}
  9207. In \LangXIfVar{} we also have the conditional jump
  9208. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9209. this instruction is particularly interesting because during
  9210. compilation, we do not know which way a conditional jump will go. Thus
  9211. we do not know whether to use the live-before set for the block
  9212. associated with the $\itm{label}$ or the live-before set for the
  9213. following instruction. So we use both, by taking the union of the
  9214. live-before sets from the following instruction and from the mapping
  9215. for $\itm{label}$ in
  9216. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9217. The auxiliary functions for computing the variables in an
  9218. instruction's argument and for computing the variables read-from ($R$)
  9219. or written-to ($W$) by an instruction need to be updated to handle the
  9220. new kinds of arguments and instructions in \LangXIfVar{}.
  9221. \begin{exercise}\normalfont\normalsize
  9222. {\if\edition\racketEd
  9223. %
  9224. Update the \code{uncover\_live} pass to apply liveness analysis to
  9225. every basic block in the program.
  9226. %
  9227. Add the following entry to the list of \code{passes} in the
  9228. \code{run-tests.rkt} script:
  9229. \begin{lstlisting}
  9230. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9231. \end{lstlisting}
  9232. \fi}
  9233. {\if\edition\pythonEd\pythonColor
  9234. %
  9235. Update the \code{uncover\_live} function to perform liveness analysis,
  9236. in reverse topological order, on all the basic blocks in the
  9237. program.
  9238. %
  9239. \fi}
  9240. % Check that the live-after sets that you generate for
  9241. % example X matches the following... -Jeremy
  9242. \end{exercise}
  9243. \subsection{Build the Interference Graph}
  9244. \label{sec:build-interference-Lif}
  9245. Many of the new instructions in \LangXIfVar{} can be handled in the
  9246. same way as the instructions in \LangXVar{}.
  9247. % Thus, if your code was
  9248. % already quite general, it will not need to be changed to handle the
  9249. % new instructions. If your code is not general enough, we recommend that
  9250. % you change your code to be more general. For example, you can factor
  9251. % out the computing of the the read and write sets for each kind of
  9252. % instruction into auxiliary functions.
  9253. %
  9254. Some instructions, such as the \key{movzbq} instruction, require special care,
  9255. similar to the \key{movq} instruction. Refer to rule number 1 in
  9256. section~\ref{sec:build-interference}.
  9257. \begin{exercise}\normalfont\normalsize
  9258. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9259. {\if\edition\racketEd
  9260. Add the following entries to the list of \code{passes} in the
  9261. \code{run-tests.rkt} script:
  9262. \begin{lstlisting}
  9263. (list "build_interference" build_interference interp-pseudo-x86-1)
  9264. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9265. \end{lstlisting}
  9266. \fi}
  9267. % Check that the interference graph that you generate for
  9268. % example X matches the following graph G... -Jeremy
  9269. \end{exercise}
  9270. \section{Patch Instructions}
  9271. The new instructions \key{cmpq} and \key{movzbq} have some special
  9272. restrictions that need to be handled in the \code{patch\_instructions}
  9273. pass.
  9274. %
  9275. The second argument of the \key{cmpq} instruction must not be an
  9276. immediate value (such as an integer). So, if you are comparing two
  9277. immediates, we recommend inserting a \key{movq} instruction to put the
  9278. second argument in \key{rax}. On the other hand, if you implemented
  9279. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9280. update it for \LangIf{} and then this situation would not arise.
  9281. %
  9282. As usual, \key{cmpq} may have at most one memory reference.
  9283. %
  9284. The second argument of the \key{movzbq} must be a register.
  9285. \begin{exercise}\normalfont\normalsize
  9286. %
  9287. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9288. %
  9289. {\if\edition\racketEd
  9290. Add the following entry to the list of \code{passes} in
  9291. \code{run-tests.rkt}, and then run this script to test your compiler.
  9292. \begin{lstlisting}
  9293. (list "patch_instructions" patch_instructions interp-x86-1)
  9294. \end{lstlisting}
  9295. \fi}
  9296. \end{exercise}
  9297. {\if\edition\pythonEd\pythonColor
  9298. \section{Generate Prelude and Conclusion}
  9299. \label{sec:prelude-conclusion-cond}
  9300. The generation of the \code{main} function with its prelude and
  9301. conclusion must change to accommodate how the program now consists of
  9302. one or more basic blocks. After the prelude in \code{main}, jump to
  9303. the \code{start} block. Place the conclusion in a basic block labeled
  9304. with \code{conclusion}.
  9305. \fi}
  9306. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9307. \LangIf{} translated to x86, showing the results of
  9308. \code{explicate\_control}, \code{select\_instructions}, and the final
  9309. x86 assembly.
  9310. \begin{figure}[tbp]
  9311. \begin{tcolorbox}[colback=white]
  9312. {\if\edition\racketEd
  9313. \begin{tabular}{lll}
  9314. \begin{minipage}{0.4\textwidth}
  9315. % cond_test_20.rkt, eq_input.py
  9316. \begin{lstlisting}
  9317. (if (eq? (read) 1) 42 0)
  9318. \end{lstlisting}
  9319. $\Downarrow$
  9320. \begin{lstlisting}
  9321. start:
  9322. tmp7951 = (read);
  9323. if (eq? tmp7951 1)
  9324. goto block7952;
  9325. else
  9326. goto block7953;
  9327. block7952:
  9328. return 42;
  9329. block7953:
  9330. return 0;
  9331. \end{lstlisting}
  9332. $\Downarrow$
  9333. \begin{lstlisting}
  9334. start:
  9335. callq read_int
  9336. movq %rax, tmp7951
  9337. cmpq $1, tmp7951
  9338. je block7952
  9339. jmp block7953
  9340. block7953:
  9341. movq $0, %rax
  9342. jmp conclusion
  9343. block7952:
  9344. movq $42, %rax
  9345. jmp conclusion
  9346. \end{lstlisting}
  9347. \end{minipage}
  9348. &
  9349. $\Rightarrow\qquad$
  9350. \begin{minipage}{0.4\textwidth}
  9351. \begin{lstlisting}
  9352. start:
  9353. callq read_int
  9354. movq %rax, %rcx
  9355. cmpq $1, %rcx
  9356. je block7952
  9357. jmp block7953
  9358. block7953:
  9359. movq $0, %rax
  9360. jmp conclusion
  9361. block7952:
  9362. movq $42, %rax
  9363. jmp conclusion
  9364. .globl main
  9365. main:
  9366. pushq %rbp
  9367. movq %rsp, %rbp
  9368. pushq %r13
  9369. pushq %r12
  9370. pushq %rbx
  9371. pushq %r14
  9372. subq $0, %rsp
  9373. jmp start
  9374. conclusion:
  9375. addq $0, %rsp
  9376. popq %r14
  9377. popq %rbx
  9378. popq %r12
  9379. popq %r13
  9380. popq %rbp
  9381. retq
  9382. \end{lstlisting}
  9383. \end{minipage}
  9384. \end{tabular}
  9385. \fi}
  9386. {\if\edition\pythonEd\pythonColor
  9387. \begin{tabular}{lll}
  9388. \begin{minipage}{0.4\textwidth}
  9389. % cond_test_20.rkt, eq_input.py
  9390. \begin{lstlisting}
  9391. print(42 if input_int() == 1 else 0)
  9392. \end{lstlisting}
  9393. $\Downarrow$
  9394. \begin{lstlisting}
  9395. start:
  9396. tmp_0 = input_int()
  9397. if tmp_0 == 1:
  9398. goto block_3
  9399. else:
  9400. goto block_4
  9401. block_3:
  9402. tmp_1 = 42
  9403. goto block_2
  9404. block_4:
  9405. tmp_1 = 0
  9406. goto block_2
  9407. block_2:
  9408. print(tmp_1)
  9409. return 0
  9410. \end{lstlisting}
  9411. $\Downarrow$
  9412. \begin{lstlisting}
  9413. start:
  9414. callq read_int
  9415. movq %rax, tmp_0
  9416. cmpq 1, tmp_0
  9417. je block_3
  9418. jmp block_4
  9419. block_3:
  9420. movq 42, tmp_1
  9421. jmp block_2
  9422. block_4:
  9423. movq 0, tmp_1
  9424. jmp block_2
  9425. block_2:
  9426. movq tmp_1, %rdi
  9427. callq print_int
  9428. movq 0, %rax
  9429. jmp conclusion
  9430. \end{lstlisting}
  9431. \end{minipage}
  9432. &
  9433. $\Rightarrow\qquad$
  9434. \begin{minipage}{0.4\textwidth}
  9435. \begin{lstlisting}
  9436. .globl main
  9437. main:
  9438. pushq %rbp
  9439. movq %rsp, %rbp
  9440. subq $0, %rsp
  9441. jmp start
  9442. start:
  9443. callq read_int
  9444. movq %rax, %rcx
  9445. cmpq $1, %rcx
  9446. je block_3
  9447. jmp block_4
  9448. block_3:
  9449. movq $42, %rcx
  9450. jmp block_2
  9451. block_4:
  9452. movq $0, %rcx
  9453. jmp block_2
  9454. block_2:
  9455. movq %rcx, %rdi
  9456. callq print_int
  9457. movq $0, %rax
  9458. jmp conclusion
  9459. conclusion:
  9460. addq $0, %rsp
  9461. popq %rbp
  9462. retq
  9463. \end{lstlisting}
  9464. \end{minipage}
  9465. \end{tabular}
  9466. \fi}
  9467. \end{tcolorbox}
  9468. \caption{Example compilation of an \key{if} expression to x86, showing
  9469. the results of \code{explicate\_control},
  9470. \code{select\_instructions}, and the final x86 assembly code. }
  9471. \label{fig:if-example-x86}
  9472. \end{figure}
  9473. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9474. compilation of \LangIf{}.
  9475. \begin{figure}[htbp]
  9476. \begin{tcolorbox}[colback=white]
  9477. {\if\edition\racketEd
  9478. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9479. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9480. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9481. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9482. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9483. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9484. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9485. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9486. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9487. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9488. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9489. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9490. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9491. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9492. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9493. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9494. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9495. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9496. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9497. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9498. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9499. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9500. \end{tikzpicture}
  9501. \fi}
  9502. {\if\edition\pythonEd\pythonColor
  9503. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9504. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9505. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9506. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9507. \node (C-1) at (0,0) {\large \LangCIf{}};
  9508. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9509. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9510. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9511. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9512. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9513. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9514. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9515. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9516. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9517. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9518. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9519. \end{tikzpicture}
  9520. \fi}
  9521. \end{tcolorbox}
  9522. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9523. \label{fig:Lif-passes}
  9524. \end{figure}
  9525. \section{Challenge: Optimize Blocks and Remove Jumps}
  9526. \label{sec:opt-jumps}
  9527. We discuss two challenges that involve optimizing the control-flow of
  9528. the program.
  9529. \subsection{Optimize Blocks}
  9530. The algorithm for \code{explicate\_control} that we discussed in
  9531. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9532. blocks. It creates a block whenever a continuation \emph{might} get
  9533. used more than once (for example, whenever the \code{cont} parameter
  9534. is passed into two or more recursive calls). However, some
  9535. continuation arguments may not be used at all. Consider the case for
  9536. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9537. the \code{els} continuation.
  9538. %
  9539. {\if\edition\racketEd
  9540. The following example program falls into this
  9541. case, and it creates two unused blocks.
  9542. \begin{center}
  9543. \begin{tabular}{lll}
  9544. \begin{minipage}{0.4\textwidth}
  9545. % cond_test_82.rkt
  9546. \begin{lstlisting}
  9547. (let ([y (if #t
  9548. (read)
  9549. (if (eq? (read) 0)
  9550. 777
  9551. (let ([x (read)])
  9552. (+ 1 x))))])
  9553. (+ y 2))
  9554. \end{lstlisting}
  9555. \end{minipage}
  9556. &
  9557. $\Rightarrow$
  9558. &
  9559. \begin{minipage}{0.4\textwidth}
  9560. \begin{lstlisting}
  9561. start:
  9562. y = (read);
  9563. goto block_5;
  9564. block_5:
  9565. return (+ y 2);
  9566. block_6:
  9567. y = 777;
  9568. goto block_5;
  9569. block_7:
  9570. x = (read);
  9571. y = (+ 1 x2);
  9572. goto block_5;
  9573. \end{lstlisting}
  9574. \end{minipage}
  9575. \end{tabular}
  9576. \end{center}
  9577. \fi}
  9578. {\if\edition\pythonEd
  9579. The following example program falls into this
  9580. case, and it creates the unused \code{block\_9}.
  9581. \begin{center}
  9582. \begin{minipage}{0.4\textwidth}
  9583. % if/if_true.py
  9584. \begin{lstlisting}
  9585. if True:
  9586. print(0)
  9587. else:
  9588. x = 1 if False else 2
  9589. print(x)
  9590. \end{lstlisting}
  9591. \end{minipage}
  9592. $\Rightarrow\qquad\qquad$
  9593. \begin{minipage}{0.4\textwidth}
  9594. \begin{lstlisting}
  9595. start:
  9596. print(0)
  9597. goto block_8
  9598. block_9:
  9599. print(x)
  9600. goto block_8
  9601. block_8:
  9602. return 0
  9603. \end{lstlisting}
  9604. \end{minipage}
  9605. \end{center}
  9606. \fi}
  9607. The question is, how can we decide whether to create a basic block?
  9608. \emph{Lazy evaluation}\index{subject}{lazy
  9609. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9610. delaying the creation of a basic block until the point in time at which
  9611. we know that it will be used.
  9612. %
  9613. {\if\edition\racketEd
  9614. %
  9615. Racket provides support for
  9616. lazy evaluation with the
  9617. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9618. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9619. \index{subject}{delay} creates a
  9620. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9621. expressions is postponed. When \key{(force}
  9622. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9623. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9624. result of $e_n$ is cached in the promise and returned. If \code{force}
  9625. is applied again to the same promise, then the cached result is
  9626. returned. If \code{force} is applied to an argument that is not a
  9627. promise, \code{force} simply returns the argument.
  9628. %
  9629. \fi}
  9630. %
  9631. {\if\edition\pythonEd\pythonColor
  9632. %
  9633. Although Python does not provide direct support for lazy evaluation,
  9634. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9635. by wrapping it inside a function with no parameters. We \emph{force}
  9636. its evaluation by calling the function. However, we might need to
  9637. force multiple times, so we store the result of calling the
  9638. function instead of recomputing it each time. The following
  9639. \code{Promise} class handles this memoization process.
  9640. \begin{minipage}{0.8\textwidth}
  9641. \begin{lstlisting}
  9642. @dataclass
  9643. class Promise:
  9644. fun : typing.Any
  9645. cache : list[stmt] = None
  9646. def force(self):
  9647. if self.cache is None:
  9648. self.cache = self.fun(); return self.cache
  9649. else:
  9650. return self.cache
  9651. \end{lstlisting}
  9652. \end{minipage}
  9653. \noindent However, in some cases of \code{explicate\_pred}, we return
  9654. a list of statements, and in other cases we return a function that
  9655. computes a list of statements. To uniformly deal with both regular
  9656. data and promises, we define the following \code{force} function that
  9657. checks whether its input is delayed (i.e., whether it is a
  9658. \code{Promise}) and then either (1) forces the promise or (2) returns
  9659. the input.
  9660. %
  9661. \begin{lstlisting}
  9662. def force(promise):
  9663. if isinstance(promise, Promise):
  9664. return promise.force()
  9665. else:
  9666. return promise
  9667. \end{lstlisting}
  9668. %
  9669. \fi}
  9670. We use promises for the input and output of the functions
  9671. \code{explicate\_pred}, \code{explicate\_assign},
  9672. %
  9673. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9674. %
  9675. So, instead of taking and returning \racket{$\Tail$
  9676. expressions}\python{lists of statements}, they take and return
  9677. promises. Furthermore, when we come to a situation in which a
  9678. continuation might be used more than once, as in the case for
  9679. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9680. that creates a basic block for each continuation (if there is not
  9681. already one) and then returns a \code{goto} statement to that basic
  9682. block. When we come to a situation in which we have a promise but need an
  9683. actual piece of code, for example, to create a larger piece of code with a
  9684. constructor such as \code{Seq}, then insert a call to \code{force}.
  9685. %
  9686. {\if\edition\racketEd
  9687. %
  9688. Also, we must modify the \code{create\_block} function to begin with
  9689. \code{delay} to create a promise. When forced, this promise forces the
  9690. original promise. If that returns a \code{Goto} (because the block was
  9691. already added to \code{basic-blocks}), then we return the
  9692. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9693. return a \code{Goto} to the new label.
  9694. \begin{center}
  9695. \begin{minipage}{\textwidth}
  9696. \begin{lstlisting}
  9697. (define (create_block tail)
  9698. (delay
  9699. (define t (force tail))
  9700. (match t
  9701. [(Goto label) (Goto label)]
  9702. [else
  9703. (let ([label (gensym 'block)])
  9704. (set! basic-blocks (cons (cons label t) basic-blocks))
  9705. (Goto label))])))
  9706. \end{lstlisting}
  9707. \end{minipage}
  9708. \end{center}
  9709. \fi}
  9710. {\if\edition\pythonEd\pythonColor
  9711. %
  9712. Here is the new version of the \code{create\_block} auxiliary function
  9713. that delays the creation of the new basic block.\\
  9714. \begin{minipage}{\textwidth}
  9715. \begin{lstlisting}
  9716. def create_block(promise, basic_blocks):
  9717. def delay():
  9718. stmts = force(promise)
  9719. match stmts:
  9720. case [Goto(l)]:
  9721. return [Goto(l)]
  9722. case _:
  9723. label = label_name(generate_name('block'))
  9724. basic_blocks[label] = stmts
  9725. return [Goto(label)]
  9726. return Promise(delay)
  9727. \end{lstlisting}
  9728. \end{minipage}
  9729. \fi}
  9730. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9731. improved \code{explicate\_control} on this example.
  9732. \racket{As you can see, the number of basic blocks has been reduced
  9733. from four blocks to two blocks.}%
  9734. \python{As you can see, the number of basic blocks has been reduced
  9735. from three blocks to two blocks.}
  9736. \begin{figure}[tbp]
  9737. \begin{tcolorbox}[colback=white]
  9738. {\if\edition\racketEd
  9739. \begin{tabular}{lll}
  9740. \begin{minipage}{0.45\textwidth}
  9741. % cond_test_82.rkt
  9742. \begin{lstlisting}
  9743. (let ([y (if #t
  9744. (read)
  9745. (if (eq? (read) 0)
  9746. 777
  9747. (let ([x (read)])
  9748. (+ 1 x))))])
  9749. (+ y 2))
  9750. \end{lstlisting}
  9751. \end{minipage}
  9752. &
  9753. $\quad\Rightarrow\quad$
  9754. &
  9755. \begin{minipage}{0.4\textwidth}
  9756. \begin{lstlisting}
  9757. start:
  9758. y = (read);
  9759. goto block_5;
  9760. block_5:
  9761. return (+ y 2);
  9762. \end{lstlisting}
  9763. \end{minipage}
  9764. \end{tabular}
  9765. \fi}
  9766. {\if\edition\pythonEd\pythonColor
  9767. \begin{tabular}{lll}
  9768. \begin{minipage}{0.4\textwidth}
  9769. % if/if_true.py
  9770. \begin{lstlisting}
  9771. if True:
  9772. print(0)
  9773. else:
  9774. x = 1 if False else 2
  9775. print(x)
  9776. \end{lstlisting}
  9777. \end{minipage}
  9778. &
  9779. $\Rightarrow$
  9780. &
  9781. \begin{minipage}{0.55\textwidth}
  9782. \begin{lstlisting}
  9783. start:
  9784. print(0)
  9785. goto block_4
  9786. block_4:
  9787. return 0
  9788. \end{lstlisting}
  9789. \end{minipage}
  9790. \end{tabular}
  9791. \fi}
  9792. \end{tcolorbox}
  9793. \caption{Translation from \LangIf{} to \LangCIf{}
  9794. via the improved \code{explicate\_control}.}
  9795. \label{fig:explicate-control-challenge}
  9796. \end{figure}
  9797. %% Recall that in the example output of \code{explicate\_control} in
  9798. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9799. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9800. %% block. The first goal of this challenge assignment is to remove those
  9801. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9802. %% \code{explicate\_control} on the left and shows the result of bypassing
  9803. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9804. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9805. %% \code{block55}. The optimized code on the right of
  9806. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9807. %% \code{then} branch jumping directly to \code{block55}. The story is
  9808. %% similar for the \code{else} branch, as well as for the two branches in
  9809. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9810. %% have been optimized in this way, there are no longer any jumps to
  9811. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9812. %% \begin{figure}[tbp]
  9813. %% \begin{tabular}{lll}
  9814. %% \begin{minipage}{0.4\textwidth}
  9815. %% \begin{lstlisting}
  9816. %% block62:
  9817. %% tmp54 = (read);
  9818. %% if (eq? tmp54 2) then
  9819. %% goto block59;
  9820. %% else
  9821. %% goto block60;
  9822. %% block61:
  9823. %% tmp53 = (read);
  9824. %% if (eq? tmp53 0) then
  9825. %% goto block57;
  9826. %% else
  9827. %% goto block58;
  9828. %% block60:
  9829. %% goto block56;
  9830. %% block59:
  9831. %% goto block55;
  9832. %% block58:
  9833. %% goto block56;
  9834. %% block57:
  9835. %% goto block55;
  9836. %% block56:
  9837. %% return (+ 700 77);
  9838. %% block55:
  9839. %% return (+ 10 32);
  9840. %% start:
  9841. %% tmp52 = (read);
  9842. %% if (eq? tmp52 1) then
  9843. %% goto block61;
  9844. %% else
  9845. %% goto block62;
  9846. %% \end{lstlisting}
  9847. %% \end{minipage}
  9848. %% &
  9849. %% $\Rightarrow$
  9850. %% &
  9851. %% \begin{minipage}{0.55\textwidth}
  9852. %% \begin{lstlisting}
  9853. %% block62:
  9854. %% tmp54 = (read);
  9855. %% if (eq? tmp54 2) then
  9856. %% goto block55;
  9857. %% else
  9858. %% goto block56;
  9859. %% block61:
  9860. %% tmp53 = (read);
  9861. %% if (eq? tmp53 0) then
  9862. %% goto block55;
  9863. %% else
  9864. %% goto block56;
  9865. %% block56:
  9866. %% return (+ 700 77);
  9867. %% block55:
  9868. %% return (+ 10 32);
  9869. %% start:
  9870. %% tmp52 = (read);
  9871. %% if (eq? tmp52 1) then
  9872. %% goto block61;
  9873. %% else
  9874. %% goto block62;
  9875. %% \end{lstlisting}
  9876. %% \end{minipage}
  9877. %% \end{tabular}
  9878. %% \caption{Optimize jumps by removing trivial blocks.}
  9879. %% \label{fig:optimize-jumps}
  9880. %% \end{figure}
  9881. %% The name of this pass is \code{optimize-jumps}. We recommend
  9882. %% implementing this pass in two phases. The first phrase builds a hash
  9883. %% table that maps labels to possibly improved labels. The second phase
  9884. %% changes the target of each \code{goto} to use the improved label. If
  9885. %% the label is for a trivial block, then the hash table should map the
  9886. %% label to the first non-trivial block that can be reached from this
  9887. %% label by jumping through trivial blocks. If the label is for a
  9888. %% non-trivial block, then the hash table should map the label to itself;
  9889. %% we do not want to change jumps to non-trivial blocks.
  9890. %% The first phase can be accomplished by constructing an empty hash
  9891. %% table, call it \code{short-cut}, and then iterating over the control
  9892. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9893. %% then update the hash table, mapping the block's source to the target
  9894. %% of the \code{goto}. Also, the hash table may already have mapped some
  9895. %% labels to the block's source, to you must iterate through the hash
  9896. %% table and update all of those so that they instead map to the target
  9897. %% of the \code{goto}.
  9898. %% For the second phase, we recommend iterating through the $\Tail$ of
  9899. %% each block in the program, updating the target of every \code{goto}
  9900. %% according to the mapping in \code{short-cut}.
  9901. \begin{exercise}\normalfont\normalsize
  9902. Implement the improvements to the \code{explicate\_control} pass.
  9903. Check that it removes trivial blocks in a few example programs. Then
  9904. check that your compiler still passes all your tests.
  9905. \end{exercise}
  9906. \subsection{Remove Jumps}
  9907. There is an opportunity for removing jumps that is apparent in the
  9908. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9909. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9910. and there are no other jumps to
  9911. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9912. In this situation we can avoid the runtime overhead of this jump by merging
  9913. \racket{\code{block\_5}}\python{\code{block\_4}}
  9914. into the preceding block, which in this case is the \code{start} block.
  9915. Figure~\ref{fig:remove-jumps} shows the output of
  9916. \code{allocate\_registers} on the left and the result of this
  9917. optimization on the right.
  9918. \begin{figure}[tbp]
  9919. \begin{tcolorbox}[colback=white]
  9920. {\if\edition\racketEd
  9921. \begin{tabular}{lll}
  9922. \begin{minipage}{0.5\textwidth}
  9923. % cond_test_82.rkt
  9924. \begin{lstlisting}
  9925. start:
  9926. callq read_int
  9927. movq %rax, %rcx
  9928. jmp block_5
  9929. block_5:
  9930. movq %rcx, %rax
  9931. addq $2, %rax
  9932. jmp conclusion
  9933. \end{lstlisting}
  9934. \end{minipage}
  9935. &
  9936. $\Rightarrow\qquad$
  9937. \begin{minipage}{0.4\textwidth}
  9938. \begin{lstlisting}
  9939. start:
  9940. callq read_int
  9941. movq %rax, %rcx
  9942. movq %rcx, %rax
  9943. addq $2, %rax
  9944. jmp conclusion
  9945. \end{lstlisting}
  9946. \end{minipage}
  9947. \end{tabular}
  9948. \fi}
  9949. {\if\edition\pythonEd\pythonColor
  9950. \begin{tabular}{lll}
  9951. \begin{minipage}{0.5\textwidth}
  9952. % cond_test_20.rkt
  9953. \begin{lstlisting}
  9954. start:
  9955. callq read_int
  9956. movq %rax, tmp_0
  9957. cmpq 1, tmp_0
  9958. je block_3
  9959. jmp block_4
  9960. block_3:
  9961. movq 42, tmp_1
  9962. jmp block_2
  9963. block_4:
  9964. movq 0, tmp_1
  9965. jmp block_2
  9966. block_2:
  9967. movq tmp_1, %rdi
  9968. callq print_int
  9969. movq 0, %rax
  9970. jmp conclusion
  9971. \end{lstlisting}
  9972. \end{minipage}
  9973. &
  9974. $\Rightarrow\qquad$
  9975. \begin{minipage}{0.4\textwidth}
  9976. \begin{lstlisting}
  9977. start:
  9978. callq read_int
  9979. movq %rax, tmp_0
  9980. cmpq 1, tmp_0
  9981. je block_3
  9982. movq 0, tmp_1
  9983. jmp block_2
  9984. block_3:
  9985. movq 42, tmp_1
  9986. jmp block_2
  9987. block_2:
  9988. movq tmp_1, %rdi
  9989. callq print_int
  9990. movq 0, %rax
  9991. jmp conclusion
  9992. \end{lstlisting}
  9993. \end{minipage}
  9994. \end{tabular}
  9995. \fi}
  9996. \end{tcolorbox}
  9997. \caption{Merging basic blocks by removing unnecessary jumps.}
  9998. \label{fig:remove-jumps}
  9999. \end{figure}
  10000. \begin{exercise}\normalfont\normalsize
  10001. %
  10002. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10003. into their preceding basic block, when there is only one preceding
  10004. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10005. %
  10006. {\if\edition\racketEd
  10007. In the \code{run-tests.rkt} script, add the following entry to the
  10008. list of \code{passes} between \code{allocate\_registers}
  10009. and \code{patch\_instructions}:
  10010. \begin{lstlisting}
  10011. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10012. \end{lstlisting}
  10013. \fi}
  10014. %
  10015. Run the script to test your compiler.
  10016. %
  10017. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10018. blocks on several test programs.
  10019. \end{exercise}
  10020. \section{Further Reading}
  10021. \label{sec:cond-further-reading}
  10022. The algorithm for the \code{explicate\_control} pass is based on the
  10023. \code{expose-basic-blocks} pass in the course notes of
  10024. \citet{Dybvig:2010aa}.
  10025. %
  10026. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10027. \citet{Appel:2003fk}, and is related to translations into continuation
  10028. passing
  10029. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10030. %
  10031. The treatment of conditionals in the \code{explicate\_control} pass is
  10032. similar to short-cut Boolean
  10033. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10034. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10035. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10036. \chapter{Loops and Dataflow Analysis}
  10037. \label{ch:Lwhile}
  10038. \setcounter{footnote}{0}
  10039. % TODO: define R'_8
  10040. % TODO: multi-graph
  10041. {\if\edition\racketEd
  10042. %
  10043. In this chapter we study two features that are the hallmarks of
  10044. imperative programming languages: loops and assignments to local
  10045. variables. The following example demonstrates these new features by
  10046. computing the sum of the first five positive integers:
  10047. % similar to loop_test_1.rkt
  10048. \begin{lstlisting}
  10049. (let ([sum 0])
  10050. (let ([i 5])
  10051. (begin
  10052. (while (> i 0)
  10053. (begin
  10054. (set! sum (+ sum i))
  10055. (set! i (- i 1))))
  10056. sum)))
  10057. \end{lstlisting}
  10058. The \code{while} loop consists of a condition and a
  10059. body.\footnote{The \code{while} loop is not a built-in
  10060. feature of the Racket language, but Racket includes many looping
  10061. constructs and it is straightforward to define \code{while} as a
  10062. macro.} The body is evaluated repeatedly so long as the condition
  10063. remains true.
  10064. %
  10065. The \code{set!} consists of a variable and a right-hand side
  10066. expression. The \code{set!} updates value of the variable to the
  10067. value of the right-hand side.
  10068. %
  10069. The primary purpose of both the \code{while} loop and \code{set!} is
  10070. to cause side effects, so they do not give a meaningful result
  10071. value. Instead, their result is the \code{\#<void>} value. The
  10072. expression \code{(void)} is an explicit way to create the
  10073. \code{\#<void>} value, and it has type \code{Void}. The
  10074. \code{\#<void>} value can be passed around just like other values
  10075. inside an \LangLoop{} program, and it can be compared for equality with
  10076. another \code{\#<void>} value. However, there are no other operations
  10077. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10078. Racket defines the \code{void?} predicate that returns \code{\#t}
  10079. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10080. %
  10081. \footnote{Racket's \code{Void} type corresponds to what is often
  10082. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10083. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10084. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10085. %
  10086. With the addition of side effect-producing features such as
  10087. \code{while} loop and \code{set!}, it is helpful to include a language
  10088. feature for sequencing side effects: the \code{begin} expression. It
  10089. consists of one or more subexpressions that are evaluated
  10090. left to right.
  10091. %
  10092. \fi}
  10093. {\if\edition\pythonEd\pythonColor
  10094. %
  10095. In this chapter we study loops, one of the hallmarks of imperative
  10096. programming languages. The following example demonstrates the
  10097. \code{while} loop by computing the sum of the first five positive
  10098. integers.
  10099. \begin{lstlisting}
  10100. sum = 0
  10101. i = 5
  10102. while i > 0:
  10103. sum = sum + i
  10104. i = i - 1
  10105. print(sum)
  10106. \end{lstlisting}
  10107. The \code{while} loop consists of a condition and a body (a sequence
  10108. of statements). The body is evaluated repeatedly so long as the
  10109. condition remains true.
  10110. %
  10111. \fi}
  10112. \section{The \LangLoop{} Language}
  10113. \newcommand{\LwhileGrammarRacket}{
  10114. \begin{array}{lcl}
  10115. \Type &::=& \key{Void}\\
  10116. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10117. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10118. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10119. \end{array}
  10120. }
  10121. \newcommand{\LwhileASTRacket}{
  10122. \begin{array}{lcl}
  10123. \Type &::=& \key{Void}\\
  10124. \Exp &::=& \SETBANG{\Var}{\Exp}
  10125. \MID \BEGIN{\Exp^{*}}{\Exp}
  10126. \MID \WHILE{\Exp}{\Exp}
  10127. \MID \VOID{}
  10128. \end{array}
  10129. }
  10130. \newcommand{\LwhileGrammarPython}{
  10131. \begin{array}{rcl}
  10132. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10133. \end{array}
  10134. }
  10135. \newcommand{\LwhileASTPython}{
  10136. \begin{array}{lcl}
  10137. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10138. \end{array}
  10139. }
  10140. \begin{figure}[tp]
  10141. \centering
  10142. \begin{tcolorbox}[colback=white]
  10143. \small
  10144. {\if\edition\racketEd
  10145. \[
  10146. \begin{array}{l}
  10147. \gray{\LintGrammarRacket{}} \\ \hline
  10148. \gray{\LvarGrammarRacket{}} \\ \hline
  10149. \gray{\LifGrammarRacket{}} \\ \hline
  10150. \LwhileGrammarRacket \\
  10151. \begin{array}{lcl}
  10152. \LangLoopM{} &::=& \Exp
  10153. \end{array}
  10154. \end{array}
  10155. \]
  10156. \fi}
  10157. {\if\edition\pythonEd\pythonColor
  10158. \[
  10159. \begin{array}{l}
  10160. \gray{\LintGrammarPython} \\ \hline
  10161. \gray{\LvarGrammarPython} \\ \hline
  10162. \gray{\LifGrammarPython} \\ \hline
  10163. \LwhileGrammarPython \\
  10164. \begin{array}{rcl}
  10165. \LangLoopM{} &::=& \Stmt^{*}
  10166. \end{array}
  10167. \end{array}
  10168. \]
  10169. \fi}
  10170. \end{tcolorbox}
  10171. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10172. \label{fig:Lwhile-concrete-syntax}
  10173. \end{figure}
  10174. \begin{figure}[tp]
  10175. \centering
  10176. \begin{tcolorbox}[colback=white]
  10177. \small
  10178. {\if\edition\racketEd
  10179. \[
  10180. \begin{array}{l}
  10181. \gray{\LintOpAST} \\ \hline
  10182. \gray{\LvarASTRacket{}} \\ \hline
  10183. \gray{\LifASTRacket{}} \\ \hline
  10184. \LwhileASTRacket{} \\
  10185. \begin{array}{lcl}
  10186. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10187. \end{array}
  10188. \end{array}
  10189. \]
  10190. \fi}
  10191. {\if\edition\pythonEd\pythonColor
  10192. \[
  10193. \begin{array}{l}
  10194. \gray{\LintASTPython} \\ \hline
  10195. \gray{\LvarASTPython} \\ \hline
  10196. \gray{\LifASTPython} \\ \hline
  10197. \LwhileASTPython \\
  10198. \begin{array}{lcl}
  10199. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10200. \end{array}
  10201. \end{array}
  10202. \]
  10203. \fi}
  10204. \end{tcolorbox}
  10205. \python{
  10206. \index{subject}{While@\texttt{While}}
  10207. }
  10208. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10209. \label{fig:Lwhile-syntax}
  10210. \end{figure}
  10211. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10212. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10213. shows the definition of its abstract syntax.
  10214. %
  10215. The definitional interpreter for \LangLoop{} is shown in
  10216. figure~\ref{fig:interp-Lwhile}.
  10217. %
  10218. {\if\edition\racketEd
  10219. %
  10220. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10221. and \code{Void}, and we make changes to the cases for \code{Var} and
  10222. \code{Let} regarding variables. To support assignment to variables and
  10223. to make their lifetimes indefinite (see the second example in
  10224. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10225. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10226. value.
  10227. %
  10228. Now we discuss the new cases. For \code{SetBang}, we find the
  10229. variable in the environment to obtain a boxed value, and then we change
  10230. it using \code{set-box!} to the result of evaluating the right-hand
  10231. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10232. %
  10233. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10234. if the result is true, (2) evaluate the body.
  10235. The result value of a \code{while} loop is also \code{\#<void>}.
  10236. %
  10237. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10238. subexpressions \itm{es} for their effects and then evaluates
  10239. and returns the result from \itm{body}.
  10240. %
  10241. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10242. %
  10243. \fi}
  10244. {\if\edition\pythonEd\pythonColor
  10245. %
  10246. We add a new case for \code{While} in the \code{interp\_stmts}
  10247. function, in which we repeatedly interpret the \code{body} so long as the
  10248. \code{test} expression remains true.
  10249. %
  10250. \fi}
  10251. \begin{figure}[tbp]
  10252. \begin{tcolorbox}[colback=white]
  10253. {\if\edition\racketEd
  10254. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10255. (define interp-Lwhile-class
  10256. (class interp-Lif-class
  10257. (super-new)
  10258. (define/override ((interp-exp env) e)
  10259. (define recur (interp-exp env))
  10260. (match e
  10261. [(Let x e body)
  10262. (define new-env (dict-set env x (box (recur e))))
  10263. ((interp-exp new-env) body)]
  10264. [(Var x) (unbox (dict-ref env x))]
  10265. [(SetBang x rhs)
  10266. (set-box! (dict-ref env x) (recur rhs))]
  10267. [(WhileLoop cnd body)
  10268. (define (loop)
  10269. (cond [(recur cnd) (recur body) (loop)]
  10270. [else (void)]))
  10271. (loop)]
  10272. [(Begin es body)
  10273. (for ([e es]) (recur e))
  10274. (recur body)]
  10275. [(Void) (void)]
  10276. [else ((super interp-exp env) e)]))
  10277. ))
  10278. (define (interp-Lwhile p)
  10279. (send (new interp-Lwhile-class) interp-program p))
  10280. \end{lstlisting}
  10281. \fi}
  10282. {\if\edition\pythonEd\pythonColor
  10283. \begin{lstlisting}
  10284. class InterpLwhile(InterpLif):
  10285. def interp_stmt(self, s, env, cont):
  10286. match s:
  10287. case While(test, body, []):
  10288. if self.interp_exp(test, env):
  10289. self.interp_stmts(body + [s] + cont, env)
  10290. else:
  10291. return self.interp_stmts(cont, env)
  10292. case _:
  10293. return super().interp_stmt(s, env, cont)
  10294. \end{lstlisting}
  10295. \fi}
  10296. \end{tcolorbox}
  10297. \caption{Interpreter for \LangLoop{}.}
  10298. \label{fig:interp-Lwhile}
  10299. \end{figure}
  10300. The definition of the type checker for \LangLoop{} is shown in
  10301. figure~\ref{fig:type-check-Lwhile}.
  10302. %
  10303. {\if\edition\racketEd
  10304. %
  10305. The type checking of the \code{SetBang} expression requires the type
  10306. of the variable and the right-hand side to agree. The result type is
  10307. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10308. and the result type is \code{Void}. For \code{Begin}, the result type
  10309. is the type of its last subexpression.
  10310. %
  10311. \fi}
  10312. %
  10313. {\if\edition\pythonEd\pythonColor
  10314. %
  10315. A \code{while} loop is well typed if the type of the \code{test}
  10316. expression is \code{bool} and the statements in the \code{body} are
  10317. well typed.
  10318. %
  10319. \fi}
  10320. \begin{figure}[tbp]
  10321. \begin{tcolorbox}[colback=white]
  10322. {\if\edition\racketEd
  10323. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10324. (define type-check-Lwhile-class
  10325. (class type-check-Lif-class
  10326. (super-new)
  10327. (inherit check-type-equal?)
  10328. (define/override (type-check-exp env)
  10329. (lambda (e)
  10330. (define recur (type-check-exp env))
  10331. (match e
  10332. [(SetBang x rhs)
  10333. (define-values (rhs^ rhsT) (recur rhs))
  10334. (define varT (dict-ref env x))
  10335. (check-type-equal? rhsT varT e)
  10336. (values (SetBang x rhs^) 'Void)]
  10337. [(WhileLoop cnd body)
  10338. (define-values (cnd^ Tc) (recur cnd))
  10339. (check-type-equal? Tc 'Boolean e)
  10340. (define-values (body^ Tbody) ((type-check-exp env) body))
  10341. (values (WhileLoop cnd^ body^) 'Void)]
  10342. [(Begin es body)
  10343. (define-values (es^ ts)
  10344. (for/lists (l1 l2) ([e es]) (recur e)))
  10345. (define-values (body^ Tbody) (recur body))
  10346. (values (Begin es^ body^) Tbody)]
  10347. [else ((super type-check-exp env) e)])))
  10348. ))
  10349. (define (type-check-Lwhile p)
  10350. (send (new type-check-Lwhile-class) type-check-program p))
  10351. \end{lstlisting}
  10352. \fi}
  10353. {\if\edition\pythonEd\pythonColor
  10354. \begin{lstlisting}
  10355. class TypeCheckLwhile(TypeCheckLif):
  10356. def type_check_stmts(self, ss, env):
  10357. if len(ss) == 0:
  10358. return
  10359. match ss[0]:
  10360. case While(test, body, []):
  10361. test_t = self.type_check_exp(test, env)
  10362. check_type_equal(bool, test_t, test)
  10363. body_t = self.type_check_stmts(body, env)
  10364. return self.type_check_stmts(ss[1:], env)
  10365. case _:
  10366. return super().type_check_stmts(ss, env)
  10367. \end{lstlisting}
  10368. \fi}
  10369. \end{tcolorbox}
  10370. \caption{Type checker for the \LangLoop{} language.}
  10371. \label{fig:type-check-Lwhile}
  10372. \end{figure}
  10373. {\if\edition\racketEd
  10374. %
  10375. At first glance, the translation of these language features to x86
  10376. seems straightforward because the \LangCIf{} intermediate language
  10377. already supports all the ingredients that we need: assignment,
  10378. \code{goto}, conditional branching, and sequencing. However,
  10379. complications arise, which we discuss in the next section. After
  10380. that we introduce the changes necessary to the existing passes.
  10381. %
  10382. \fi}
  10383. {\if\edition\pythonEd\pythonColor
  10384. %
  10385. At first glance, the translation of \code{while} loops to x86 seems
  10386. straightforward because the \LangCIf{} intermediate language already
  10387. supports \code{goto} and conditional branching. However, there are
  10388. complications that arise, which we discuss in the next section. After
  10389. that we introduce the changes necessary to the existing passes.
  10390. %
  10391. \fi}
  10392. \section{Cyclic Control Flow and Dataflow Analysis}
  10393. \label{sec:dataflow-analysis}
  10394. Up until this point, the programs generated in
  10395. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10396. \code{while} loop introduces a cycle. Does that matter?
  10397. %
  10398. Indeed, it does. Recall that for register allocation, the compiler
  10399. performs liveness analysis to determine which variables can share the
  10400. same register. To accomplish this, we analyzed the control-flow graph
  10401. in reverse topological order
  10402. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10403. well defined only for acyclic graphs.
  10404. Let us return to the example of computing the sum of the first five
  10405. positive integers. Here is the program after instruction
  10406. selection\index{subject}{instruction selection} but before register
  10407. allocation.
  10408. \begin{center}
  10409. {\if\edition\racketEd
  10410. \begin{minipage}{0.45\textwidth}
  10411. \begin{lstlisting}
  10412. (define (main) : Integer
  10413. mainstart:
  10414. movq $0, sum
  10415. movq $5, i
  10416. jmp block5
  10417. block5:
  10418. movq i, tmp3
  10419. cmpq tmp3, $0
  10420. jl block7
  10421. jmp block8
  10422. \end{lstlisting}
  10423. \end{minipage}
  10424. \begin{minipage}{0.45\textwidth}
  10425. \begin{lstlisting}
  10426. block7:
  10427. addq i, sum
  10428. movq $1, tmp4
  10429. negq tmp4
  10430. addq tmp4, i
  10431. jmp block5
  10432. block8:
  10433. movq $27, %rax
  10434. addq sum, %rax
  10435. jmp mainconclusion)
  10436. \end{lstlisting}
  10437. \end{minipage}
  10438. \fi}
  10439. {\if\edition\pythonEd\pythonColor
  10440. \begin{minipage}{0.45\textwidth}
  10441. \begin{lstlisting}
  10442. mainstart:
  10443. movq $0, sum
  10444. movq $5, i
  10445. jmp block5
  10446. block5:
  10447. cmpq $0, i
  10448. jg block7
  10449. jmp block8
  10450. \end{lstlisting}
  10451. \end{minipage}
  10452. \begin{minipage}{0.45\textwidth}
  10453. \begin{lstlisting}
  10454. block7:
  10455. addq i, sum
  10456. subq $1, i
  10457. jmp block5
  10458. block8:
  10459. movq sum, %rdi
  10460. callq print_int
  10461. movq $0, %rax
  10462. jmp mainconclusion
  10463. \end{lstlisting}
  10464. \end{minipage}
  10465. \fi}
  10466. \end{center}
  10467. Recall that liveness analysis works backward, starting at the end
  10468. of each function. For this example we could start with \code{block8}
  10469. because we know what is live at the beginning of the conclusion:
  10470. only \code{rax} and \code{rsp}. So the live-before set
  10471. for \code{block8} is \code{\{rsp,sum\}}.
  10472. %
  10473. Next we might try to analyze \code{block5} or \code{block7}, but
  10474. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10475. we are stuck.
  10476. The way out of this impasse is to realize that we can compute an
  10477. underapproximation of each live-before set by starting with empty
  10478. live-after sets. By \emph{underapproximation}, we mean that the set
  10479. contains only variables that are live for some execution of the
  10480. program, but the set may be missing some variables that are live.
  10481. Next, the underapproximations for each block can be improved by (1)
  10482. updating the live-after set for each block using the approximate
  10483. live-before sets from the other blocks, and (2) performing liveness
  10484. analysis again on each block. In fact, by iterating this process, the
  10485. underapproximations eventually become the correct solutions!
  10486. %
  10487. This approach of iteratively analyzing a control-flow graph is
  10488. applicable to many static analysis problems and goes by the name
  10489. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10490. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10491. Washington.
  10492. Let us apply this approach to the previously presented example. We use
  10493. the empty set for the initial live-before set for each block. Let
  10494. $m_0$ be the following mapping from label names to sets of locations
  10495. (variables and registers):
  10496. \begin{center}
  10497. \begin{lstlisting}
  10498. mainstart: {}, block5: {}, block7: {}, block8: {}
  10499. \end{lstlisting}
  10500. \end{center}
  10501. Using the above live-before approximations, we determine the
  10502. live-after for each block and then apply liveness analysis to each
  10503. block. This produces our next approximation $m_1$ of the live-before
  10504. sets.
  10505. \begin{center}
  10506. \begin{lstlisting}
  10507. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10508. \end{lstlisting}
  10509. \end{center}
  10510. For the second round, the live-after for \code{mainstart} is the
  10511. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10512. the liveness analysis for \code{mainstart} computes the empty set. The
  10513. live-after for \code{block5} is the union of the live-before sets for
  10514. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10515. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10516. sum\}}. The live-after for \code{block7} is the live-before for
  10517. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10518. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10519. Together these yield the following approximation $m_2$ of
  10520. the live-before sets:
  10521. \begin{center}
  10522. \begin{lstlisting}
  10523. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10524. \end{lstlisting}
  10525. \end{center}
  10526. In the preceding iteration, only \code{block5} changed, so we can
  10527. limit our attention to \code{mainstart} and \code{block7}, the two
  10528. blocks that jump to \code{block5}. As a result, the live-before sets
  10529. for \code{mainstart} and \code{block7} are updated to include
  10530. \code{rsp}, yielding the following approximation $m_3$:
  10531. \begin{center}
  10532. \begin{lstlisting}
  10533. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10534. \end{lstlisting}
  10535. \end{center}
  10536. Because \code{block7} changed, we analyze \code{block5} once more, but
  10537. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10538. our approximations have converged, so $m_3$ is the solution.
  10539. This iteration process is guaranteed to converge to a solution by the
  10540. Kleene fixed-point theorem, a general theorem about functions on
  10541. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10542. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10543. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10544. join operator
  10545. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10546. will be working with join semilattices.} When two elements are
  10547. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10548. as much information as $m_i$, so we can think of $m_j$ as a
  10549. better-than-or-equal-to approximation in relation to $m_i$. The
  10550. bottom element $\bot$ represents the complete lack of information,
  10551. that is, the worst approximation. The join operator takes two lattice
  10552. elements and combines their information; that is, it produces the
  10553. least upper bound of the two.\index{subject}{least upper bound}
  10554. A dataflow analysis typically involves two lattices: one lattice to
  10555. represent abstract states and another lattice that aggregates the
  10556. abstract states of all the blocks in the control-flow graph. For
  10557. liveness analysis, an abstract state is a set of locations. We form
  10558. the lattice $L$ by taking its elements to be sets of locations, the
  10559. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10560. set, and the join operator to be set union.
  10561. %
  10562. We form a second lattice $M$ by taking its elements to be mappings
  10563. from the block labels to sets of locations (elements of $L$). We
  10564. order the mappings point-wise, using the ordering of $L$. So, given any
  10565. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10566. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10567. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10568. to the empty set, $\bot_M(\ell) = \emptyset$.
  10569. We can think of one iteration of liveness analysis applied to the
  10570. whole program as being a function $f$ on the lattice $M$. It takes a
  10571. mapping as input and computes a new mapping.
  10572. \[
  10573. f(m_i) = m_{i+1}
  10574. \]
  10575. Next let us think for a moment about what a final solution $m_s$
  10576. should look like. If we perform liveness analysis using the solution
  10577. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10578. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10579. \[
  10580. f(m_s) = m_s
  10581. \]
  10582. Furthermore, the solution should include only locations that are
  10583. forced to be there by performing liveness analysis on the program, so
  10584. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10585. The Kleene fixed-point theorem states that if a function $f$ is
  10586. monotone (better inputs produce better outputs), then the least fixed
  10587. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10588. chain} that starts at $\bot$ and iterates $f$ as
  10589. follows:\index{subject}{Kleene fixed-point theorem}
  10590. \[
  10591. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10592. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10593. \]
  10594. When a lattice contains only finitely long ascending chains, then
  10595. every Kleene chain tops out at some fixed point after some number of
  10596. iterations of $f$.
  10597. \[
  10598. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10599. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10600. \]
  10601. The liveness analysis is indeed a monotone function and the lattice
  10602. $M$ has finitely long ascending chains because there are only a
  10603. finite number of variables and blocks in the program. Thus we are
  10604. guaranteed that iteratively applying liveness analysis to all blocks
  10605. in the program will eventually produce the least fixed point solution.
  10606. Next let us consider dataflow analysis in general and discuss the
  10607. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10608. %
  10609. The algorithm has four parameters: the control-flow graph \code{G}, a
  10610. function \code{transfer} that applies the analysis to one block, and the
  10611. \code{bottom} and \code{join} operators for the lattice of abstract
  10612. states. The \code{analyze\_dataflow} function is formulated as a
  10613. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10614. function come from the predecessor nodes in the control-flow
  10615. graph. However, liveness analysis is a \emph{backward} dataflow
  10616. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10617. function with the transpose of the control-flow graph.
  10618. The algorithm begins by creating the bottom mapping, represented by a
  10619. hash table. It then pushes all the nodes in the control-flow graph
  10620. onto the work list (a queue). The algorithm repeats the \code{while}
  10621. loop as long as there are items in the work list. In each iteration, a
  10622. node is popped from the work list and processed. The \code{input} for
  10623. the node is computed by taking the join of the abstract states of all
  10624. the predecessor nodes. The \code{transfer} function is then applied to
  10625. obtain the \code{output} abstract state. If the output differs from
  10626. the previous state for this block, the mapping for this block is
  10627. updated and its successor nodes are pushed onto the work list.
  10628. \begin{figure}[tb]
  10629. \begin{tcolorbox}[colback=white]
  10630. {\if\edition\racketEd
  10631. \begin{lstlisting}
  10632. (define (analyze_dataflow G transfer bottom join)
  10633. (define mapping (make-hash))
  10634. (for ([v (in-vertices G)])
  10635. (dict-set! mapping v bottom))
  10636. (define worklist (make-queue))
  10637. (for ([v (in-vertices G)])
  10638. (enqueue! worklist v))
  10639. (define trans-G (transpose G))
  10640. (while (not (queue-empty? worklist))
  10641. (define node (dequeue! worklist))
  10642. (define input (for/fold ([state bottom])
  10643. ([pred (in-neighbors trans-G node)])
  10644. (join state (dict-ref mapping pred))))
  10645. (define output (transfer node input))
  10646. (cond [(not (equal? output (dict-ref mapping node)))
  10647. (dict-set! mapping node output)
  10648. (for ([v (in-neighbors G node)])
  10649. (enqueue! worklist v))]))
  10650. mapping)
  10651. \end{lstlisting}
  10652. \fi}
  10653. {\if\edition\pythonEd\pythonColor
  10654. \begin{lstlisting}
  10655. def analyze_dataflow(G, transfer, bottom, join):
  10656. trans_G = transpose(G)
  10657. mapping = dict((v, bottom) for v in G.vertices())
  10658. worklist = deque(G.vertices)
  10659. while worklist:
  10660. node = worklist.pop()
  10661. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10662. input = reduce(join, inputs, bottom)
  10663. output = transfer(node, input)
  10664. if output != mapping[node]:
  10665. mapping[node] = output
  10666. worklist.extend(G.adjacent(node))
  10667. \end{lstlisting}
  10668. \fi}
  10669. \end{tcolorbox}
  10670. \caption{Generic work list algorithm for dataflow analysis.}
  10671. \label{fig:generic-dataflow}
  10672. \end{figure}
  10673. {\if\edition\racketEd
  10674. \section{Mutable Variables and Remove Complex Operands}
  10675. There is a subtle interaction between the
  10676. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10677. and the left-to-right order of evaluation of Racket. Consider the
  10678. following example:
  10679. \begin{lstlisting}
  10680. (let ([x 2])
  10681. (+ x (begin (set! x 40) x)))
  10682. \end{lstlisting}
  10683. The result of this program is \code{42} because the first read from
  10684. \code{x} produces \code{2} and the second produces \code{40}. However,
  10685. if we naively apply the \code{remove\_complex\_operands} pass to this
  10686. example we obtain the following program whose result is \code{80}!
  10687. \begin{lstlisting}
  10688. (let ([x 2])
  10689. (let ([tmp (begin (set! x 40) x)])
  10690. (+ x tmp)))
  10691. \end{lstlisting}
  10692. The problem is that with mutable variables, the ordering between
  10693. reads and writes is important, and the
  10694. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10695. before the first read of \code{x}.
  10696. We recommend solving this problem by giving special treatment to reads
  10697. from mutable variables, that is, variables that occur on the left-hand
  10698. side of a \code{set!}. We mark each read from a mutable variable with
  10699. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10700. that the read operation is effectful in that it can produce different
  10701. results at different points in time. Let's apply this idea to the
  10702. following variation that also involves a variable that is not mutated:
  10703. % loop_test_24.rkt
  10704. \begin{lstlisting}
  10705. (let ([x 2])
  10706. (let ([y 0])
  10707. (+ y (+ x (begin (set! x 40) x)))))
  10708. \end{lstlisting}
  10709. We first analyze this program to discover that variable \code{x}
  10710. is mutable but \code{y} is not. We then transform the program as
  10711. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10712. \begin{lstlisting}
  10713. (let ([x 2])
  10714. (let ([y 0])
  10715. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10716. \end{lstlisting}
  10717. Now that we have a clear distinction between reads from mutable and
  10718. immutable variables, we can apply the \code{remove\_complex\_operands}
  10719. pass, where reads from immutable variables are still classified as
  10720. atomic expressions but reads from mutable variables are classified as
  10721. complex. Thus, \code{remove\_complex\_operands} yields the following
  10722. program:\\
  10723. \begin{minipage}{\textwidth}
  10724. \begin{lstlisting}
  10725. (let ([x 2])
  10726. (let ([y 0])
  10727. (let ([t1 x])
  10728. (let ([t2 (begin (set! x 40) x)])
  10729. (let ([t3 (+ t1 t2)])
  10730. (+ y t3))))))
  10731. \end{lstlisting}
  10732. \end{minipage}
  10733. The temporary variable \code{t1} gets the value of \code{x} before the
  10734. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10735. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10736. do not generate a temporary variable for the occurrence of \code{y}
  10737. because it's an immutable variable. We want to avoid such unnecessary
  10738. extra temporaries because they would needlessly increase the number of
  10739. variables, making it more likely for some of them to be spilled. The
  10740. result of this program is \code{42}, the same as the result prior to
  10741. \code{remove\_complex\_operands}.
  10742. The approach that we've sketched requires only a small
  10743. modification to \code{remove\_complex\_operands} to handle
  10744. \code{get!}. However, it requires a new pass, called
  10745. \code{uncover-get!}, that we discuss in
  10746. section~\ref{sec:uncover-get-bang}.
  10747. As an aside, this problematic interaction between \code{set!} and the
  10748. pass \code{remove\_complex\_operands} is particular to Racket and not
  10749. its predecessor, the Scheme language. The key difference is that
  10750. Scheme does not specify an order of evaluation for the arguments of an
  10751. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10752. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10753. would be correct results for the example program. Interestingly,
  10754. Racket is implemented on top of the Chez Scheme
  10755. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10756. presented in this section (using extra \code{let} bindings to control
  10757. the order of evaluation) is used in the translation from Racket to
  10758. Scheme~\citep{Flatt:2019tb}.
  10759. \fi} % racket
  10760. Having discussed the complications that arise from adding support for
  10761. assignment and loops, we turn to discussing the individual compilation
  10762. passes.
  10763. {\if\edition\racketEd
  10764. \section{Uncover \texttt{get!}}
  10765. \label{sec:uncover-get-bang}
  10766. The goal of this pass is to mark uses of mutable variables so that
  10767. \code{remove\_complex\_operands} can treat them as complex expressions
  10768. and thereby preserve their ordering relative to the side effects in
  10769. other operands. So, the first step is to collect all the mutable
  10770. variables. We recommend creating an auxiliary function for this,
  10771. named \code{collect-set!}, that recursively traverses expressions,
  10772. returning the set of all variables that occur on the left-hand side of a
  10773. \code{set!}. Here's an excerpt of its implementation.
  10774. \begin{center}
  10775. \begin{minipage}{\textwidth}
  10776. \begin{lstlisting}
  10777. (define (collect-set! e)
  10778. (match e
  10779. [(Var x) (set)]
  10780. [(Int n) (set)]
  10781. [(Let x rhs body)
  10782. (set-union (collect-set! rhs) (collect-set! body))]
  10783. [(SetBang var rhs)
  10784. (set-union (set var) (collect-set! rhs))]
  10785. ...))
  10786. \end{lstlisting}
  10787. \end{minipage}
  10788. \end{center}
  10789. By placing this pass after \code{uniquify}, we need not worry about
  10790. variable shadowing, and our logic for \code{Let} can remain simple, as
  10791. in this excerpt.
  10792. The second step is to mark the occurrences of the mutable variables
  10793. with the new \code{GetBang} AST node (\code{get!} in concrete
  10794. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10795. function, which takes two parameters: the set of mutable variables
  10796. \code{set!-vars} and the expression \code{e} to be processed. The
  10797. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10798. mutable variable or leaves it alone if not.
  10799. \begin{center}
  10800. \begin{minipage}{\textwidth}
  10801. \begin{lstlisting}
  10802. (define ((uncover-get!-exp set!-vars) e)
  10803. (match e
  10804. [(Var x)
  10805. (if (set-member? set!-vars x)
  10806. (GetBang x)
  10807. (Var x))]
  10808. ...))
  10809. \end{lstlisting}
  10810. \end{minipage}
  10811. \end{center}
  10812. To wrap things up, define the \code{uncover-get!} function for
  10813. processing a whole program, using \code{collect-set!} to obtain the
  10814. set of mutable variables and then \code{uncover-get!-exp} to replace
  10815. their occurrences with \code{GetBang}.
  10816. \fi}
  10817. \section{Remove Complex Operands}
  10818. \label{sec:rco-loop}
  10819. {\if\edition\racketEd
  10820. %
  10821. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10822. \code{while} are all complex expressions. The subexpressions of
  10823. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10824. %
  10825. \fi}
  10826. {\if\edition\pythonEd\pythonColor
  10827. %
  10828. The change needed for this pass is to add a case for the \code{while}
  10829. statement. The condition of a loop is allowed to be a complex
  10830. expression, just like the condition of the \code{if} statement.
  10831. %
  10832. \fi}
  10833. %
  10834. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10835. \LangLoopANF{} of this pass.
  10836. \newcommand{\LwhileMonadASTRacket}{
  10837. \begin{array}{rcl}
  10838. \Atm &::=& \VOID{} \\
  10839. \Exp &::=& \GETBANG{\Var}
  10840. \MID \SETBANG{\Var}{\Exp}
  10841. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10842. &\MID& \WHILE{\Exp}{\Exp}
  10843. \end{array}
  10844. }
  10845. \newcommand{\LwhileMonadASTPython}{
  10846. \begin{array}{rcl}
  10847. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10848. \end{array}
  10849. }
  10850. \begin{figure}[tp]
  10851. \centering
  10852. \begin{tcolorbox}[colback=white]
  10853. \small
  10854. {\if\edition\racketEd
  10855. \[
  10856. \begin{array}{l}
  10857. \gray{\LvarMonadASTRacket} \\ \hline
  10858. \gray{\LifMonadASTRacket} \\ \hline
  10859. \LwhileMonadASTRacket \\
  10860. \begin{array}{rcl}
  10861. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10862. \end{array}
  10863. \end{array}
  10864. \]
  10865. \fi}
  10866. {\if\edition\pythonEd\pythonColor
  10867. \[
  10868. \begin{array}{l}
  10869. \gray{\LvarMonadASTPython} \\ \hline
  10870. \gray{\LifMonadASTPython} \\ \hline
  10871. \LwhileMonadASTPython \\
  10872. \begin{array}{rcl}
  10873. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10874. \end{array}
  10875. \end{array}
  10876. \]
  10877. \fi}
  10878. \end{tcolorbox}
  10879. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10880. \label{fig:Lwhile-anf-syntax}
  10881. \end{figure}
  10882. {\if\edition\racketEd
  10883. %
  10884. As usual, when a complex expression appears in a grammar position that
  10885. needs to be atomic, such as the argument of a primitive operator, we
  10886. must introduce a temporary variable and bind it to the complex
  10887. expression. This approach applies, unchanged, to handle the new
  10888. language forms. For example, in the following code there are two
  10889. \code{begin} expressions appearing as arguments to the \code{+}
  10890. operator. The output of \code{rco\_exp} is then shown, in which the
  10891. \code{begin} expressions have been bound to temporary
  10892. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10893. allowed to have arbitrary expressions in their right-hand side
  10894. expression, so it is fine to place \code{begin} there.
  10895. %
  10896. \begin{center}
  10897. \begin{tabular}{lcl}
  10898. \begin{minipage}{0.4\textwidth}
  10899. \begin{lstlisting}
  10900. (let ([x2 10])
  10901. (let ([y3 0])
  10902. (+ (+ (begin
  10903. (set! y3 (read))
  10904. (get! x2))
  10905. (begin
  10906. (set! x2 (read))
  10907. (get! y3)))
  10908. (get! x2))))
  10909. \end{lstlisting}
  10910. \end{minipage}
  10911. &
  10912. $\Rightarrow$
  10913. &
  10914. \begin{minipage}{0.4\textwidth}
  10915. \begin{lstlisting}
  10916. (let ([x2 10])
  10917. (let ([y3 0])
  10918. (let ([tmp4 (begin
  10919. (set! y3 (read))
  10920. x2)])
  10921. (let ([tmp5 (begin
  10922. (set! x2 (read))
  10923. y3)])
  10924. (let ([tmp6 (+ tmp4 tmp5)])
  10925. (let ([tmp7 x2])
  10926. (+ tmp6 tmp7)))))))
  10927. \end{lstlisting}
  10928. \end{minipage}
  10929. \end{tabular}
  10930. \end{center}
  10931. \fi}
  10932. \section{Explicate Control \racket{and \LangCLoop{}}}
  10933. \label{sec:explicate-loop}
  10934. \newcommand{\CloopASTRacket}{
  10935. \begin{array}{lcl}
  10936. \Atm &::=& \VOID \\
  10937. \Stmt &::=& \READ{}
  10938. \end{array}
  10939. }
  10940. {\if\edition\racketEd
  10941. Recall that in the \code{explicate\_control} pass we define one helper
  10942. function for each kind of position in the program. For the \LangVar{}
  10943. language of integers and variables, we needed assignment and tail
  10944. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10945. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10946. another kind of position: effect position. Except for the last
  10947. subexpression, the subexpressions inside a \code{begin} are evaluated
  10948. only for their effect. Their result values are discarded. We can
  10949. generate better code by taking this fact into account.
  10950. The output language of \code{explicate\_control} is \LangCLoop{}
  10951. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10952. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10953. and that \code{read} may appear as a statement. The most significant
  10954. difference between the programs generated by \code{explicate\_control}
  10955. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10956. chapter is that the control-flow graphs of the latter may contain
  10957. cycles.
  10958. \begin{figure}[tp]
  10959. \begin{tcolorbox}[colback=white]
  10960. \small
  10961. \[
  10962. \begin{array}{l}
  10963. \gray{\CvarASTRacket} \\ \hline
  10964. \gray{\CifASTRacket} \\ \hline
  10965. \CloopASTRacket \\
  10966. \begin{array}{lcl}
  10967. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10968. \end{array}
  10969. \end{array}
  10970. \]
  10971. \end{tcolorbox}
  10972. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10973. \label{fig:c7-syntax}
  10974. \end{figure}
  10975. The new auxiliary function \code{explicate\_effect} takes an
  10976. expression (in an effect position) and the code for its
  10977. continuation. The function returns a $\Tail$ that includes the
  10978. generated code for the input expression followed by the
  10979. continuation. If the expression is obviously pure, that is, never
  10980. causes side effects, then the expression can be removed, so the result
  10981. is just the continuation.
  10982. %
  10983. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10984. interesting; the generated code is depicted in the following diagram:
  10985. \begin{center}
  10986. \begin{minipage}{0.3\textwidth}
  10987. \xymatrix{
  10988. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10989. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10990. & *+[F]{\txt{\itm{cont}}} \\
  10991. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10992. }
  10993. \end{minipage}
  10994. \end{center}
  10995. We start by creating a fresh label $\itm{loop}$ for the top of the
  10996. loop. Next, recursively process the \itm{body} (in effect position)
  10997. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10998. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10999. \itm{body'} as the \emph{then} branch and the continuation block as the
  11000. \emph{else} branch. The result should be added to the dictionary of
  11001. \code{basic-blocks} with the label \itm{loop}. The result for the
  11002. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11003. The auxiliary functions for tail, assignment, and predicate positions
  11004. need to be updated. The three new language forms, \code{while},
  11005. \code{set!}, and \code{begin}, can appear in assignment and tail
  11006. positions. Only \code{begin} may appear in predicate positions; the
  11007. other two have result type \code{Void}.
  11008. \fi}
  11009. %
  11010. {\if\edition\pythonEd\pythonColor
  11011. %
  11012. The output of this pass is the language \LangCIf{}. No new language
  11013. features are needed in the output, because a \code{while} loop can be
  11014. expressed in terms of \code{goto} and \code{if} statements, which are
  11015. already in \LangCIf{}.
  11016. %
  11017. Add a case for the \code{while} statement to the
  11018. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11019. the condition expression.
  11020. %
  11021. \fi}
  11022. {\if\edition\racketEd
  11023. \section{Select Instructions}
  11024. \label{sec:select-instructions-loop}
  11025. \index{subject}{select instructions}
  11026. Only two small additions are needed in the \code{select\_instructions}
  11027. pass to handle the changes to \LangCLoop{}. First, to handle the
  11028. addition of \VOID{} we simply translate it to \code{0}. Second,
  11029. \code{read} may appear as a stand-alone statement instead of
  11030. appearing only on the right-hand side of an assignment statement. The code
  11031. generation is nearly identical to the one for assignment; just leave
  11032. off the instruction for moving the result into the left-hand side.
  11033. \fi}
  11034. \section{Register Allocation}
  11035. \label{sec:register-allocation-loop}
  11036. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11037. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11038. which complicates the liveness analysis needed for register
  11039. allocation.
  11040. %
  11041. We recommend using the generic \code{analyze\_dataflow} function that
  11042. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11043. perform liveness analysis, replacing the code in
  11044. \code{uncover\_live} that processed the basic blocks in topological
  11045. order (section~\ref{sec:liveness-analysis-Lif}).
  11046. The \code{analyze\_dataflow} function has the following four parameters.
  11047. \begin{enumerate}
  11048. \item The first parameter \code{G} should be passed the transpose
  11049. of the control-flow graph.
  11050. \item The second parameter \code{transfer} should be passed a function
  11051. that applies liveness analysis to a basic block. It takes two
  11052. parameters: the label for the block to analyze and the live-after
  11053. set for that block. The transfer function should return the
  11054. live-before set for the block.
  11055. %
  11056. \racket{Also, as a side effect, it should update the block's
  11057. $\itm{info}$ with the liveness information for each instruction.}
  11058. %
  11059. \python{Also, as a side effect, it should update the live-before and
  11060. live-after sets for each instruction.}
  11061. %
  11062. To implement the \code{transfer} function, you should be able to
  11063. reuse the code you already have for analyzing basic blocks.
  11064. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11065. \code{bottom} and \code{join} for the lattice of abstract states,
  11066. that is, sets of locations. For liveness analysis, the bottom of the
  11067. lattice is the empty set, and the join operator is set union.
  11068. \end{enumerate}
  11069. \begin{figure}[tp]
  11070. \begin{tcolorbox}[colback=white]
  11071. {\if\edition\racketEd
  11072. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11073. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11074. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11075. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11076. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11077. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11078. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11079. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11080. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11081. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11082. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11083. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11084. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11085. \path[->,bend left=15] (Lfun) edge [above] node
  11086. {\ttfamily\footnotesize shrink} (Lfun-2);
  11087. \path[->,bend left=15] (Lfun-2) edge [above] node
  11088. {\ttfamily\footnotesize uniquify} (F1-4);
  11089. \path[->,bend left=15] (F1-4) edge [above] node
  11090. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11091. \path[->,bend left=15] (F1-5) edge [left] node
  11092. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11093. \path[->,bend left=10] (F1-6) edge [above] node
  11094. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11095. \path[->,bend left=15] (C3-2) edge [right] node
  11096. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11097. \path[->,bend right=15] (x86-2) edge [right] node
  11098. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11099. \path[->,bend right=15] (x86-2-1) edge [below] node
  11100. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11101. \path[->,bend right=15] (x86-2-2) edge [right] node
  11102. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11103. \path[->,bend left=15] (x86-3) edge [above] node
  11104. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11105. \path[->,bend left=15] (x86-4) edge [right] node
  11106. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11107. \end{tikzpicture}
  11108. \fi}
  11109. {\if\edition\pythonEd\pythonColor
  11110. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11111. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11112. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11113. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11114. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11115. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11116. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11117. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11118. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11119. \path[->,bend left=15] (Lfun) edge [above] node
  11120. {\ttfamily\footnotesize shrink} (Lfun-2);
  11121. \path[->,bend left=15] (Lfun-2) edge [above] node
  11122. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11123. \path[->,bend left=10] (F1-6) edge [right] node
  11124. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11125. \path[->,bend right=15] (C3-2) edge [right] node
  11126. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11127. \path[->,bend right=15] (x86-2) edge [below] node
  11128. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11129. \path[->,bend left=15] (x86-3) edge [above] node
  11130. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11131. \path[->,bend right=15] (x86-4) edge [below] node
  11132. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11133. \end{tikzpicture}
  11134. \fi}
  11135. \end{tcolorbox}
  11136. \caption{Diagram of the passes for \LangLoop{}.}
  11137. \label{fig:Lwhile-passes}
  11138. \end{figure}
  11139. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11140. for the compilation of \LangLoop{}.
  11141. % Further Reading: dataflow analysis
  11142. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11143. \chapter{Tuples and Garbage Collection}
  11144. \label{ch:Lvec}
  11145. \index{subject}{tuple}
  11146. \index{subject}{vector}
  11147. \setcounter{footnote}{0}
  11148. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11149. %% all the IR grammars are spelled out! \\ --Jeremy}
  11150. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11151. %% the root stack. \\ --Jeremy}
  11152. In this chapter we study the implementation of tuples\racket{, called
  11153. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11154. in which each element may have a different type.
  11155. %
  11156. This language feature is the first to use the computer's
  11157. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11158. indefinite; that is, a tuple lives forever from the programmer's
  11159. viewpoint. Of course, from an implementer's viewpoint, it is important
  11160. to reclaim the space associated with a tuple when it is no longer
  11161. needed, which is why we also study \emph{garbage collection}
  11162. \index{subject}{garbage collection} techniques in this chapter.
  11163. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11164. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11165. language (chapter~\ref{ch:Lwhile}) with tuples.
  11166. %
  11167. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11168. copying live tuples back and forth between two halves of the heap. The
  11169. garbage collector requires coordination with the compiler so that it
  11170. can find all the live tuples.
  11171. %
  11172. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11173. discuss the necessary changes and additions to the compiler passes,
  11174. including a new compiler pass named \code{expose\_allocation}.
  11175. \section{The \LangVec{} Language}
  11176. \label{sec:r3}
  11177. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11178. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11179. the definition of the abstract syntax.
  11180. %
  11181. \racket{The \LangVec{} language includes the forms \code{vector} for
  11182. creating a tuple, \code{vector-ref} for reading an element of a
  11183. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11184. \code{vector-length} for obtaining the number of elements of a
  11185. tuple.}
  11186. %
  11187. \python{The \LangVec{} language adds (1) tuple creation via a
  11188. comma-separated list of expressions; (2) accessing an element of a
  11189. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11190. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11191. comparison operator; and (4) obtaining the number of elements (the
  11192. length) of a tuple. In this chapter, we restrict access indices to
  11193. constant integers.}
  11194. %
  11195. The following program shows an example of the use of tuples. It creates a tuple
  11196. \code{t} containing the elements \code{40},
  11197. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11198. contains just \code{2}. The element at index $1$ of \code{t} is
  11199. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11200. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11201. to which we add \code{2}, the element at index $0$ of the tuple.
  11202. The result of the program is \code{42}.
  11203. %
  11204. {\if\edition\racketEd
  11205. \begin{lstlisting}
  11206. (let ([t (vector 40 #t (vector 2))])
  11207. (if (vector-ref t 1)
  11208. (+ (vector-ref t 0)
  11209. (vector-ref (vector-ref t 2) 0))
  11210. 44))
  11211. \end{lstlisting}
  11212. \fi}
  11213. {\if\edition\pythonEd\pythonColor
  11214. \begin{lstlisting}
  11215. t = 40, True, (2,)
  11216. print(t[0] + t[2][0] if t[1] else 44)
  11217. \end{lstlisting}
  11218. \fi}
  11219. \newcommand{\LtupGrammarRacket}{
  11220. \begin{array}{lcl}
  11221. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11222. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11223. \MID \LP\key{vector-length}\;\Exp\RP \\
  11224. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11225. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11226. \end{array}
  11227. }
  11228. \newcommand{\LtupASTRacket}{
  11229. \begin{array}{lcl}
  11230. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11231. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11232. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11233. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11234. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11235. \end{array}
  11236. }
  11237. \newcommand{\LtupGrammarPython}{
  11238. \begin{array}{rcl}
  11239. \itm{cmp} &::= & \key{is} \\
  11240. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11241. \end{array}
  11242. }
  11243. \newcommand{\LtupASTPython}{
  11244. \begin{array}{lcl}
  11245. \itm{cmp} &::= & \code{Is()} \\
  11246. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11247. &\MID& \LEN{\Exp}
  11248. \end{array}
  11249. }
  11250. \begin{figure}[tbp]
  11251. \centering
  11252. \begin{tcolorbox}[colback=white]
  11253. \small
  11254. {\if\edition\racketEd
  11255. \[
  11256. \begin{array}{l}
  11257. \gray{\LintGrammarRacket{}} \\ \hline
  11258. \gray{\LvarGrammarRacket{}} \\ \hline
  11259. \gray{\LifGrammarRacket{}} \\ \hline
  11260. \gray{\LwhileGrammarRacket} \\ \hline
  11261. \LtupGrammarRacket \\
  11262. \begin{array}{lcl}
  11263. \LangVecM{} &::=& \Exp
  11264. \end{array}
  11265. \end{array}
  11266. \]
  11267. \fi}
  11268. {\if\edition\pythonEd\pythonColor
  11269. \[
  11270. \begin{array}{l}
  11271. \gray{\LintGrammarPython{}} \\ \hline
  11272. \gray{\LvarGrammarPython{}} \\ \hline
  11273. \gray{\LifGrammarPython{}} \\ \hline
  11274. \gray{\LwhileGrammarPython} \\ \hline
  11275. \LtupGrammarPython \\
  11276. \begin{array}{rcl}
  11277. \LangVecM{} &::=& \Stmt^{*}
  11278. \end{array}
  11279. \end{array}
  11280. \]
  11281. \fi}
  11282. \end{tcolorbox}
  11283. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11284. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11285. \label{fig:Lvec-concrete-syntax}
  11286. \end{figure}
  11287. \begin{figure}[tp]
  11288. \centering
  11289. \begin{tcolorbox}[colback=white]
  11290. \small
  11291. {\if\edition\racketEd
  11292. \[
  11293. \begin{array}{l}
  11294. \gray{\LintOpAST} \\ \hline
  11295. \gray{\LvarASTRacket{}} \\ \hline
  11296. \gray{\LifASTRacket{}} \\ \hline
  11297. \gray{\LwhileASTRacket{}} \\ \hline
  11298. \LtupASTRacket{} \\
  11299. \begin{array}{lcl}
  11300. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11301. \end{array}
  11302. \end{array}
  11303. \]
  11304. \fi}
  11305. {\if\edition\pythonEd\pythonColor
  11306. \[
  11307. \begin{array}{l}
  11308. \gray{\LintASTPython} \\ \hline
  11309. \gray{\LvarASTPython} \\ \hline
  11310. \gray{\LifASTPython} \\ \hline
  11311. \gray{\LwhileASTPython} \\ \hline
  11312. \LtupASTPython \\
  11313. \begin{array}{lcl}
  11314. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11315. \end{array}
  11316. \end{array}
  11317. \]
  11318. \fi}
  11319. \end{tcolorbox}
  11320. \caption{The abstract syntax of \LangVec{}.}
  11321. \label{fig:Lvec-syntax}
  11322. \end{figure}
  11323. Tuples raise several interesting new issues. First, variable binding
  11324. performs a shallow copy in dealing with tuples, which means that
  11325. different variables can refer to the same tuple; that is, two
  11326. variables can be \emph{aliases}\index{subject}{alias} for the same
  11327. entity. Consider the following example, in which \code{t1} and
  11328. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11329. different tuple value with equal elements. The result of the
  11330. program is \code{42}.
  11331. \begin{center}
  11332. \begin{minipage}{0.96\textwidth}
  11333. {\if\edition\racketEd
  11334. \begin{lstlisting}
  11335. (let ([t1 (vector 3 7)])
  11336. (let ([t2 t1])
  11337. (let ([t3 (vector 3 7)])
  11338. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11339. 42
  11340. 0))))
  11341. \end{lstlisting}
  11342. \fi}
  11343. {\if\edition\pythonEd\pythonColor
  11344. \begin{lstlisting}
  11345. t1 = 3, 7
  11346. t2 = t1
  11347. t3 = 3, 7
  11348. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11349. \end{lstlisting}
  11350. \fi}
  11351. \end{minipage}
  11352. \end{center}
  11353. {\if\edition\racketEd
  11354. Whether two variables are aliased or not affects what happens
  11355. when the underlying tuple is mutated\index{subject}{mutation}.
  11356. Consider the following example in which \code{t1} and \code{t2}
  11357. again refer to the same tuple value.
  11358. \begin{center}
  11359. \begin{minipage}{0.96\textwidth}
  11360. \begin{lstlisting}
  11361. (let ([t1 (vector 3 7)])
  11362. (let ([t2 t1])
  11363. (let ([_ (vector-set! t2 0 42)])
  11364. (vector-ref t1 0))))
  11365. \end{lstlisting}
  11366. \end{minipage}
  11367. \end{center}
  11368. The mutation through \code{t2} is visible in referencing the tuple
  11369. from \code{t1}, so the result of this program is \code{42}.
  11370. \fi}
  11371. The next issue concerns the lifetime of tuples. When does a tuple's
  11372. lifetime end? Notice that \LangVec{} does not include an operation
  11373. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11374. to any notion of static scoping.
  11375. %
  11376. {\if\edition\racketEd
  11377. %
  11378. For example, the following program returns \code{42} even though the
  11379. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11380. that reads from the vector to which it was bound.
  11381. \begin{center}
  11382. \begin{minipage}{0.96\textwidth}
  11383. \begin{lstlisting}
  11384. (let ([v (vector (vector 44))])
  11385. (let ([x (let ([w (vector 42)])
  11386. (let ([_ (vector-set! v 0 w)])
  11387. 0))])
  11388. (+ x (vector-ref (vector-ref v 0) 0))))
  11389. \end{lstlisting}
  11390. \end{minipage}
  11391. \end{center}
  11392. \fi}
  11393. %
  11394. {\if\edition\pythonEd\pythonColor
  11395. %
  11396. For example, the following program returns \code{42} even though the
  11397. variable \code{x} goes out of scope when the function returns, prior
  11398. to reading the tuple element at index $0$. (We study the compilation
  11399. of functions in chapter~\ref{ch:Lfun}.)
  11400. %
  11401. \begin{center}
  11402. \begin{minipage}{0.96\textwidth}
  11403. \begin{lstlisting}
  11404. def f():
  11405. x = 42, 43
  11406. return x
  11407. t = f()
  11408. print(t[0])
  11409. \end{lstlisting}
  11410. \end{minipage}
  11411. \end{center}
  11412. \fi}
  11413. %
  11414. From the perspective of programmer-observable behavior, tuples live
  11415. forever. However, if they really lived forever then many long-running
  11416. programs would run out of memory. To solve this problem, the
  11417. language's runtime system performs automatic garbage collection.
  11418. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11419. \LangVec{} language.
  11420. %
  11421. \racket{We define the \code{vector}, \code{vector-ref},
  11422. \code{vector-set!}, and \code{vector-length} operations for
  11423. \LangVec{} in terms of the corresponding operations in Racket. One
  11424. subtle point is that the \code{vector-set!} operation returns the
  11425. \code{\#<void>} value.}
  11426. %
  11427. \python{We represent tuples with Python lists in the interpreter
  11428. because we need to write to them
  11429. (section~\ref{sec:expose-allocation}). (Python tuples are
  11430. immutable.) We define element access, the \code{is} operator, and
  11431. the \code{len} operator for \LangVec{} in terms of the corresponding
  11432. operations in Python.}
  11433. \begin{figure}[tbp]
  11434. \begin{tcolorbox}[colback=white]
  11435. {\if\edition\racketEd
  11436. \begin{lstlisting}
  11437. (define interp-Lvec-class
  11438. (class interp-Lwhile-class
  11439. (super-new)
  11440. (define/override (interp-op op)
  11441. (match op
  11442. ['eq? (lambda (v1 v2)
  11443. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11444. (and (boolean? v1) (boolean? v2))
  11445. (and (vector? v1) (vector? v2))
  11446. (and (void? v1) (void? v2)))
  11447. (eq? v1 v2)]))]
  11448. ['vector vector]
  11449. ['vector-length vector-length]
  11450. ['vector-ref vector-ref]
  11451. ['vector-set! vector-set!]
  11452. [else (super interp-op op)]
  11453. ))
  11454. (define/override ((interp-exp env) e)
  11455. (match e
  11456. [(HasType e t) ((interp-exp env) e)]
  11457. [else ((super interp-exp env) e)]
  11458. ))
  11459. ))
  11460. (define (interp-Lvec p)
  11461. (send (new interp-Lvec-class) interp-program p))
  11462. \end{lstlisting}
  11463. \fi}
  11464. %
  11465. {\if\edition\pythonEd\pythonColor
  11466. \begin{lstlisting}
  11467. class InterpLtup(InterpLwhile):
  11468. def interp_cmp(self, cmp):
  11469. match cmp:
  11470. case Is():
  11471. return lambda x, y: x is y
  11472. case _:
  11473. return super().interp_cmp(cmp)
  11474. def interp_exp(self, e, env):
  11475. match e:
  11476. case Tuple(es, Load()):
  11477. return tuple([self.interp_exp(e, env) for e in es])
  11478. case Subscript(tup, index, Load()):
  11479. t = self.interp_exp(tup, env)
  11480. n = self.interp_exp(index, env)
  11481. return t[n]
  11482. case _:
  11483. return super().interp_exp(e, env)
  11484. \end{lstlisting}
  11485. \fi}
  11486. \end{tcolorbox}
  11487. \caption{Interpreter for the \LangVec{} language.}
  11488. \label{fig:interp-Lvec}
  11489. \end{figure}
  11490. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11491. \LangVec{}.
  11492. %
  11493. The type of a tuple is a
  11494. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11495. type for each of its elements.
  11496. %
  11497. \racket{To create the s-expression for the \code{Vector} type, we use the
  11498. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11499. operator} \code{,@} to insert the list \code{t*} without its usual
  11500. start and end parentheses. \index{subject}{unquote-splicing}}
  11501. %
  11502. The type of accessing the ith element of a tuple is the ith element
  11503. type of the tuple's type, if there is one. If not, an error is
  11504. signaled. Note that the index \code{i} is required to be a constant
  11505. integer (and not, for example, a call to
  11506. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11507. can determine the element's type given the tuple type.
  11508. %
  11509. \racket{
  11510. Regarding writing an element to a tuple, the element's type must
  11511. be equal to the ith element type of the tuple's type.
  11512. The result type is \code{Void}.}
  11513. %% When allocating a tuple,
  11514. %% we need to know which elements of the tuple are themselves tuples for
  11515. %% the purposes of garbage collection. We can obtain this information
  11516. %% during type checking. The type checker shown in
  11517. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11518. %% expression; it also
  11519. %% %
  11520. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11521. %% where $T$ is the tuple's type.
  11522. %
  11523. %records the type of each tuple expression in a new field named \code{has\_type}.
  11524. \begin{figure}[tp]
  11525. \begin{tcolorbox}[colback=white]
  11526. {\if\edition\racketEd
  11527. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11528. (define type-check-Lvec-class
  11529. (class type-check-Lif-class
  11530. (super-new)
  11531. (inherit check-type-equal?)
  11532. (define/override (type-check-exp env)
  11533. (lambda (e)
  11534. (define recur (type-check-exp env))
  11535. (match e
  11536. [(Prim 'vector es)
  11537. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11538. (define t `(Vector ,@t*))
  11539. (values (Prim 'vector e*) t)]
  11540. [(Prim 'vector-ref (list e1 (Int i)))
  11541. (define-values (e1^ t) (recur e1))
  11542. (match t
  11543. [`(Vector ,ts ...)
  11544. (unless (and (0 . <= . i) (i . < . (length ts)))
  11545. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11546. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11547. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11548. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11549. (define-values (e-vec t-vec) (recur e1))
  11550. (define-values (e-elt^ t-elt) (recur elt))
  11551. (match t-vec
  11552. [`(Vector ,ts ...)
  11553. (unless (and (0 . <= . i) (i . < . (length ts)))
  11554. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11555. (check-type-equal? (list-ref ts i) t-elt e)
  11556. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11557. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11558. [(Prim 'vector-length (list e))
  11559. (define-values (e^ t) (recur e))
  11560. (match t
  11561. [`(Vector ,ts ...)
  11562. (values (Prim 'vector-length (list e^)) 'Integer)]
  11563. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11564. [(Prim 'eq? (list arg1 arg2))
  11565. (define-values (e1 t1) (recur arg1))
  11566. (define-values (e2 t2) (recur arg2))
  11567. (match* (t1 t2)
  11568. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11569. [(other wise) (check-type-equal? t1 t2 e)])
  11570. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11571. [else ((super type-check-exp env) e)]
  11572. )))
  11573. ))
  11574. (define (type-check-Lvec p)
  11575. (send (new type-check-Lvec-class) type-check-program p))
  11576. \end{lstlisting}
  11577. \fi}
  11578. {\if\edition\pythonEd\pythonColor
  11579. \begin{lstlisting}
  11580. class TypeCheckLtup(TypeCheckLwhile):
  11581. def type_check_exp(self, e, env):
  11582. match e:
  11583. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11584. l = self.type_check_exp(left, env)
  11585. r = self.type_check_exp(right, env)
  11586. check_type_equal(l, r, e)
  11587. return bool
  11588. case Tuple(es, Load()):
  11589. ts = [self.type_check_exp(e, env) for e in es]
  11590. e.has_type = TupleType(ts)
  11591. return e.has_type
  11592. case Subscript(tup, Constant(i), Load()):
  11593. tup_ty = self.type_check_exp(tup, env)
  11594. i_ty = self.type_check_exp(Constant(i), env)
  11595. check_type_equal(i_ty, int, i)
  11596. match tup_ty:
  11597. case TupleType(ts):
  11598. return ts[i]
  11599. case _:
  11600. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11601. case _:
  11602. return super().type_check_exp(e, env)
  11603. \end{lstlisting}
  11604. \fi}
  11605. \end{tcolorbox}
  11606. \caption{Type checker for the \LangVec{} language.}
  11607. \label{fig:type-check-Lvec}
  11608. \end{figure}
  11609. \section{Garbage Collection}
  11610. \label{sec:GC}
  11611. Garbage collection is a runtime technique for reclaiming space on the
  11612. heap that will not be used in the future of the running program. We
  11613. use the term \emph{object}\index{subject}{object} to refer to any
  11614. value that is stored in the heap, which for now includes only
  11615. tuples.%
  11616. %
  11617. \footnote{The term \emph{object} as it is used in the context of
  11618. object-oriented programming has a more specific meaning than the
  11619. way in which we use the term here.}
  11620. %
  11621. Unfortunately, it is impossible to know precisely which objects will
  11622. be accessed in the future and which will not. Instead, garbage
  11623. collectors overapproximate the set of objects that will be accessed by
  11624. identifying which objects can possibly be accessed. The running
  11625. program can directly access objects that are in registers and on the
  11626. procedure call stack. It can also transitively access the elements of
  11627. tuples, starting with a tuple whose address is in a register or on the
  11628. procedure call stack. We define the \emph{root
  11629. set}\index{subject}{root set} to be all the tuple addresses that are
  11630. in registers or on the procedure call stack. We define the \emph{live
  11631. objects}\index{subject}{live objects} to be the objects that are
  11632. reachable from the root set. Garbage collectors reclaim the space that
  11633. is allocated to objects that are no longer live. \index{subject}{allocate}
  11634. That means that some objects may not get reclaimed as soon as they could be,
  11635. but at least
  11636. garbage collectors do not reclaim the space dedicated to objects that
  11637. will be accessed in the future! The programmer can influence which
  11638. objects get reclaimed by causing them to become unreachable.
  11639. So the goal of the garbage collector is twofold:
  11640. \begin{enumerate}
  11641. \item to preserve all the live objects, and
  11642. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11643. \end{enumerate}
  11644. \subsection{Two-Space Copying Collector}
  11645. Here we study a relatively simple algorithm for garbage collection
  11646. that is the basis of many state-of-the-art garbage
  11647. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11648. particular, we describe a two-space copying
  11649. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11650. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11651. collector} \index{subject}{two-space copying collector}
  11652. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11653. what happens in a two-space collector, showing two time steps, prior
  11654. to garbage collection (on the top) and after garbage collection (on
  11655. the bottom). In a two-space collector, the heap is divided into two
  11656. parts named the FromSpace\index{subject}{FromSpace} and the
  11657. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11658. FromSpace until there is not enough room for the next allocation
  11659. request. At that point, the garbage collector goes to work to make
  11660. room for the next allocation.
  11661. A copying collector makes more room by copying all the live objects
  11662. from the FromSpace into the ToSpace and then performs a sleight of
  11663. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11664. as the new ToSpace. In the example shown in
  11665. figure~\ref{fig:copying-collector}, the root set consists of three
  11666. pointers, one in a register and two on the stack. All the live
  11667. objects have been copied to the ToSpace (the right-hand side of
  11668. figure~\ref{fig:copying-collector}) in a way that preserves the
  11669. pointer relationships. For example, the pointer in the register still
  11670. points to a tuple that in turn points to two other tuples. There are
  11671. four tuples that are not reachable from the root set and therefore do
  11672. not get copied into the ToSpace.
  11673. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11674. created by a well-typed program in \LangVec{} because it contains a
  11675. cycle. However, creating cycles will be possible once we get to
  11676. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11677. to deal with cycles to begin with, so we will not need to revisit this
  11678. issue.
  11679. \begin{figure}[tbp]
  11680. \centering
  11681. \begin{tcolorbox}[colback=white]
  11682. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11683. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11684. \\[5ex]
  11685. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11686. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11687. \end{tcolorbox}
  11688. \caption{A copying collector in action.}
  11689. \label{fig:copying-collector}
  11690. \end{figure}
  11691. \subsection{Graph Copying via Cheney's Algorithm}
  11692. \label{sec:cheney}
  11693. \index{subject}{Cheney's algorithm}
  11694. Let us take a closer look at the copying of the live objects. The
  11695. allocated\index{subject}{allocate} objects and pointers can be viewed
  11696. as a graph, and we need to copy the part of the graph that is
  11697. reachable from the root set. To make sure that we copy all the
  11698. reachable vertices in the graph, we need an exhaustive graph traversal
  11699. algorithm, such as depth-first search or breadth-first
  11700. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11701. take into account the possibility of cycles by marking which vertices
  11702. have already been visited, so to ensure termination of the
  11703. algorithm. These search algorithms also use a data structure such as a
  11704. stack or queue as a to-do list to keep track of the vertices that need
  11705. to be visited. We use breadth-first search and a trick due to
  11706. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11707. copying tuples into the ToSpace.
  11708. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11709. copy progresses. The queue is represented by a chunk of contiguous
  11710. memory at the beginning of the ToSpace, using two pointers to track
  11711. the front and the back of the queue, called the \emph{free pointer}
  11712. and the \emph{scan pointer}, respectively. The algorithm starts by
  11713. copying all tuples that are immediately reachable from the root set
  11714. into the ToSpace to form the initial queue. When we copy a tuple, we
  11715. mark the old tuple to indicate that it has been visited. We discuss
  11716. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11717. that any pointers inside the copied tuples in the queue still point
  11718. back to the FromSpace. Once the initial queue has been created, the
  11719. algorithm enters a loop in which it repeatedly processes the tuple at
  11720. the front of the queue and pops it off the queue. To process a tuple,
  11721. the algorithm copies all the objects that are directly reachable from it
  11722. to the ToSpace, placing them at the back of the queue. The algorithm
  11723. then updates the pointers in the popped tuple so that they point to the
  11724. newly copied objects.
  11725. \begin{figure}[tbp]
  11726. \centering
  11727. \begin{tcolorbox}[colback=white]
  11728. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11729. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11730. \end{tcolorbox}
  11731. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11732. \label{fig:cheney}
  11733. \end{figure}
  11734. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11735. tuple whose second element is $42$ to the back of the queue. The other
  11736. pointer goes to a tuple that has already been copied, so we do not
  11737. need to copy it again, but we do need to update the pointer to the new
  11738. location. This can be accomplished by storing a \emph{forwarding
  11739. pointer}\index{subject}{forwarding pointer} to the new location in the
  11740. old tuple, when we initially copied the tuple into the
  11741. ToSpace. This completes one step of the algorithm. The algorithm
  11742. continues in this way until the queue is empty; that is, when the scan
  11743. pointer catches up with the free pointer.
  11744. \subsection{Data Representation}
  11745. \label{sec:data-rep-gc}
  11746. The garbage collector places some requirements on the data
  11747. representations used by our compiler. First, the garbage collector
  11748. needs to distinguish between pointers and other kinds of data such as
  11749. integers. The following are three ways to accomplish this:
  11750. \begin{enumerate}
  11751. \item Attach a tag to each object that identifies what type of
  11752. object it is~\citep{McCarthy:1960dz}.
  11753. \item Store different types of objects in different
  11754. regions~\citep{Steele:1977ab}.
  11755. \item Use type information from the program to either (a) generate
  11756. type-specific code for collecting, or (b) generate tables that
  11757. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11758. \end{enumerate}
  11759. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11760. need to tag objects in any case, so option 1 is a natural choice for those
  11761. languages. However, \LangVec{} is a statically typed language, so it
  11762. would be unfortunate to require tags on every object, especially small
  11763. and pervasive objects like integers and Booleans. Option 3 is the
  11764. best-performing choice for statically typed languages, but it comes with
  11765. a relatively high implementation complexity. To keep this chapter
  11766. within a reasonable scope of complexity, we recommend a combination of options
  11767. 1 and 2, using separate strategies for the stack and the heap.
  11768. Regarding the stack, we recommend using a separate stack for pointers,
  11769. which we call the \emph{root stack}\index{subject}{root stack}
  11770. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11771. That is, when a local variable needs to be spilled and is of type
  11772. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11773. root stack instead of putting it on the procedure call
  11774. stack. Furthermore, we always spill tuple-typed variables if they are
  11775. live during a call to the collector, thereby ensuring that no pointers
  11776. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11777. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11778. contrasts it with the data layout using a root stack. The root stack
  11779. contains the two pointers from the regular stack and also the pointer
  11780. in the second register.
  11781. \begin{figure}[tbp]
  11782. \centering
  11783. \begin{tcolorbox}[colback=white]
  11784. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11785. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11786. \end{tcolorbox}
  11787. \caption{Maintaining a root stack to facilitate garbage collection.}
  11788. \label{fig:shadow-stack}
  11789. \end{figure}
  11790. The problem of distinguishing between pointers and other kinds of data
  11791. also arises inside each tuple on the heap. We solve this problem by
  11792. attaching a tag, an extra 64 bits, to each
  11793. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11794. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11795. Note that we have drawn the bits in a big-endian way, from right to left,
  11796. with bit location 0 (the least significant bit) on the far right,
  11797. which corresponds to the direction of the x86 shifting instructions
  11798. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11799. is dedicated to specifying which elements of the tuple are pointers,
  11800. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11801. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11802. data. The pointer mask starts at bit location 7. We limit tuples to a
  11803. maximum size of fifty elements, so we need 50 bits for the pointer
  11804. mask.%
  11805. %
  11806. \footnote{A production-quality compiler would handle
  11807. arbitrarily sized tuples and use a more complex approach.}
  11808. %
  11809. The tag also contains two other pieces of information. The length of
  11810. the tuple (number of elements) is stored in bits at locations 1 through
  11811. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11812. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11813. has not yet been copied. If the bit has value 0, then the entire tag
  11814. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11815. zero in any case, because our tuples are 8-byte aligned.)
  11816. \begin{figure}[tbp]
  11817. \centering
  11818. \begin{tcolorbox}[colback=white]
  11819. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11820. \end{tcolorbox}
  11821. \caption{Representation of tuples in the heap.}
  11822. \label{fig:tuple-rep}
  11823. \end{figure}
  11824. \subsection{Implementation of the Garbage Collector}
  11825. \label{sec:organize-gz}
  11826. \index{subject}{prelude}
  11827. An implementation of the copying collector is provided in the
  11828. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11829. interface to the garbage collector that is used by the compiler. The
  11830. \code{initialize} function creates the FromSpace, ToSpace, and root
  11831. stack and should be called in the prelude of the \code{main}
  11832. function. The arguments of \code{initialize} are the root stack size
  11833. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11834. good choice for both. The \code{initialize} function puts the address
  11835. of the beginning of the FromSpace into the global variable
  11836. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11837. the address that is one past the last element of the FromSpace. We use
  11838. half-open intervals to represent chunks of
  11839. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11840. points to the first element of the root stack.
  11841. As long as there is room left in the FromSpace, your generated code
  11842. can allocate\index{subject}{allocate} tuples simply by moving the
  11843. \code{free\_ptr} forward.
  11844. %
  11845. The amount of room left in the FromSpace is the difference between the
  11846. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11847. function should be called when there is not enough room left in the
  11848. FromSpace for the next allocation. The \code{collect} function takes
  11849. a pointer to the current top of the root stack (one past the last item
  11850. that was pushed) and the number of bytes that need to be
  11851. allocated. The \code{collect} function performs the copying collection
  11852. and leaves the heap in a state such that there is enough room for the
  11853. next allocation.
  11854. \begin{figure}[tbp]
  11855. \begin{tcolorbox}[colback=white]
  11856. \begin{lstlisting}
  11857. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11858. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11859. int64_t* free_ptr;
  11860. int64_t* fromspace_begin;
  11861. int64_t* fromspace_end;
  11862. int64_t** rootstack_begin;
  11863. \end{lstlisting}
  11864. \end{tcolorbox}
  11865. \caption{The compiler's interface to the garbage collector.}
  11866. \label{fig:gc-header}
  11867. \end{figure}
  11868. %% \begin{exercise}
  11869. %% In the file \code{runtime.c} you will find the implementation of
  11870. %% \code{initialize} and a partial implementation of \code{collect}.
  11871. %% The \code{collect} function calls another function, \code{cheney},
  11872. %% to perform the actual copy, and that function is left to the reader
  11873. %% to implement. The following is the prototype for \code{cheney}.
  11874. %% \begin{lstlisting}
  11875. %% static void cheney(int64_t** rootstack_ptr);
  11876. %% \end{lstlisting}
  11877. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11878. %% rootstack (which is an array of pointers). The \code{cheney} function
  11879. %% also communicates with \code{collect} through the global
  11880. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11881. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11882. %% the ToSpace:
  11883. %% \begin{lstlisting}
  11884. %% static int64_t* tospace_begin;
  11885. %% static int64_t* tospace_end;
  11886. %% \end{lstlisting}
  11887. %% The job of the \code{cheney} function is to copy all the live
  11888. %% objects (reachable from the root stack) into the ToSpace, update
  11889. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11890. %% update the root stack so that it points to the objects in the
  11891. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11892. %% and ToSpace.
  11893. %% \end{exercise}
  11894. The introduction of garbage collection has a nontrivial impact on our
  11895. compiler passes. We introduce a new compiler pass named
  11896. \code{expose\_allocation} that elaborates the code for allocating
  11897. tuples. We also make significant changes to
  11898. \code{select\_instructions}, \code{build\_interference},
  11899. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11900. make minor changes in several more passes.
  11901. The following program serves as our running example. It creates
  11902. two tuples, one nested inside the other. Both tuples have length
  11903. one. The program accesses the element in the inner tuple.
  11904. % tests/vectors_test_17.rkt
  11905. {\if\edition\racketEd
  11906. \begin{lstlisting}
  11907. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11908. \end{lstlisting}
  11909. \fi}
  11910. % tests/tuple/get_get.py
  11911. {\if\edition\pythonEd\pythonColor
  11912. \begin{lstlisting}
  11913. v1 = (42,)
  11914. v2 = (v1,)
  11915. print(v2[0][0])
  11916. \end{lstlisting}
  11917. \fi}
  11918. %% {\if\edition\racketEd
  11919. %% \section{Shrink}
  11920. %% \label{sec:shrink-Lvec}
  11921. %% Recall that the \code{shrink} pass translates the primitives operators
  11922. %% into a smaller set of primitives.
  11923. %% %
  11924. %% This pass comes after type checking, and the type checker adds a
  11925. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11926. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11927. %% \fi}
  11928. \section{Expose Allocation}
  11929. \label{sec:expose-allocation}
  11930. The pass \code{expose\_allocation} lowers tuple creation into making a
  11931. conditional call to the collector followed by allocating the
  11932. appropriate amount of memory and initializing it. We choose to place
  11933. the \code{expose\_allocation} pass before
  11934. \code{remove\_complex\_operands} because it generates code that
  11935. contains complex operands. However, with some care it can also be
  11936. placed before \code{remove\_complex\_operands} which would simplify
  11937. tuple creation by removing the need to assign the initializing
  11938. expressions to temporary variables (see below).
  11939. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11940. that replaces tuple creation with new lower-level forms that we use in the
  11941. translation of tuple creation.
  11942. %
  11943. {\if\edition\racketEd
  11944. \[
  11945. \begin{array}{lcl}
  11946. \Exp &::=& (\key{collect} \,\itm{int})
  11947. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11948. \MID (\key{global-value} \,\itm{name})
  11949. \end{array}
  11950. \]
  11951. \fi}
  11952. {\if\edition\pythonEd\pythonColor
  11953. \[
  11954. \begin{array}{lcl}
  11955. \Exp &::=& \key{collect}(\itm{int})
  11956. \MID \key{allocate}(\itm{int},\itm{type})
  11957. \MID \key{global\_value}(\itm{name}) \\
  11958. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11959. \end{array}
  11960. \]
  11961. \fi}
  11962. %
  11963. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  11964. there be $n$ bytes ready to be allocated. During instruction
  11965. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  11966. form will become a call to the \code{collect} function in
  11967. \code{runtime.c}.
  11968. %
  11969. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11970. space at the front for the 64-bit tag), but the elements are not
  11971. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11972. of the tuple:
  11973. %
  11974. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11975. %
  11976. where $\Type_i$ is the type of the $i$th element.
  11977. %
  11978. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11979. variable, such as \code{free\_ptr}.
  11980. \racket{
  11981. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11982. can be obtained by running the
  11983. \code{type-check-Lvec-has-type} type checker immediately before the
  11984. \code{expose\_allocation} pass. This version of the type checker
  11985. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11986. around each tuple creation. The concrete syntax
  11987. for \code{HasType} is \code{has-type}.}
  11988. The following shows the transformation of tuple creation into (1) a
  11989. sequence of temporary variable bindings for the initializing
  11990. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11991. \code{allocate}, and (4) the initialization of the tuple. The
  11992. \itm{len} placeholder refers to the length of the tuple, and
  11993. \itm{bytes} is the total number of bytes that need to be allocated for
  11994. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11995. %
  11996. \python{The \itm{type} needed for the second argument of the
  11997. \code{allocate} form can be obtained from the \code{has\_type} field
  11998. of the tuple AST node, which is stored there by running the type
  11999. checker for \LangVec{} immediately before this pass.}
  12000. %
  12001. \begin{center}
  12002. \begin{minipage}{\textwidth}
  12003. {\if\edition\racketEd
  12004. \begin{lstlisting}
  12005. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12006. |$\Longrightarrow$|
  12007. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12008. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12009. (global-value fromspace_end))
  12010. (void)
  12011. (collect |\itm{bytes}|))])
  12012. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12013. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12014. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12015. |$v$|) ... )))) ...)
  12016. \end{lstlisting}
  12017. \fi}
  12018. {\if\edition\pythonEd\pythonColor
  12019. \begin{lstlisting}
  12020. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12021. |$\Longrightarrow$|
  12022. begin:
  12023. |$x_0$| = |$e_0$|
  12024. |$\vdots$|
  12025. |$x_{n-1}$| = |$e_{n-1}$|
  12026. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12027. 0
  12028. else:
  12029. collect(|\itm{bytes}|)
  12030. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12031. |$v$|[0] = |$x_0$|
  12032. |$\vdots$|
  12033. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12034. |$v$|
  12035. \end{lstlisting}
  12036. \fi}
  12037. \end{minipage}
  12038. \end{center}
  12039. %
  12040. \noindent The sequencing of the initializing expressions
  12041. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12042. they may trigger garbage collection and we cannot have an allocated
  12043. but uninitialized tuple on the heap during a collection.
  12044. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12045. \code{expose\_allocation} pass on our running example.
  12046. \begin{figure}[tbp]
  12047. \begin{tcolorbox}[colback=white]
  12048. % tests/s2_17.rkt
  12049. {\if\edition\racketEd
  12050. \begin{lstlisting}
  12051. (vector-ref
  12052. (vector-ref
  12053. (let ([vecinit6
  12054. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12055. (global-value fromspace_end))
  12056. (void)
  12057. (collect 16))])
  12058. (let ([alloc2 (allocate 1 (Vector Integer))])
  12059. (let ([_3 (vector-set! alloc2 0 42)])
  12060. alloc2)))])
  12061. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12062. (global-value fromspace_end))
  12063. (void)
  12064. (collect 16))])
  12065. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12066. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12067. alloc5))))
  12068. 0)
  12069. 0)
  12070. \end{lstlisting}
  12071. \fi}
  12072. {\if\edition\pythonEd\pythonColor
  12073. \begin{lstlisting}
  12074. v1 = begin:
  12075. init.514 = 42
  12076. if (free_ptr + 16) < fromspace_end:
  12077. else:
  12078. collect(16)
  12079. alloc.513 = allocate(1,tuple[int])
  12080. alloc.513[0] = init.514
  12081. alloc.513
  12082. v2 = begin:
  12083. init.516 = v1
  12084. if (free_ptr + 16) < fromspace_end:
  12085. else:
  12086. collect(16)
  12087. alloc.515 = allocate(1,tuple[tuple[int]])
  12088. alloc.515[0] = init.516
  12089. alloc.515
  12090. print(v2[0][0])
  12091. \end{lstlisting}
  12092. \fi}
  12093. \end{tcolorbox}
  12094. \caption{Output of the \code{expose\_allocation} pass.}
  12095. \label{fig:expose-alloc-output}
  12096. \end{figure}
  12097. \section{Remove Complex Operands}
  12098. \label{sec:remove-complex-opera-Lvec}
  12099. {\if\edition\racketEd
  12100. %
  12101. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12102. should be treated as complex operands.
  12103. %
  12104. \fi}
  12105. %
  12106. {\if\edition\pythonEd\pythonColor
  12107. %
  12108. The expressions \code{allocate}, \code{begin},
  12109. and tuple access should be treated as complex operands. The
  12110. subexpressions of tuple access must be atomic.
  12111. The \code{global\_value} AST node is atomic.
  12112. %
  12113. \fi}
  12114. %% A new case for
  12115. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12116. %% handled carefully to prevent the \code{Prim} node from being separated
  12117. %% from its enclosing \code{HasType}.
  12118. Figure~\ref{fig:Lvec-anf-syntax}
  12119. shows the grammar for the output language \LangAllocANF{} of this
  12120. pass, which is \LangAlloc{} in monadic normal form.
  12121. \newcommand{\LtupMonadASTRacket}{
  12122. \begin{array}{rcl}
  12123. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12124. \MID \GLOBALVALUE{\Var}
  12125. \end{array}
  12126. }
  12127. \newcommand{\LtupMonadASTPython}{
  12128. \begin{array}{rcl}
  12129. \Atm &::=& \GLOBALVALUE{\Var} \\
  12130. \Exp &::=& \GET{\Atm}{\Atm}
  12131. \MID \LEN{\Atm}\\
  12132. &\MID& \ALLOCATE{\Int}{\Type}\\
  12133. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12134. &\MID& \COLLECT{\Int}
  12135. \end{array}
  12136. }
  12137. \begin{figure}[tp]
  12138. \centering
  12139. \begin{tcolorbox}[colback=white]
  12140. \small
  12141. {\if\edition\racketEd
  12142. \[
  12143. \begin{array}{l}
  12144. \gray{\LvarMonadASTRacket} \\ \hline
  12145. \gray{\LifMonadASTRacket} \\ \hline
  12146. \gray{\LwhileMonadASTRacket} \\ \hline
  12147. \LtupMonadASTRacket \\
  12148. \begin{array}{rcl}
  12149. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12150. \end{array}
  12151. \end{array}
  12152. \]
  12153. \fi}
  12154. {\if\edition\pythonEd\pythonColor
  12155. \[
  12156. \begin{array}{l}
  12157. \gray{\LvarMonadASTPython} \\ \hline
  12158. \gray{\LifMonadASTPython} \\ \hline
  12159. \gray{\LwhileMonadASTPython} \\ \hline
  12160. \LtupMonadASTPython \\
  12161. \begin{array}{rcl}
  12162. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12163. \end{array}
  12164. \end{array}
  12165. \]
  12166. \fi}
  12167. \end{tcolorbox}
  12168. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12169. \label{fig:Lvec-anf-syntax}
  12170. \end{figure}
  12171. \section{Explicate Control and the \LangCVec{} Language}
  12172. \label{sec:explicate-control-r3}
  12173. \newcommand{\CtupASTRacket}{
  12174. \begin{array}{lcl}
  12175. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12176. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12177. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12178. &\MID& \VECLEN{\Atm} \\
  12179. &\MID& \GLOBALVALUE{\Var} \\
  12180. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12181. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12182. \end{array}
  12183. }
  12184. \newcommand{\CtupASTPython}{
  12185. \begin{array}{lcl}
  12186. \Atm &::=& \GLOBALVALUE{\Var} \\
  12187. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12188. &\MID& \LEN{\Atm} \\
  12189. \Stmt &::=& \COLLECT{\Int}
  12190. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12191. \end{array}
  12192. }
  12193. \begin{figure}[tp]
  12194. \begin{tcolorbox}[colback=white]
  12195. \small
  12196. {\if\edition\racketEd
  12197. \[
  12198. \begin{array}{l}
  12199. \gray{\CvarASTRacket} \\ \hline
  12200. \gray{\CifASTRacket} \\ \hline
  12201. \gray{\CloopASTRacket} \\ \hline
  12202. \CtupASTRacket \\
  12203. \begin{array}{lcl}
  12204. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12205. \end{array}
  12206. \end{array}
  12207. \]
  12208. \fi}
  12209. {\if\edition\pythonEd\pythonColor
  12210. \[
  12211. \begin{array}{l}
  12212. \gray{\CifASTPython} \\ \hline
  12213. \CtupASTPython \\
  12214. \begin{array}{lcl}
  12215. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12216. \end{array}
  12217. \end{array}
  12218. \]
  12219. \fi}
  12220. \end{tcolorbox}
  12221. \caption{The abstract syntax of \LangCVec{}, extending
  12222. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12223. (figure~\ref{fig:c1-syntax})}.}
  12224. \label{fig:c2-syntax}
  12225. \end{figure}
  12226. The output of \code{explicate\_control} is a program in the
  12227. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12228. shows the definition of the abstract syntax.
  12229. %
  12230. %% \racket{(The concrete syntax is defined in
  12231. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12232. %
  12233. The new expressions of \LangCVec{} include \key{allocate},
  12234. %
  12235. \racket{\key{vector-ref}, and \key{vector-set!},}
  12236. %
  12237. \python{accessing tuple elements,}
  12238. %
  12239. and \key{global\_value}.
  12240. %
  12241. \python{\LangCVec{} also includes the \code{collect} statement and
  12242. assignment to a tuple element.}
  12243. %
  12244. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12245. %
  12246. The \code{explicate\_control} pass can treat these new forms much like
  12247. the other forms that we've already encountered. The output of the
  12248. \code{explicate\_control} pass on the running example is shown on the
  12249. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12250. section.
  12251. \section{Select Instructions and the \LangXGlobal{} Language}
  12252. \label{sec:select-instructions-gc}
  12253. \index{subject}{select instructions}
  12254. %% void (rep as zero)
  12255. %% allocate
  12256. %% collect (callq collect)
  12257. %% vector-ref
  12258. %% vector-set!
  12259. %% vector-length
  12260. %% global (postpone)
  12261. In this pass we generate x86 code for most of the new operations that
  12262. are needed to compile tuples, including \code{Allocate},
  12263. \code{Collect}, accessing tuple elements, and the \code{Is}
  12264. comparison.
  12265. %
  12266. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12267. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12268. \ref{fig:x86-2}). \index{subject}{x86}
  12269. The tuple read and write forms translate into \code{movq}
  12270. instructions. (The $+1$ in the offset serves to move past the tag at the
  12271. beginning of the tuple representation.)
  12272. %
  12273. \begin{center}
  12274. \begin{minipage}{\textwidth}
  12275. {\if\edition\racketEd
  12276. \begin{lstlisting}
  12277. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12278. |$\Longrightarrow$|
  12279. movq |$\itm{tup}'$|, %r11
  12280. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12281. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12282. |$\Longrightarrow$|
  12283. movq |$\itm{tup}'$|, %r11
  12284. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12285. movq $0, |$\itm{lhs'}$|
  12286. \end{lstlisting}
  12287. \fi}
  12288. {\if\edition\pythonEd\pythonColor
  12289. \begin{lstlisting}
  12290. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12291. |$\Longrightarrow$|
  12292. movq |$\itm{tup}'$|, %r11
  12293. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12294. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12295. |$\Longrightarrow$|
  12296. movq |$\itm{tup}'$|, %r11
  12297. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12298. \end{lstlisting}
  12299. \fi}
  12300. \end{minipage}
  12301. \end{center}
  12302. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12303. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12304. are obtained by translating from \LangCVec{} to x86.
  12305. %
  12306. The move of $\itm{tup}'$ to
  12307. register \code{r11} ensures that the offset expression
  12308. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12309. removing \code{r11} from consideration by the register allocator.
  12310. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12311. \code{rax}. Then the generated code for tuple assignment would be
  12312. \begin{lstlisting}
  12313. movq |$\itm{tup}'$|, %rax
  12314. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12315. \end{lstlisting}
  12316. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12317. \code{patch\_instructions} would insert a move through \code{rax}
  12318. as follows:
  12319. \begin{lstlisting}
  12320. movq |$\itm{tup}'$|, %rax
  12321. movq |$\itm{rhs}'$|, %rax
  12322. movq %rax, |$8(n+1)$|(%rax)
  12323. \end{lstlisting}
  12324. However, this sequence of instructions does not work because we're
  12325. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12326. $\itm{rhs}'$) at the same time!
  12327. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12328. be translated into a sequence of instructions that read the tag of the
  12329. tuple and extract the 6 bits that represent the tuple length, which
  12330. are the bits starting at index 1 and going up to and including bit 6.
  12331. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12332. (shift right) can be used to accomplish this.
  12333. We compile the \code{allocate} form to operations on the
  12334. \code{free\_ptr}, as shown next. This approach is called
  12335. \emph{inline allocation} because it implements allocation without a
  12336. function call by simply incrementing the allocation pointer. It is much
  12337. more efficient than calling a function for each allocation. The
  12338. address in the \code{free\_ptr} is the next free address in the
  12339. FromSpace, so we copy it into \code{r11} and then move it forward by
  12340. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12341. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12342. the tag. We then initialize the \itm{tag} and finally copy the
  12343. address in \code{r11} to the left-hand side. Refer to
  12344. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12345. %
  12346. \racket{We recommend using the Racket operations
  12347. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12348. during compilation.}
  12349. %
  12350. \python{We recommend using the bitwise-or operator \code{|} and the
  12351. shift-left operator \code{<<} to compute the tag during
  12352. compilation.}
  12353. %
  12354. The type annotation in the \code{allocate} form is used to determine
  12355. the pointer mask region of the tag.
  12356. %
  12357. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12358. address of the \code{free\_ptr} global variable using a special
  12359. instruction-pointer-relative addressing mode of the x86-64 processor.
  12360. In particular, the assembler computes the distance $d$ between the
  12361. address of \code{free\_ptr} and where the \code{rip} would be at that
  12362. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12363. \code{$d$(\%rip)}, which at runtime will compute the address of
  12364. \code{free\_ptr}.
  12365. %
  12366. {\if\edition\racketEd
  12367. \begin{lstlisting}
  12368. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12369. |$\Longrightarrow$|
  12370. movq free_ptr(%rip), %r11
  12371. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12372. movq $|$\itm{tag}$|, 0(%r11)
  12373. movq %r11, |$\itm{lhs}'$|
  12374. \end{lstlisting}
  12375. \fi}
  12376. {\if\edition\pythonEd\pythonColor
  12377. \begin{lstlisting}
  12378. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12379. |$\Longrightarrow$|
  12380. movq free_ptr(%rip), %r11
  12381. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12382. movq $|$\itm{tag}$|, 0(%r11)
  12383. movq %r11, |$\itm{lhs}'$|
  12384. \end{lstlisting}
  12385. \fi}
  12386. %
  12387. The \code{collect} form is compiled to a call to the \code{collect}
  12388. function in the runtime. The arguments to \code{collect} are (1) the
  12389. top of the root stack, and (2) the number of bytes that need to be
  12390. allocated. We use another dedicated register, \code{r15}, to store
  12391. the pointer to the top of the root stack. Therefore \code{r15} is not
  12392. available for use by the register allocator.
  12393. %
  12394. {\if\edition\racketEd
  12395. \begin{lstlisting}
  12396. (collect |$\itm{bytes}$|)
  12397. |$\Longrightarrow$|
  12398. movq %r15, %rdi
  12399. movq $|\itm{bytes}|, %rsi
  12400. callq collect
  12401. \end{lstlisting}
  12402. \fi}
  12403. {\if\edition\pythonEd\pythonColor
  12404. \begin{lstlisting}
  12405. collect(|$\itm{bytes}$|)
  12406. |$\Longrightarrow$|
  12407. movq %r15, %rdi
  12408. movq $|\itm{bytes}|, %rsi
  12409. callq collect
  12410. \end{lstlisting}
  12411. \fi}
  12412. {\if\edition\pythonEd\pythonColor
  12413. The \code{is} comparison is compiled similarly to the other comparison
  12414. operators, using the \code{cmpq} instruction. Because the value of a
  12415. tuple is its address, we can translate \code{is} into a simple check
  12416. for equality using the \code{e} condition code. \\
  12417. \begin{tabular}{lll}
  12418. \begin{minipage}{0.4\textwidth}
  12419. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12420. \end{minipage}
  12421. &
  12422. $\Rightarrow$
  12423. &
  12424. \begin{minipage}{0.4\textwidth}
  12425. \begin{lstlisting}
  12426. cmpq |$\Arg_2$|, |$\Arg_1$|
  12427. sete %al
  12428. movzbq %al, |$\Var$|
  12429. \end{lstlisting}
  12430. \end{minipage}
  12431. \end{tabular}
  12432. \fi}
  12433. \newcommand{\GrammarXGlobal}{
  12434. \begin{array}{lcl}
  12435. \Arg &::=& \itm{label} \key{(\%rip)}
  12436. \end{array}
  12437. }
  12438. \newcommand{\ASTXGlobalRacket}{
  12439. \begin{array}{lcl}
  12440. \Arg &::=& \GLOBAL{\itm{label}}
  12441. \end{array}
  12442. }
  12443. \begin{figure}[tp]
  12444. \begin{tcolorbox}[colback=white]
  12445. \[
  12446. \begin{array}{l}
  12447. \gray{\GrammarXInt} \\ \hline
  12448. \gray{\GrammarXIf} \\ \hline
  12449. \GrammarXGlobal \\
  12450. \begin{array}{lcl}
  12451. \LangXGlobalM{} &::= & \key{.globl main} \\
  12452. & & \key{main:} \; \Instr^{*}
  12453. \end{array}
  12454. \end{array}
  12455. \]
  12456. \end{tcolorbox}
  12457. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12458. \label{fig:x86-2-concrete}
  12459. \end{figure}
  12460. \begin{figure}[tp]
  12461. \begin{tcolorbox}[colback=white]
  12462. \small
  12463. {\if\edition\racketEd
  12464. \[
  12465. \begin{array}{l}
  12466. \gray{\ASTXIntRacket} \\ \hline
  12467. \gray{\ASTXIfRacket} \\ \hline
  12468. \ASTXGlobalRacket \\
  12469. \begin{array}{lcl}
  12470. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12471. \end{array}
  12472. \end{array}
  12473. \]
  12474. \fi}
  12475. {\if\edition\pythonEd\pythonColor
  12476. \[
  12477. \begin{array}{l}
  12478. \gray{\ASTXIntPython} \\ \hline
  12479. \gray{\ASTXIfPython} \\ \hline
  12480. \ASTXGlobalRacket \\
  12481. \begin{array}{lcl}
  12482. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12483. \end{array}
  12484. \end{array}
  12485. \]
  12486. \fi}
  12487. \end{tcolorbox}
  12488. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12489. \label{fig:x86-2}
  12490. \end{figure}
  12491. The definitions of the concrete and abstract syntax of the
  12492. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12493. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12494. of global variables.
  12495. %
  12496. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12497. \code{select\_instructions} pass on the running example.
  12498. \begin{figure}[tbp]
  12499. \centering
  12500. \begin{tcolorbox}[colback=white]
  12501. {\if\edition\racketEd
  12502. % tests/s2_17.rkt
  12503. \begin{tabular}{lll}
  12504. \begin{minipage}{0.5\textwidth}
  12505. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12506. start:
  12507. tmp9 = (global-value free_ptr);
  12508. tmp0 = (+ tmp9 16);
  12509. tmp1 = (global-value fromspace_end);
  12510. if (< tmp0 tmp1)
  12511. goto block0;
  12512. else
  12513. goto block1;
  12514. block0:
  12515. _4 = (void);
  12516. goto block9;
  12517. block1:
  12518. (collect 16)
  12519. goto block9;
  12520. block9:
  12521. alloc2 = (allocate 1 (Vector Integer));
  12522. _3 = (vector-set! alloc2 0 42);
  12523. vecinit6 = alloc2;
  12524. tmp2 = (global-value free_ptr);
  12525. tmp3 = (+ tmp2 16);
  12526. tmp4 = (global-value fromspace_end);
  12527. if (< tmp3 tmp4)
  12528. goto block7;
  12529. else
  12530. goto block8;
  12531. block7:
  12532. _8 = (void);
  12533. goto block6;
  12534. block8:
  12535. (collect 16)
  12536. goto block6;
  12537. block6:
  12538. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12539. _7 = (vector-set! alloc5 0 vecinit6);
  12540. tmp5 = (vector-ref alloc5 0);
  12541. return (vector-ref tmp5 0);
  12542. \end{lstlisting}
  12543. \end{minipage}
  12544. &$\Rightarrow$&
  12545. \begin{minipage}{0.4\textwidth}
  12546. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12547. start:
  12548. movq free_ptr(%rip), tmp9
  12549. movq tmp9, tmp0
  12550. addq $16, tmp0
  12551. movq fromspace_end(%rip), tmp1
  12552. cmpq tmp1, tmp0
  12553. jl block0
  12554. jmp block1
  12555. block0:
  12556. movq $0, _4
  12557. jmp block9
  12558. block1:
  12559. movq %r15, %rdi
  12560. movq $16, %rsi
  12561. callq collect
  12562. jmp block9
  12563. block9:
  12564. movq free_ptr(%rip), %r11
  12565. addq $16, free_ptr(%rip)
  12566. movq $3, 0(%r11)
  12567. movq %r11, alloc2
  12568. movq alloc2, %r11
  12569. movq $42, 8(%r11)
  12570. movq $0, _3
  12571. movq alloc2, vecinit6
  12572. movq free_ptr(%rip), tmp2
  12573. movq tmp2, tmp3
  12574. addq $16, tmp3
  12575. movq fromspace_end(%rip), tmp4
  12576. cmpq tmp4, tmp3
  12577. jl block7
  12578. jmp block8
  12579. block7:
  12580. movq $0, _8
  12581. jmp block6
  12582. block8:
  12583. movq %r15, %rdi
  12584. movq $16, %rsi
  12585. callq collect
  12586. jmp block6
  12587. block6:
  12588. movq free_ptr(%rip), %r11
  12589. addq $16, free_ptr(%rip)
  12590. movq $131, 0(%r11)
  12591. movq %r11, alloc5
  12592. movq alloc5, %r11
  12593. movq vecinit6, 8(%r11)
  12594. movq $0, _7
  12595. movq alloc5, %r11
  12596. movq 8(%r11), tmp5
  12597. movq tmp5, %r11
  12598. movq 8(%r11), %rax
  12599. jmp conclusion
  12600. \end{lstlisting}
  12601. \end{minipage}
  12602. \end{tabular}
  12603. \fi}
  12604. {\if\edition\pythonEd
  12605. % tests/tuple/get_get.py
  12606. \begin{tabular}{lll}
  12607. \begin{minipage}{0.5\textwidth}
  12608. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12609. start:
  12610. init.514 = 42
  12611. tmp.517 = free_ptr
  12612. tmp.518 = (tmp.517 + 16)
  12613. tmp.519 = fromspace_end
  12614. if tmp.518 < tmp.519:
  12615. goto block.529
  12616. else:
  12617. goto block.530
  12618. block.529:
  12619. goto block.528
  12620. block.530:
  12621. collect(16)
  12622. goto block.528
  12623. block.528:
  12624. alloc.513 = allocate(1,tuple[int])
  12625. alloc.513:tuple[int][0] = init.514
  12626. v1 = alloc.513
  12627. init.516 = v1
  12628. tmp.520 = free_ptr
  12629. tmp.521 = (tmp.520 + 16)
  12630. tmp.522 = fromspace_end
  12631. if tmp.521 < tmp.522:
  12632. goto block.526
  12633. else:
  12634. goto block.527
  12635. block.526:
  12636. goto block.525
  12637. block.527:
  12638. collect(16)
  12639. goto block.525
  12640. block.525:
  12641. alloc.515 = allocate(1,tuple[tuple[int]])
  12642. alloc.515:tuple[tuple[int]][0] = init.516
  12643. v2 = alloc.515
  12644. tmp.523 = v2[0]
  12645. tmp.524 = tmp.523[0]
  12646. print(tmp.524)
  12647. return 0
  12648. \end{lstlisting}
  12649. \end{minipage}
  12650. &$\Rightarrow$&
  12651. \begin{minipage}{0.4\textwidth}
  12652. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12653. start:
  12654. movq $42, init.514
  12655. movq free_ptr(%rip), tmp.517
  12656. movq tmp.517, tmp.518
  12657. addq $16, tmp.518
  12658. movq fromspace_end(%rip), tmp.519
  12659. cmpq tmp.519, tmp.518
  12660. jl block.529
  12661. jmp block.530
  12662. block.529:
  12663. jmp block.528
  12664. block.530:
  12665. movq %r15, %rdi
  12666. movq $16, %rsi
  12667. callq collect
  12668. jmp block.528
  12669. block.528:
  12670. movq free_ptr(%rip), %r11
  12671. addq $16, free_ptr(%rip)
  12672. movq $3, 0(%r11)
  12673. movq %r11, alloc.513
  12674. movq alloc.513, %r11
  12675. movq init.514, 8(%r11)
  12676. movq alloc.513, v1
  12677. movq v1, init.516
  12678. movq free_ptr(%rip), tmp.520
  12679. movq tmp.520, tmp.521
  12680. addq $16, tmp.521
  12681. movq fromspace_end(%rip), tmp.522
  12682. cmpq tmp.522, tmp.521
  12683. jl block.526
  12684. jmp block.527
  12685. block.526:
  12686. jmp block.525
  12687. block.527:
  12688. movq %r15, %rdi
  12689. movq $16, %rsi
  12690. callq collect
  12691. jmp block.525
  12692. block.525:
  12693. movq free_ptr(%rip), %r11
  12694. addq $16, free_ptr(%rip)
  12695. movq $131, 0(%r11)
  12696. movq %r11, alloc.515
  12697. movq alloc.515, %r11
  12698. movq init.516, 8(%r11)
  12699. movq alloc.515, v2
  12700. movq v2, %r11
  12701. movq 8(%r11), %r11
  12702. movq %r11, tmp.523
  12703. movq tmp.523, %r11
  12704. movq 8(%r11), %r11
  12705. movq %r11, tmp.524
  12706. movq tmp.524, %rdi
  12707. callq print_int
  12708. movq $0, %rax
  12709. jmp conclusion
  12710. \end{lstlisting}
  12711. \end{minipage}
  12712. \end{tabular}
  12713. \fi}
  12714. \end{tcolorbox}
  12715. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12716. \code{select\_instructions} (\emph{right}) on the running example.}
  12717. \label{fig:select-instr-output-gc}
  12718. \end{figure}
  12719. \clearpage
  12720. \section{Register Allocation}
  12721. \label{sec:reg-alloc-gc}
  12722. \index{subject}{register allocation}
  12723. As discussed previously in this chapter, the garbage collector needs to
  12724. access all the pointers in the root set, that is, all variables that
  12725. are tuples. It will be the responsibility of the register allocator
  12726. to make sure that
  12727. \begin{enumerate}
  12728. \item the root stack is used for spilling tuple-typed variables, and
  12729. \item if a tuple-typed variable is live during a call to the
  12730. collector, it must be spilled to ensure that it is visible to the
  12731. collector.
  12732. \end{enumerate}
  12733. The latter responsibility can be handled during construction of the
  12734. interference graph, by adding interference edges between the call-live
  12735. tuple-typed variables and all the callee-saved registers. (They
  12736. already interfere with the caller-saved registers.)
  12737. %
  12738. \racket{The type information for variables is in the \code{Program}
  12739. form, so we recommend adding another parameter to the
  12740. \code{build\_interference} function to communicate this alist.}
  12741. %
  12742. \python{The type information for variables is generated by the type
  12743. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12744. the \code{CProgram} AST mode. You'll need to propagate that
  12745. information so that it is available in this pass.}
  12746. The spilling of tuple-typed variables to the root stack can be handled
  12747. after graph coloring, in choosing how to assign the colors
  12748. (integers) to registers and stack locations. The
  12749. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12750. changes to also record the number of spills to the root stack.
  12751. % build-interference
  12752. %
  12753. % callq
  12754. % extra parameter for var->type assoc. list
  12755. % update 'program' and 'if'
  12756. % allocate-registers
  12757. % allocate spilled vectors to the rootstack
  12758. % don't change color-graph
  12759. % TODO:
  12760. %\section{Patch Instructions}
  12761. %[mention that global variables are memory references]
  12762. \section{Generate Prelude and Conclusion}
  12763. \label{sec:print-x86-gc}
  12764. \label{sec:prelude-conclusion-x86-gc}
  12765. \index{subject}{prelude}\index{subject}{conclusion}
  12766. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12767. \code{prelude\_and\_conclusion} pass on the running example. In the
  12768. prelude of the \code{main} function, we allocate space
  12769. on the root stack to make room for the spills of tuple-typed
  12770. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12771. taking care that the root stack grows up instead of down. For the
  12772. running example, there was just one spill, so we increment \code{r15}
  12773. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12774. One issue that deserves special care is that there may be a call to
  12775. \code{collect} prior to the initializing assignments for all the
  12776. variables in the root stack. We do not want the garbage collector to
  12777. mistakenly determine that some uninitialized variable is a pointer that
  12778. needs to be followed. Thus, we zero out all locations on the root
  12779. stack in the prelude of \code{main}. In
  12780. figure~\ref{fig:print-x86-output-gc}, the instruction
  12781. %
  12782. \lstinline{movq $0, 0(%r15)}
  12783. %
  12784. is sufficient to accomplish this task because there is only one spill.
  12785. In general, we have to clear as many words as there are spills of
  12786. tuple-typed variables. The garbage collector tests each root to see
  12787. if it is null prior to dereferencing it.
  12788. \begin{figure}[htbp]
  12789. \begin{tcolorbox}[colback=white]
  12790. {\if\edition\racketEd
  12791. \begin{minipage}[t]{0.5\textwidth}
  12792. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12793. .globl main
  12794. main:
  12795. pushq %rbp
  12796. movq %rsp, %rbp
  12797. subq $0, %rsp
  12798. movq $65536, %rdi
  12799. movq $65536, %rsi
  12800. callq initialize
  12801. movq rootstack_begin(%rip), %r15
  12802. movq $0, 0(%r15)
  12803. addq $8, %r15
  12804. jmp start
  12805. conclusion:
  12806. subq $8, %r15
  12807. addq $0, %rsp
  12808. popq %rbp
  12809. retq
  12810. \end{lstlisting}
  12811. \end{minipage}
  12812. \fi}
  12813. {\if\edition\pythonEd
  12814. \begin{minipage}[t]{0.5\textwidth}
  12815. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12816. .globl main
  12817. main:
  12818. pushq %rbp
  12819. movq %rsp, %rbp
  12820. pushq %rbx
  12821. subq $8, %rsp
  12822. movq $65536, %rdi
  12823. movq $16, %rsi
  12824. callq initialize
  12825. movq rootstack_begin(%rip), %r15
  12826. movq $0, 0(%r15)
  12827. addq $8, %r15
  12828. jmp start
  12829. conclusion:
  12830. subq $8, %r15
  12831. addq $8, %rsp
  12832. popq %rbx
  12833. popq %rbp
  12834. retq
  12835. \end{lstlisting}
  12836. \end{minipage}
  12837. \fi}
  12838. \end{tcolorbox}
  12839. \caption{The prelude and conclusion for the running example.}
  12840. \label{fig:print-x86-output-gc}
  12841. \end{figure}
  12842. \begin{figure}[tbp]
  12843. \begin{tcolorbox}[colback=white]
  12844. {\if\edition\racketEd
  12845. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12846. \node (Lvec) at (0,2) {\large \LangVec{}};
  12847. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12848. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12849. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12850. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12851. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12852. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12853. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12854. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12855. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12856. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12857. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12858. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12859. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12860. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12861. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12862. \path[->,bend left=15] (Lvec-4) edge [right] node
  12863. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12864. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12865. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12866. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12867. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12868. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12869. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12870. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12871. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12872. \end{tikzpicture}
  12873. \fi}
  12874. {\if\edition\pythonEd\pythonColor
  12875. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12876. \node (Lvec) at (0,2) {\large \LangVec{}};
  12877. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12878. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12879. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12880. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12881. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12882. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12883. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12884. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12885. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12886. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12887. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12888. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12889. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12890. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12891. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12892. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12893. \end{tikzpicture}
  12894. \fi}
  12895. \end{tcolorbox}
  12896. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12897. \label{fig:Lvec-passes}
  12898. \end{figure}
  12899. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12900. for the compilation of \LangVec{}.
  12901. \clearpage
  12902. {\if\edition\racketEd
  12903. \section{Challenge: Simple Structures}
  12904. \label{sec:simple-structures}
  12905. \index{subject}{struct}
  12906. \index{subject}{structure}
  12907. The language \LangStruct{} extends \LangVec{} with support for simple
  12908. structures. The definition of its concrete syntax is shown in
  12909. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12910. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12911. in Typed Racket is a user-defined data type that contains named fields
  12912. and that is heap allocated\index{subject}{heap allocated},
  12913. similarly to a vector. The following is an
  12914. example of a structure definition, in this case the definition of a
  12915. \code{point} type:
  12916. \begin{lstlisting}
  12917. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12918. \end{lstlisting}
  12919. \newcommand{\LstructGrammarRacket}{
  12920. \begin{array}{lcl}
  12921. \Type &::=& \Var \\
  12922. \Exp &::=& (\Var\;\Exp \ldots)\\
  12923. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12924. \end{array}
  12925. }
  12926. \newcommand{\LstructASTRacket}{
  12927. \begin{array}{lcl}
  12928. \Type &::=& \VAR{\Var} \\
  12929. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12930. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12931. \end{array}
  12932. }
  12933. \begin{figure}[tbp]
  12934. \centering
  12935. \begin{tcolorbox}[colback=white]
  12936. \[
  12937. \begin{array}{l}
  12938. \gray{\LintGrammarRacket{}} \\ \hline
  12939. \gray{\LvarGrammarRacket{}} \\ \hline
  12940. \gray{\LifGrammarRacket{}} \\ \hline
  12941. \gray{\LwhileGrammarRacket} \\ \hline
  12942. \gray{\LtupGrammarRacket} \\ \hline
  12943. \LstructGrammarRacket \\
  12944. \begin{array}{lcl}
  12945. \LangStruct{} &::=& \Def \ldots \; \Exp
  12946. \end{array}
  12947. \end{array}
  12948. \]
  12949. \end{tcolorbox}
  12950. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12951. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12952. \label{fig:Lstruct-concrete-syntax}
  12953. \end{figure}
  12954. \begin{figure}[tbp]
  12955. \centering
  12956. \begin{tcolorbox}[colback=white]
  12957. \small
  12958. \[
  12959. \begin{array}{l}
  12960. \gray{\LintASTRacket{}} \\ \hline
  12961. \gray{\LvarASTRacket{}} \\ \hline
  12962. \gray{\LifASTRacket{}} \\ \hline
  12963. \gray{\LwhileASTRacket} \\ \hline
  12964. \gray{\LtupASTRacket} \\ \hline
  12965. \LstructASTRacket \\
  12966. \begin{array}{lcl}
  12967. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12968. \end{array}
  12969. \end{array}
  12970. \]
  12971. \end{tcolorbox}
  12972. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12973. (figure~\ref{fig:Lvec-syntax}).}
  12974. \label{fig:Lstruct-syntax}
  12975. \end{figure}
  12976. An instance of a structure is created using function-call syntax, with
  12977. the name of the structure in the function position, as follows:
  12978. \begin{lstlisting}
  12979. (point 7 12)
  12980. \end{lstlisting}
  12981. Function-call syntax is also used to read a field of a structure. The
  12982. function name is formed by the structure name, a dash, and the field
  12983. name. The following example uses \code{point-x} and \code{point-y} to
  12984. access the \code{x} and \code{y} fields of two point instances:
  12985. \begin{center}
  12986. \begin{lstlisting}
  12987. (let ([pt1 (point 7 12)])
  12988. (let ([pt2 (point 4 3)])
  12989. (+ (- (point-x pt1) (point-x pt2))
  12990. (- (point-y pt1) (point-y pt2)))))
  12991. \end{lstlisting}
  12992. \end{center}
  12993. Similarly, to write to a field of a structure, use its set function,
  12994. whose name starts with \code{set-}, followed by the structure name,
  12995. then a dash, then the field name, and finally with an exclamation
  12996. mark. The following example uses \code{set-point-x!} to change the
  12997. \code{x} field from \code{7} to \code{42}:
  12998. \begin{center}
  12999. \begin{lstlisting}
  13000. (let ([pt (point 7 12)])
  13001. (let ([_ (set-point-x! pt 42)])
  13002. (point-x pt)))
  13003. \end{lstlisting}
  13004. \end{center}
  13005. \begin{exercise}\normalfont\normalsize
  13006. Create a type checker for \LangStruct{} by extending the type
  13007. checker for \LangVec{}. Extend your compiler with support for simple
  13008. structures, compiling \LangStruct{} to x86 assembly code. Create
  13009. five new test cases that use structures, and test your compiler.
  13010. \end{exercise}
  13011. % TODO: create an interpreter for L_struct
  13012. \clearpage
  13013. \fi}
  13014. \section{Challenge: Arrays}
  13015. \label{sec:arrays}
  13016. % TODO mention trapped-error
  13017. In this chapter we have studied tuples, that is, heterogeneous
  13018. sequences of elements whose length is determined at compile time. This
  13019. challenge is also about sequences, but this time the length is
  13020. determined at runtime and all the elements have the same type (they
  13021. are homogeneous). We use the traditional term \emph{array} for this
  13022. latter kind of sequence.
  13023. %
  13024. \racket{
  13025. The Racket language does not distinguish between tuples and arrays;
  13026. they are both represented by vectors. However, Typed Racket
  13027. distinguishes between tuples and arrays: the \code{Vector} type is for
  13028. tuples, and the \code{Vectorof} type is for arrays.}%
  13029. \python{Arrays correspond to the \code{list} type in the Python language.}
  13030. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13031. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13032. presents the definition of the abstract syntax, extending \LangVec{}
  13033. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13034. \racket{\code{make-vector} primitive operator for creating an array,
  13035. whose arguments are the length of the array and an initial value for
  13036. all the elements in the array.}%
  13037. \python{bracket notation for creating an array literal.}
  13038. \racket{The \code{vector-length},
  13039. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13040. for tuples become overloaded for use with arrays.}
  13041. \python{
  13042. The subscript operator becomes overloaded for use with arrays and tuples
  13043. and now may appear on the left-hand side of an assignment.
  13044. Note that the index of the subscript, when applied to an array, may be an
  13045. arbitrary expression and not exclusively a constant integer.
  13046. The \code{len} function is also applicable to arrays.
  13047. }
  13048. %
  13049. We include integer multiplication in \LangArray{} because it is
  13050. useful in many examples involving arrays such as computing the
  13051. inner product of two arrays (figure~\ref{fig:inner_product}).
  13052. \newcommand{\LarrayGrammarRacket}{
  13053. \begin{array}{lcl}
  13054. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13055. \Exp &::=& \CMUL{\Exp}{\Exp}
  13056. \MID \CMAKEVEC{\Exp}{\Exp}
  13057. \end{array}
  13058. }
  13059. \newcommand{\LarrayASTRacket}{
  13060. \begin{array}{lcl}
  13061. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13062. \Exp &::=& \MUL{\Exp}{\Exp}
  13063. \MID \MAKEVEC{\Exp}{\Exp}
  13064. \end{array}
  13065. }
  13066. \newcommand{\LarrayGrammarPython}{
  13067. \begin{array}{lcl}
  13068. \Type &::=& \key{list}\LS\Type\RS \\
  13069. \Exp &::=& \CMUL{\Exp}{\Exp}
  13070. \MID \CGET{\Exp}{\Exp}
  13071. \MID \LS \Exp \code{,} \ldots \RS \\
  13072. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13073. \end{array}
  13074. }
  13075. \newcommand{\LarrayASTPython}{
  13076. \begin{array}{lcl}
  13077. \Type &::=& \key{ListType}\LP\Type\RP \\
  13078. \Exp &::=& \MUL{\Exp}{\Exp}
  13079. \MID \GET{\Exp}{\Exp} \\
  13080. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13081. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13082. \end{array}
  13083. }
  13084. \begin{figure}[tp]
  13085. \centering
  13086. \begin{tcolorbox}[colback=white]
  13087. \small
  13088. {\if\edition\racketEd
  13089. \[
  13090. \begin{array}{l}
  13091. \gray{\LintGrammarRacket{}} \\ \hline
  13092. \gray{\LvarGrammarRacket{}} \\ \hline
  13093. \gray{\LifGrammarRacket{}} \\ \hline
  13094. \gray{\LwhileGrammarRacket} \\ \hline
  13095. \gray{\LtupGrammarRacket} \\ \hline
  13096. \LarrayGrammarRacket \\
  13097. \begin{array}{lcl}
  13098. \LangArray{} &::=& \Exp
  13099. \end{array}
  13100. \end{array}
  13101. \]
  13102. \fi}
  13103. {\if\edition\pythonEd\pythonColor
  13104. \[
  13105. \begin{array}{l}
  13106. \gray{\LintGrammarPython{}} \\ \hline
  13107. \gray{\LvarGrammarPython{}} \\ \hline
  13108. \gray{\LifGrammarPython{}} \\ \hline
  13109. \gray{\LwhileGrammarPython} \\ \hline
  13110. \gray{\LtupGrammarPython} \\ \hline
  13111. \LarrayGrammarPython \\
  13112. \begin{array}{rcl}
  13113. \LangArrayM{} &::=& \Stmt^{*}
  13114. \end{array}
  13115. \end{array}
  13116. \]
  13117. \fi}
  13118. \end{tcolorbox}
  13119. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13120. \label{fig:Lvecof-concrete-syntax}
  13121. \end{figure}
  13122. \begin{figure}[tp]
  13123. \centering
  13124. \begin{tcolorbox}[colback=white]
  13125. \small
  13126. {\if\edition\racketEd
  13127. \[
  13128. \begin{array}{l}
  13129. \gray{\LintASTRacket{}} \\ \hline
  13130. \gray{\LvarASTRacket{}} \\ \hline
  13131. \gray{\LifASTRacket{}} \\ \hline
  13132. \gray{\LwhileASTRacket} \\ \hline
  13133. \gray{\LtupASTRacket} \\ \hline
  13134. \LarrayASTRacket \\
  13135. \begin{array}{lcl}
  13136. \LangArray{} &::=& \Exp
  13137. \end{array}
  13138. \end{array}
  13139. \]
  13140. \fi}
  13141. {\if\edition\pythonEd\pythonColor
  13142. \[
  13143. \begin{array}{l}
  13144. \gray{\LintASTPython{}} \\ \hline
  13145. \gray{\LvarASTPython{}} \\ \hline
  13146. \gray{\LifASTPython{}} \\ \hline
  13147. \gray{\LwhileASTPython} \\ \hline
  13148. \gray{\LtupASTPython} \\ \hline
  13149. \LarrayASTPython \\
  13150. \begin{array}{rcl}
  13151. \LangArrayM{} &::=& \Stmt^{*}
  13152. \end{array}
  13153. \end{array}
  13154. \]
  13155. \fi}
  13156. \end{tcolorbox}
  13157. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13158. \label{fig:Lvecof-syntax}
  13159. \end{figure}
  13160. \begin{figure}[tp]
  13161. \begin{tcolorbox}[colback=white]
  13162. {\if\edition\racketEd
  13163. % TODO: remove the function from the following example, like the python version -Jeremy
  13164. \begin{lstlisting}
  13165. (let ([A (make-vector 2 2)])
  13166. (let ([B (make-vector 2 3)])
  13167. (let ([i 0])
  13168. (let ([prod 0])
  13169. (begin
  13170. (while (< i n)
  13171. (begin
  13172. (set! prod (+ prod (* (vector-ref A i)
  13173. (vector-ref B i))))
  13174. (set! i (+ i 1))))
  13175. prod)))))
  13176. \end{lstlisting}
  13177. \fi}
  13178. {\if\edition\pythonEd\pythonColor
  13179. \begin{lstlisting}
  13180. A = [2, 2]
  13181. B = [3, 3]
  13182. i = 0
  13183. prod = 0
  13184. while i != len(A):
  13185. prod = prod + A[i] * B[i]
  13186. i = i + 1
  13187. print(prod)
  13188. \end{lstlisting}
  13189. \fi}
  13190. \end{tcolorbox}
  13191. \caption{Example program that computes the inner product.}
  13192. \label{fig:inner_product}
  13193. \end{figure}
  13194. {\if\edition\racketEd
  13195. %
  13196. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13197. checker for \LangArray{}. The result type of
  13198. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13199. of the initializing expression. The length expression is required to
  13200. have type \code{Integer}. The type checking of the operators
  13201. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13202. updated to handle the situation in which the vector has type
  13203. \code{Vectorof}. In these cases we translate the operators to their
  13204. \code{vectorof} form so that later passes can easily distinguish
  13205. between operations on tuples versus arrays. We override the
  13206. \code{operator-types} method to provide the type signature for
  13207. multiplication: it takes two integers and returns an integer.
  13208. \fi}
  13209. %
  13210. {\if\edition\pythonEd\pythonColor
  13211. %
  13212. The type checker for \LangArray{} is defined in
  13213. figure~\ref{fig:type-check-Lvecof} and
  13214. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13215. is \code{list[T]}, where \code{T} is the type of the initializing
  13216. expressions. The type checking of the \code{len} function and the
  13217. subscript operator are updated to handle lists. The type checker now
  13218. also handles a subscript on the left-hand side of an assignment.
  13219. Regarding multiplication, it takes two integers and returns an
  13220. integer.
  13221. %
  13222. \fi}
  13223. \begin{figure}[tbp]
  13224. \begin{tcolorbox}[colback=white]
  13225. {\if\edition\racketEd
  13226. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13227. (define type-check-Lvecof-class
  13228. (class type-check-Lvec-class
  13229. (super-new)
  13230. (inherit check-type-equal?)
  13231. (define/override (operator-types)
  13232. (append '((* . ((Integer Integer) . Integer)))
  13233. (super operator-types)))
  13234. (define/override (type-check-exp env)
  13235. (lambda (e)
  13236. (define recur (type-check-exp env))
  13237. (match e
  13238. [(Prim 'make-vector (list e1 e2))
  13239. (define-values (e1^ t1) (recur e1))
  13240. (define-values (e2^ elt-type) (recur e2))
  13241. (define vec-type `(Vectorof ,elt-type))
  13242. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13243. [(Prim 'vector-ref (list e1 e2))
  13244. (define-values (e1^ t1) (recur e1))
  13245. (define-values (e2^ t2) (recur e2))
  13246. (match* (t1 t2)
  13247. [(`(Vectorof ,elt-type) 'Integer)
  13248. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13249. [(other wise) ((super type-check-exp env) e)])]
  13250. [(Prim 'vector-set! (list e1 e2 e3) )
  13251. (define-values (e-vec t-vec) (recur e1))
  13252. (define-values (e2^ t2) (recur e2))
  13253. (define-values (e-arg^ t-arg) (recur e3))
  13254. (match t-vec
  13255. [`(Vectorof ,elt-type)
  13256. (check-type-equal? elt-type t-arg e)
  13257. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13258. [else ((super type-check-exp env) e)])]
  13259. [(Prim 'vector-length (list e1))
  13260. (define-values (e1^ t1) (recur e1))
  13261. (match t1
  13262. [`(Vectorof ,t)
  13263. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13264. [else ((super type-check-exp env) e)])]
  13265. [else ((super type-check-exp env) e)])))
  13266. ))
  13267. (define (type-check-Lvecof p)
  13268. (send (new type-check-Lvecof-class) type-check-program p))
  13269. \end{lstlisting}
  13270. \fi}
  13271. {\if\edition\pythonEd\pythonColor
  13272. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13273. class TypeCheckLarray(TypeCheckLtup):
  13274. def type_check_exp(self, e, env):
  13275. match e:
  13276. case ast.List(es, Load()):
  13277. ts = [self.type_check_exp(e, env) for e in es]
  13278. elt_ty = ts[0]
  13279. for (ty, elt) in zip(ts, es):
  13280. self.check_type_equal(elt_ty, ty, elt)
  13281. e.has_type = ListType(elt_ty)
  13282. return e.has_type
  13283. case Call(Name('len'), [tup]):
  13284. tup_t = self.type_check_exp(tup, env)
  13285. tup.has_type = tup_t
  13286. match tup_t:
  13287. case TupleType(ts):
  13288. return IntType()
  13289. case ListType(ty):
  13290. return IntType()
  13291. case _:
  13292. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13293. case Subscript(tup, index, Load()):
  13294. tup_ty = self.type_check_exp(tup, env)
  13295. index_ty = self.type_check_exp(index, env)
  13296. self.check_type_equal(index_ty, IntType(), index)
  13297. match tup_ty:
  13298. case TupleType(ts):
  13299. match index:
  13300. case Constant(i):
  13301. return ts[i]
  13302. case _:
  13303. raise Exception('subscript required constant integer index')
  13304. case ListType(ty):
  13305. return ty
  13306. case _:
  13307. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13308. case BinOp(left, Mult(), right):
  13309. l = self.type_check_exp(left, env)
  13310. self.check_type_equal(l, IntType(), left)
  13311. r = self.type_check_exp(right, env)
  13312. self.check_type_equal(r, IntType(), right)
  13313. return IntType()
  13314. case _:
  13315. return super().type_check_exp(e, env)
  13316. \end{lstlisting}
  13317. \fi}
  13318. \end{tcolorbox}
  13319. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13320. \label{fig:type-check-Lvecof}
  13321. \end{figure}
  13322. {\if\edition\pythonEd
  13323. \begin{figure}[tbp]
  13324. \begin{tcolorbox}[colback=white]
  13325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13326. def type_check_stmts(self, ss, env):
  13327. if len(ss) == 0:
  13328. return VoidType()
  13329. match ss[0]:
  13330. case Assign([Subscript(tup, index, Store())], value):
  13331. tup_t = self.type_check_exp(tup, env)
  13332. value_t = self.type_check_exp(value, env)
  13333. index_ty = self.type_check_exp(index, env)
  13334. self.check_type_equal(index_ty, IntType(), index)
  13335. match tup_t:
  13336. case ListType(ty):
  13337. self.check_type_equal(ty, value_t, ss[0])
  13338. case TupleType(ts):
  13339. return self.type_check_stmts(ss, env)
  13340. case _:
  13341. raise Exception('type_check_stmts: '
  13342. 'expected tuple or list, not ' + repr(tup_t))
  13343. return self.type_check_stmts(ss[1:], env)
  13344. case _:
  13345. return super().type_check_stmts(ss, env)
  13346. \end{lstlisting}
  13347. \end{tcolorbox}
  13348. \caption{Type checker for the \LangArray{} language, part 2.}
  13349. \label{fig:type-check-Lvecof-part2}
  13350. \end{figure}
  13351. \fi}
  13352. The definition of the interpreter for \LangArray{} is shown in
  13353. \racket{figure~\ref{fig:interp-Lvecof}}
  13354. \python{figure~\ref{fig:interp-Lvecof}}.
  13355. \racket{The \code{make-vector} operator is
  13356. interpreted using Racket's \code{make-vector} function,
  13357. and multiplication is interpreted using \code{fx*},
  13358. which is multiplication for \code{fixnum} integers.
  13359. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13360. we translate array access operations
  13361. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13362. which we interpret using \code{vector} operations with additional
  13363. bounds checks that signal a \code{trapped-error}.
  13364. }
  13365. %
  13366. \python{We implement array creation with a Python list comprehension,
  13367. and multiplication is implemented with 64-bit multiplication. We
  13368. add a case for a subscript on the left-hand side of
  13369. assignment. Other uses of subscript can be handled by the existing
  13370. code for tuples.}
  13371. \begin{figure}[tbp]
  13372. \begin{tcolorbox}[colback=white]
  13373. {\if\edition\racketEd
  13374. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13375. (define interp-Lvecof-class
  13376. (class interp-Lvec-class
  13377. (super-new)
  13378. (define/override (interp-op op)
  13379. (match op
  13380. ['make-vector make-vector]
  13381. ['vectorof-length vector-length]
  13382. ['vectorof-ref
  13383. (lambda (v i)
  13384. (if (< i (vector-length v))
  13385. (vector-ref v i)
  13386. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13387. ['vectorof-set!
  13388. (lambda (v i e)
  13389. (if (< i (vector-length v))
  13390. (vector-set! v i e)
  13391. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13392. [else (super interp-op op)]))
  13393. ))
  13394. (define (interp-Lvecof p)
  13395. (send (new interp-Lvecof-class) interp-program p))
  13396. \end{lstlisting}
  13397. \fi}
  13398. {\if\edition\pythonEd\pythonColor
  13399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13400. class InterpLarray(InterpLtup):
  13401. def interp_exp(self, e, env):
  13402. match e:
  13403. case ast.List(es, Load()):
  13404. return [self.interp_exp(e, env) for e in es]
  13405. case BinOp(left, Mult(), right):
  13406. l = self.interp_exp(left, env)
  13407. r = self.interp_exp(right, env)
  13408. return mul64(l, r)
  13409. case Subscript(tup, index, Load()):
  13410. t = self.interp_exp(tup, env)
  13411. n = self.interp_exp(index, env)
  13412. if n < len(t):
  13413. return t[n]
  13414. else:
  13415. raise TrappedError('array index out of bounds')
  13416. case _:
  13417. return super().interp_exp(e, env)
  13418. def interp_stmt(self, s, env, cont):
  13419. match s:
  13420. case Assign([Subscript(tup, index)], value):
  13421. t = self.interp_exp(tup, env)
  13422. n = self.interp_exp(index, env)
  13423. if n < len(t):
  13424. t[n] = self.interp_exp(value, env)
  13425. else:
  13426. raise TrappedError('array index out of bounds')
  13427. return self.interp_stmts(cont, env)
  13428. case _:
  13429. return super().interp_stmt(s, env, cont)
  13430. \end{lstlisting}
  13431. \fi}
  13432. \end{tcolorbox}
  13433. \caption{Interpreter for \LangArray{}.}
  13434. \label{fig:interp-Lvecof}
  13435. \end{figure}
  13436. \subsection{Data Representation}
  13437. \label{sec:array-rep}
  13438. Just as with tuples, we store arrays on the heap, which means that the
  13439. garbage collector will need to inspect arrays. An immediate thought is
  13440. to use the same representation for arrays that we use for tuples.
  13441. However, we limit tuples to a length of fifty so that their length and
  13442. pointer mask can fit into the 64-bit tag at the beginning of each
  13443. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13444. millions of elements, so we need more bits to store the length.
  13445. However, because arrays are homogeneous, we need only 1 bit for the
  13446. pointer mask instead of 1 bit per array element. Finally, the
  13447. garbage collector must be able to distinguish between tuples
  13448. and arrays, so we need to reserve one bit for that purpose. We
  13449. arrive at the following layout for the 64-bit tag at the beginning of
  13450. an array:
  13451. \begin{itemize}
  13452. \item The right-most bit is the forwarding bit, just as in a tuple.
  13453. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13454. that it is not.
  13455. \item The next bit to the left is the pointer mask. A $0$ indicates
  13456. that none of the elements are pointers, and a $1$ indicates that all
  13457. the elements are pointers.
  13458. \item The next $60$ bits store the length of the array.
  13459. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13460. and an array ($1$).
  13461. \item The left-most bit is reserved as explained in
  13462. chapter~\ref{ch:Lgrad}.
  13463. \end{itemize}
  13464. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13465. %% differentiate the kinds of values that have been injected into the
  13466. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13467. %% to indicate that the value is an array.
  13468. In the following subsections we provide hints regarding how to update
  13469. the passes to handle arrays.
  13470. \subsection{Overload Resolution}
  13471. \label{sec:array-resolution}
  13472. As noted previously, with the addition of arrays, several operators
  13473. have become \emph{overloaded}; that is, they can be applied to values
  13474. of more than one type. In this case, the element access and length
  13475. operators can be applied to both tuples and arrays. This kind of
  13476. overloading is quite common in programming languages, so many
  13477. compilers perform \emph{overload resolution}\index{subject}{overload
  13478. resolution} to handle it. The idea is to translate each overloaded
  13479. operator into different operators for the different types.
  13480. Implement a new pass named \code{resolve}.
  13481. Translate the reading of an array element to
  13482. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13483. and the writing of an array element to
  13484. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13485. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13486. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13487. When these operators are applied to tuples, leave them as is.
  13488. %
  13489. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13490. field, which can be inspected to determine whether the operator
  13491. is applied to a tuple or an array.}
  13492. \subsection{Bounds Checking}
  13493. Recall that the interpreter for \LangArray{} signals a
  13494. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13495. when there is an array access that is out of
  13496. bounds. Therefore your compiler is obliged to also catch these errors
  13497. during execution and halt, signaling an error. We recommend inserting
  13498. a new pass named \code{check\_bounds} that inserts code around each
  13499. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13500. \python{subscript} operation to ensure that the index is greater than
  13501. or equal to zero and less than the array's length. If not, the program
  13502. should halt, for which we recommend using a new primitive operation
  13503. named \code{exit}.
  13504. %% \subsection{Reveal Casts}
  13505. %% The array-access operators \code{vectorof-ref} and
  13506. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13507. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13508. %% that the type checker cannot tell whether the index will be in bounds,
  13509. %% so the bounds check must be performed at run time. Recall that the
  13510. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13511. %% an \code{If} around a vector reference for update to check whether
  13512. %% the index is less than the length. You should do the same for
  13513. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13514. %% In addition, the handling of the \code{any-vector} operators in
  13515. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13516. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13517. %% generated code should test whether the tag is for tuples (\code{010})
  13518. %% or arrays (\code{110}) and then dispatch to either
  13519. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13520. %% we add a case in \code{select\_instructions} to generate the
  13521. %% appropriate instructions for accessing the array length from the
  13522. %% header of an array.
  13523. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13524. %% the generated code needs to check that the index is less than the
  13525. %% vector length, so like the code for \code{any-vector-length}, check
  13526. %% the tag to determine whether to use \code{any-vector-length} or
  13527. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13528. %% is complete, the generated code can use \code{any-vector-ref} and
  13529. %% \code{any-vector-set!} for both tuples and arrays because the
  13530. %% instructions used for those operators do not look at the tag at the
  13531. %% front of the tuple or array.
  13532. \subsection{Expose Allocation}
  13533. This pass should translate array creation into lower-level
  13534. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13535. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13536. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13537. array. The \code{AllocateArray} AST node allocates an array of the
  13538. length specified by the $\Exp$ (of type \INTTY), but does not
  13539. initialize the elements of the array. Generate code in this pass to
  13540. initialize the elements analogous to the case for tuples.
  13541. {\if\edition\racketEd
  13542. \subsection{Uncover \texttt{get!}}
  13543. \label{sec:uncover-get-bang-vecof}
  13544. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13545. \code{uncover-get!-exp}.
  13546. \fi}
  13547. \subsection{Remove Complex Operands}
  13548. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13549. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13550. complex, and its subexpression must be atomic.
  13551. \subsection{Explicate Control}
  13552. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13553. \code{explicate\_assign}.
  13554. \subsection{Select Instructions}
  13555. \index{subject}{select instructions}
  13556. Generate instructions for \code{AllocateArray} similar to those for
  13557. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13558. except that the tag at the front of the array should instead use the
  13559. representation discussed in section~\ref{sec:array-rep}.
  13560. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13561. extract the length from the tag.
  13562. The instructions generated for accessing an element of an array differ
  13563. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13564. that the index is not a constant so you need to generate instructions
  13565. that compute the offset at runtime.
  13566. Compile the \code{exit} primitive into a call to the \code{exit}
  13567. function of the C standard library, with an argument of $255$.
  13568. %% Also, note that assignment to an array element may appear in
  13569. %% as a stand-alone statement, so make sure to handle that situation in
  13570. %% this pass.
  13571. %% Finally, the instructions for \code{any-vectorof-length} should be
  13572. %% similar to those for \code{vectorof-length}, except that one must
  13573. %% first project the array by writing zeroes into the $3$-bit tag
  13574. \begin{exercise}\normalfont\normalsize
  13575. Implement a compiler for the \LangArray{} language by extending your
  13576. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13577. programs, including the one shown in figure~\ref{fig:inner_product}
  13578. and also a program that multiplies two matrices. Note that although
  13579. matrices are two-dimensional arrays, they can be encoded into
  13580. one-dimensional arrays by laying out each row in the array, one after
  13581. the next.
  13582. \end{exercise}
  13583. {\if\edition\racketEd
  13584. \section{Challenge: Generational Collection}
  13585. The copying collector described in section~\ref{sec:GC} can incur
  13586. significant runtime overhead because the call to \code{collect} takes
  13587. time proportional to all the live data. One way to reduce this
  13588. overhead is to reduce how much data is inspected in each call to
  13589. \code{collect}. In particular, researchers have observed that recently
  13590. allocated data is more likely to become garbage then data that has
  13591. survived one or more previous calls to \code{collect}. This insight
  13592. motivated the creation of \emph{generational garbage collectors}
  13593. \index{subject}{generational garbage collector} that
  13594. (1) segregate data according to its age into two or more generations;
  13595. (2) allocate less space for younger generations, so collecting them is
  13596. faster, and more space for the older generations; and (3) perform
  13597. collection on the younger generations more frequently than on older
  13598. generations~\citep{Wilson:1992fk}.
  13599. For this challenge assignment, the goal is to adapt the copying
  13600. collector implemented in \code{runtime.c} to use two generations, one
  13601. for young data and one for old data. Each generation consists of a
  13602. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13603. \code{collect} function to use the two generations:
  13604. \begin{enumerate}
  13605. \item Copy the young generation's FromSpace to its ToSpace and then
  13606. switch the role of the ToSpace and FromSpace.
  13607. \item If there is enough space for the requested number of bytes in
  13608. the young FromSpace, then return from \code{collect}.
  13609. \item If there is not enough space in the young FromSpace for the
  13610. requested bytes, then move the data from the young generation to the
  13611. old one with the following steps:
  13612. \begin{enumerate}
  13613. \item[a.] If there is enough room in the old FromSpace, copy the young
  13614. FromSpace to the old FromSpace and then return.
  13615. \item[b.] If there is not enough room in the old FromSpace, then collect
  13616. the old generation by copying the old FromSpace to the old ToSpace
  13617. and swap the roles of the old FromSpace and ToSpace.
  13618. \item[c.] If there is enough room now, copy the young FromSpace to the
  13619. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13620. and ToSpace for the old generation. Copy the young FromSpace and
  13621. the old FromSpace into the larger FromSpace for the old
  13622. generation and then return.
  13623. \end{enumerate}
  13624. \end{enumerate}
  13625. We recommend that you generalize the \code{cheney} function so that it
  13626. can be used for all the copies mentioned: between the young FromSpace
  13627. and ToSpace, between the old FromSpace and ToSpace, and between the
  13628. young FromSpace and old FromSpace. This can be accomplished by adding
  13629. parameters to \code{cheney} that replace its use of the global
  13630. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13631. \code{tospace\_begin}, and \code{tospace\_end}.
  13632. Note that the collection of the young generation does not traverse the
  13633. old generation. This introduces a potential problem: there may be
  13634. young data that is reachable only through pointers in the old
  13635. generation. If these pointers are not taken into account, the
  13636. collector could throw away young data that is live! One solution,
  13637. called \emph{pointer recording}, is to maintain a set of all the
  13638. pointers from the old generation into the new generation and consider
  13639. this set as part of the root set. To maintain this set, the compiler
  13640. must insert extra instructions around every \code{vector-set!}. If the
  13641. vector being modified is in the old generation, and if the value being
  13642. written is a pointer into the new generation, then that pointer must
  13643. be added to the set. Also, if the value being overwritten was a
  13644. pointer into the new generation, then that pointer should be removed
  13645. from the set.
  13646. \begin{exercise}\normalfont\normalsize
  13647. Adapt the \code{collect} function in \code{runtime.c} to implement
  13648. generational garbage collection, as outlined in this section.
  13649. Update the code generation for \code{vector-set!} to implement
  13650. pointer recording. Make sure that your new compiler and runtime
  13651. execute without error on your test suite.
  13652. \end{exercise}
  13653. \fi}
  13654. \section{Further Reading}
  13655. \citet{Appel90} describes many data representation approaches
  13656. including the ones used in the compilation of Standard ML.
  13657. There are many alternatives to copying collectors (and their bigger
  13658. siblings, the generational collectors) with regard to garbage
  13659. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13660. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13661. collectors are that allocation is fast (just a comparison and pointer
  13662. increment), there is no fragmentation, cyclic garbage is collected,
  13663. and the time complexity of collection depends only on the amount of
  13664. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13665. main disadvantages of a two-space copying collector is that it uses a
  13666. lot of extra space and takes a long time to perform the copy, though
  13667. these problems are ameliorated in generational collectors.
  13668. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13669. small objects and generate a lot of garbage, so copying and
  13670. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13671. Garbage collection is an active research topic, especially concurrent
  13672. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13673. developing new techniques and revisiting old
  13674. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13675. meet every year at the International Symposium on Memory Management to
  13676. present these findings.
  13677. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13678. \chapter{Functions}
  13679. \label{ch:Lfun}
  13680. \index{subject}{function}
  13681. \setcounter{footnote}{0}
  13682. This chapter studies the compilation of a subset of \racket{Typed
  13683. Racket}\python{Python} in which only top-level function definitions
  13684. are allowed. This kind of function appears in the C programming
  13685. language, and it serves as an important stepping-stone to implementing
  13686. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13687. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13688. \section{The \LangFun{} Language}
  13689. The concrete syntax and abstract syntax for function definitions and
  13690. function application are shown in
  13691. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13692. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13693. with zero or more function definitions. The function names from these
  13694. definitions are in scope for the entire program, including all the
  13695. function definitions, and therefore the ordering of function
  13696. definitions does not matter.
  13697. %
  13698. \python{The abstract syntax for function parameters in
  13699. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13700. consists of a parameter name and its type. This design differs from
  13701. Python's \code{ast} module, which has a more complex structure for
  13702. function parameters to handle keyword parameters,
  13703. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13704. complex Python abstract syntax into the simpler syntax shown in
  13705. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13706. \code{FunctionDef} constructor are for decorators and a type
  13707. comment, neither of which are used by our compiler. We recommend
  13708. replacing them with \code{None} in the \code{shrink} pass.
  13709. }
  13710. %
  13711. The concrete syntax for function application
  13712. \index{subject}{function application}
  13713. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13714. where the first expression
  13715. must evaluate to a function and the remaining expressions are the arguments. The
  13716. abstract syntax for function application is
  13717. $\APPLY{\Exp}{\Exp^*}$.
  13718. %% The syntax for function application does not include an explicit
  13719. %% keyword, which is error prone when using \code{match}. To alleviate
  13720. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13721. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13722. Functions are first-class in the sense that a function pointer
  13723. \index{subject}{function pointer} is data and can be stored in memory or passed
  13724. as a parameter to another function. Thus, there is a function
  13725. type, written
  13726. {\if\edition\racketEd
  13727. \begin{lstlisting}
  13728. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13729. \end{lstlisting}
  13730. \fi}
  13731. {\if\edition\pythonEd\pythonColor
  13732. \begin{lstlisting}
  13733. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13734. \end{lstlisting}
  13735. \fi}
  13736. %
  13737. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13738. through $\Type_n$ and whose return type is $\Type_R$. The main
  13739. limitation of these functions (with respect to
  13740. \racket{Racket}\python{Python} functions) is that they are not
  13741. lexically scoped. That is, the only external entities that can be
  13742. referenced from inside a function body are other globally defined
  13743. functions. The syntax of \LangFun{} prevents function definitions from
  13744. being nested inside each other.
  13745. \newcommand{\LfunGrammarRacket}{
  13746. \begin{array}{lcl}
  13747. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13748. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13749. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13750. \end{array}
  13751. }
  13752. \newcommand{\LfunASTRacket}{
  13753. \begin{array}{lcl}
  13754. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13755. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13756. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13757. \end{array}
  13758. }
  13759. \newcommand{\LfunGrammarPython}{
  13760. \begin{array}{lcl}
  13761. \Type &::=& \key{int}
  13762. \MID \key{bool} \MID \key{void}
  13763. \MID \key{tuple}\LS \Type^+ \RS
  13764. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13765. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13766. \Stmt &::=& \CRETURN{\Exp} \\
  13767. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13768. \end{array}
  13769. }
  13770. \newcommand{\LfunASTPython}{
  13771. \begin{array}{lcl}
  13772. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13773. \MID \key{TupleType}\LS\Type^+\RS\\
  13774. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13775. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13776. \Stmt &::=& \RETURN{\Exp} \\
  13777. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13778. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13779. \end{array}
  13780. }
  13781. \begin{figure}[tp]
  13782. \centering
  13783. \begin{tcolorbox}[colback=white]
  13784. \small
  13785. {\if\edition\racketEd
  13786. \[
  13787. \begin{array}{l}
  13788. \gray{\LintGrammarRacket{}} \\ \hline
  13789. \gray{\LvarGrammarRacket{}} \\ \hline
  13790. \gray{\LifGrammarRacket{}} \\ \hline
  13791. \gray{\LwhileGrammarRacket} \\ \hline
  13792. \gray{\LtupGrammarRacket} \\ \hline
  13793. \LfunGrammarRacket \\
  13794. \begin{array}{lcl}
  13795. \LangFunM{} &::=& \Def \ldots \; \Exp
  13796. \end{array}
  13797. \end{array}
  13798. \]
  13799. \fi}
  13800. {\if\edition\pythonEd\pythonColor
  13801. \[
  13802. \begin{array}{l}
  13803. \gray{\LintGrammarPython{}} \\ \hline
  13804. \gray{\LvarGrammarPython{}} \\ \hline
  13805. \gray{\LifGrammarPython{}} \\ \hline
  13806. \gray{\LwhileGrammarPython} \\ \hline
  13807. \gray{\LtupGrammarPython} \\ \hline
  13808. \LfunGrammarPython \\
  13809. \begin{array}{rcl}
  13810. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13811. \end{array}
  13812. \end{array}
  13813. \]
  13814. \fi}
  13815. \end{tcolorbox}
  13816. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13817. \label{fig:Lfun-concrete-syntax}
  13818. \end{figure}
  13819. \begin{figure}[tp]
  13820. \centering
  13821. \begin{tcolorbox}[colback=white]
  13822. \small
  13823. {\if\edition\racketEd
  13824. \[
  13825. \begin{array}{l}
  13826. \gray{\LintOpAST} \\ \hline
  13827. \gray{\LvarASTRacket{}} \\ \hline
  13828. \gray{\LifASTRacket{}} \\ \hline
  13829. \gray{\LwhileASTRacket{}} \\ \hline
  13830. \gray{\LtupASTRacket{}} \\ \hline
  13831. \LfunASTRacket \\
  13832. \begin{array}{lcl}
  13833. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13834. \end{array}
  13835. \end{array}
  13836. \]
  13837. \fi}
  13838. {\if\edition\pythonEd\pythonColor
  13839. \[
  13840. \begin{array}{l}
  13841. \gray{\LintASTPython{}} \\ \hline
  13842. \gray{\LvarASTPython{}} \\ \hline
  13843. \gray{\LifASTPython{}} \\ \hline
  13844. \gray{\LwhileASTPython} \\ \hline
  13845. \gray{\LtupASTPython} \\ \hline
  13846. \LfunASTPython \\
  13847. \begin{array}{rcl}
  13848. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13849. \end{array}
  13850. \end{array}
  13851. \]
  13852. \fi}
  13853. \end{tcolorbox}
  13854. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13855. \label{fig:Lfun-syntax}
  13856. \end{figure}
  13857. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13858. representative example of defining and using functions in \LangFun{}.
  13859. We define a function \code{map} that applies some other function
  13860. \code{f} to both elements of a tuple and returns a new tuple
  13861. containing the results. We also define a function \code{inc}. The
  13862. program applies \code{map} to \code{inc} and
  13863. %
  13864. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13865. %
  13866. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13867. %
  13868. from which we return \code{42}.
  13869. \begin{figure}[tbp]
  13870. \begin{tcolorbox}[colback=white]
  13871. {\if\edition\racketEd
  13872. \begin{lstlisting}
  13873. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13874. : (Vector Integer Integer)
  13875. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13876. (define (inc [x : Integer]) : Integer
  13877. (+ x 1))
  13878. (vector-ref (map inc (vector 0 41)) 1)
  13879. \end{lstlisting}
  13880. \fi}
  13881. {\if\edition\pythonEd\pythonColor
  13882. \begin{lstlisting}
  13883. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13884. return f(v[0]), f(v[1])
  13885. def inc(x : int) -> int:
  13886. return x + 1
  13887. print(map(inc, (0, 41))[1])
  13888. \end{lstlisting}
  13889. \fi}
  13890. \end{tcolorbox}
  13891. \caption{Example of using functions in \LangFun{}.}
  13892. \label{fig:Lfun-function-example}
  13893. \end{figure}
  13894. The definitional interpreter for \LangFun{} is shown in
  13895. figure~\ref{fig:interp-Lfun}. The case for the
  13896. %
  13897. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13898. %
  13899. AST is responsible for setting up the mutual recursion between the
  13900. top-level function definitions.
  13901. %
  13902. \racket{We use the classic back-patching
  13903. \index{subject}{back-patching} approach that uses mutable variables
  13904. and makes two passes over the function
  13905. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13906. top-level environment using a mutable cons cell for each function
  13907. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13908. for each function is incomplete; it does not yet include the environment.
  13909. Once the top-level environment has been constructed, we iterate over it and
  13910. update the \code{lambda} values to use the top-level environment.}
  13911. %
  13912. \python{We create a dictionary named \code{env} and fill it in
  13913. by mapping each function name to a new \code{Function} value,
  13914. each of which stores a reference to the \code{env}.
  13915. (We define the class \code{Function} for this purpose.)}
  13916. %
  13917. To interpret a function \racket{application}\python{call}, we match
  13918. the result of the function expression to obtain a function value. We
  13919. then extend the function's environment with the mapping of parameters to
  13920. argument values. Finally, we interpret the body of the function in
  13921. this extended environment.
  13922. \begin{figure}[tp]
  13923. \begin{tcolorbox}[colback=white]
  13924. {\if\edition\racketEd
  13925. \begin{lstlisting}
  13926. (define interp-Lfun-class
  13927. (class interp-Lvec-class
  13928. (super-new)
  13929. (define/override ((interp-exp env) e)
  13930. (define recur (interp-exp env))
  13931. (match e
  13932. [(Apply fun args)
  13933. (define fun-val (recur fun))
  13934. (define arg-vals (for/list ([e args]) (recur e)))
  13935. (match fun-val
  13936. [`(function (,xs ...) ,body ,fun-env)
  13937. (define params-args (for/list ([x xs] [arg arg-vals])
  13938. (cons x (box arg))))
  13939. (define new-env (append params-args fun-env))
  13940. ((interp-exp new-env) body)]
  13941. [else
  13942. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13943. [else ((super interp-exp env) e)]
  13944. ))
  13945. (define/public (interp-def d)
  13946. (match d
  13947. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13948. (cons f (box `(function ,xs ,body ())))]))
  13949. (define/override (interp-program p)
  13950. (match p
  13951. [(ProgramDefsExp info ds body)
  13952. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13953. (for/list ([f (in-dict-values top-level)])
  13954. (set-box! f (match (unbox f)
  13955. [`(function ,xs ,body ())
  13956. `(function ,xs ,body ,top-level)])))
  13957. ((interp-exp top-level) body))]))
  13958. ))
  13959. (define (interp-Lfun p)
  13960. (send (new interp-Lfun-class) interp-program p))
  13961. \end{lstlisting}
  13962. \fi}
  13963. {\if\edition\pythonEd\pythonColor
  13964. \begin{lstlisting}
  13965. class InterpLfun(InterpLtup):
  13966. def apply_fun(self, fun, args, e):
  13967. match fun:
  13968. case Function(name, xs, body, env):
  13969. new_env = env.copy().update(zip(xs, args))
  13970. return self.interp_stmts(body, new_env)
  13971. case _:
  13972. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13973. def interp_exp(self, e, env):
  13974. match e:
  13975. case Call(Name('input_int'), []):
  13976. return super().interp_exp(e, env)
  13977. case Call(func, args):
  13978. f = self.interp_exp(func, env)
  13979. vs = [self.interp_exp(arg, env) for arg in args]
  13980. return self.apply_fun(f, vs, e)
  13981. case _:
  13982. return super().interp_exp(e, env)
  13983. def interp_stmt(self, s, env, cont):
  13984. match s:
  13985. case Return(value):
  13986. return self.interp_exp(value, env)
  13987. case FunctionDef(name, params, bod, dl, returns, comment):
  13988. if isinstance(params, ast.arguments):
  13989. ps = [p.arg for p in params.args]
  13990. else:
  13991. ps = [x for (x,t) in params]
  13992. env[name] = Function(name, ps, bod, env)
  13993. return self.interp_stmts(cont, env)
  13994. case _:
  13995. return super().interp_stmt(s, env, cont)
  13996. def interp(self, p):
  13997. match p:
  13998. case Module(ss):
  13999. env = {}
  14000. self.interp_stmts(ss, env)
  14001. if 'main' in env.keys():
  14002. self.apply_fun(env['main'], [], None)
  14003. case _:
  14004. raise Exception('interp: unexpected ' + repr(p))
  14005. \end{lstlisting}
  14006. \fi}
  14007. \end{tcolorbox}
  14008. \caption{Interpreter for the \LangFun{} language.}
  14009. \label{fig:interp-Lfun}
  14010. \end{figure}
  14011. %\margincomment{TODO: explain type checker}
  14012. The type checker for \LangFun{} is shown in
  14013. figure~\ref{fig:type-check-Lfun}.
  14014. %
  14015. \python{(We omit the code that parses function parameters into the
  14016. simpler abstract syntax.)}
  14017. %
  14018. Similarly to the interpreter, the case for the
  14019. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14020. %
  14021. AST is responsible for setting up the mutual recursion between the
  14022. top-level function definitions. We begin by creating a mapping
  14023. \code{env} from every function name to its type. We then type check
  14024. the program using this mapping.
  14025. %
  14026. \python{To check a function definition, we copy and extend the
  14027. \code{env} with the parameters of the function. We then type check
  14028. the body of the function and obtain the actual return type
  14029. \code{rt}, which is either the type of the expression in a
  14030. \code{return} statement, or the \code{VoidType} if control reaches
  14031. the end of the function without a \code{return} statement. (If
  14032. there are multiple \code{return} statements, the types of their
  14033. expressions must agree.) Finally we check that the actual return
  14034. type \code{rt} is equal to the declared return type \code{returns}.}
  14035. %
  14036. To check a function \racket{application}\python{call}, we match
  14037. the type of the function expression to a function type and check that
  14038. the types of the argument expressions are equal to the function's
  14039. parameter types. The type of the \racket{application}\python{call} as
  14040. a whole is the return type from the function type.
  14041. \begin{figure}[tp]
  14042. \begin{tcolorbox}[colback=white]
  14043. {\if\edition\racketEd
  14044. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14045. (define type-check-Lfun-class
  14046. (class type-check-Lvec-class
  14047. (super-new)
  14048. (inherit check-type-equal?)
  14049. (define/public (type-check-apply env e es)
  14050. (define-values (e^ ty) ((type-check-exp env) e))
  14051. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14052. ((type-check-exp env) e)))
  14053. (match ty
  14054. [`(,ty^* ... -> ,rt)
  14055. (for ([arg-ty ty*] [param-ty ty^*])
  14056. (check-type-equal? arg-ty param-ty (Apply e es)))
  14057. (values e^ e* rt)]))
  14058. (define/override (type-check-exp env)
  14059. (lambda (e)
  14060. (match e
  14061. [(FunRef f n)
  14062. (values (FunRef f n) (dict-ref env f))]
  14063. [(Apply e es)
  14064. (define-values (e^ es^ rt) (type-check-apply env e es))
  14065. (values (Apply e^ es^) rt)]
  14066. [(Call e es)
  14067. (define-values (e^ es^ rt) (type-check-apply env e es))
  14068. (values (Call e^ es^) rt)]
  14069. [else ((super type-check-exp env) e)])))
  14070. (define/public (type-check-def env)
  14071. (lambda (e)
  14072. (match e
  14073. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14074. (define new-env (append (map cons xs ps) env))
  14075. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14076. (check-type-equal? ty^ rt body)
  14077. (Def f p:t* rt info body^)])))
  14078. (define/public (fun-def-type d)
  14079. (match d
  14080. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14081. (define/override (type-check-program e)
  14082. (match e
  14083. [(ProgramDefsExp info ds body)
  14084. (define env (for/list ([d ds])
  14085. (cons (Def-name d) (fun-def-type d))))
  14086. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14087. (define-values (body^ ty) ((type-check-exp env) body))
  14088. (check-type-equal? ty 'Integer body)
  14089. (ProgramDefsExp info ds^ body^)]))))
  14090. (define (type-check-Lfun p)
  14091. (send (new type-check-Lfun-class) type-check-program p))
  14092. \end{lstlisting}
  14093. \fi}
  14094. {\if\edition\pythonEd\pythonColor
  14095. \begin{lstlisting}
  14096. class TypeCheckLfun(TypeCheckLtup):
  14097. def type_check_exp(self, e, env):
  14098. match e:
  14099. case Call(Name('input_int'), []):
  14100. return super().type_check_exp(e, env)
  14101. case Call(func, args):
  14102. func_t = self.type_check_exp(func, env)
  14103. args_t = [self.type_check_exp(arg, env) for arg in args]
  14104. match func_t:
  14105. case FunctionType(params_t, return_t):
  14106. for (arg_t, param_t) in zip(args_t, params_t):
  14107. check_type_equal(param_t, arg_t, e)
  14108. return return_t
  14109. case _:
  14110. raise Exception('type_check_exp: in call, unexpected ' +
  14111. repr(func_t))
  14112. case _:
  14113. return super().type_check_exp(e, env)
  14114. def type_check_stmts(self, ss, env):
  14115. if len(ss) == 0:
  14116. return VoidType()
  14117. match ss[0]:
  14118. case FunctionDef(name, params, body, dl, returns, comment):
  14119. new_env = env.copy().update(params)
  14120. rt = self.type_check_stmts(body, new_env)
  14121. check_type_equal(returns, rt, ss[0])
  14122. return self.type_check_stmts(ss[1:], env)
  14123. case Return(value):
  14124. return self.type_check_exp(value, env)
  14125. case _:
  14126. return super().type_check_stmts(ss, env)
  14127. def type_check(self, p):
  14128. match p:
  14129. case Module(body):
  14130. env = {}
  14131. for s in body:
  14132. match s:
  14133. case FunctionDef(name, params, bod, dl, returns, comment):
  14134. if name in env:
  14135. raise Exception('type_check: function ' +
  14136. repr(name) + ' defined twice')
  14137. params_t = [t for (x,t) in params]
  14138. env[name] = FunctionType(params_t, returns)
  14139. self.type_check_stmts(body, env)
  14140. case _:
  14141. raise Exception('type_check: unexpected ' + repr(p))
  14142. \end{lstlisting}
  14143. \fi}
  14144. \end{tcolorbox}
  14145. \caption{Type checker for the \LangFun{} language.}
  14146. \label{fig:type-check-Lfun}
  14147. \end{figure}
  14148. \clearpage
  14149. \section{Functions in x86}
  14150. \label{sec:fun-x86}
  14151. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14152. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14153. %% \margincomment{\tiny Talk about the return address on the
  14154. %% stack and what callq and retq does.\\ --Jeremy }
  14155. The x86 architecture provides a few features to support the
  14156. implementation of functions. We have already seen that there are
  14157. labels in x86 so that one can refer to the location of an instruction,
  14158. as is needed for jump instructions. Labels can also be used to mark
  14159. the beginning of the instructions for a function. Going further, we
  14160. can obtain the address of a label by using the \key{leaq}
  14161. instruction. For example, the following puts the address of the
  14162. \code{inc} label into the \code{rbx} register:
  14163. \begin{lstlisting}
  14164. leaq inc(%rip), %rbx
  14165. \end{lstlisting}
  14166. Recall from section~\ref{sec:select-instructions-gc} that
  14167. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14168. addressing.
  14169. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14170. to functions whose locations were given by a label, such as
  14171. \code{read\_int}. To support function calls in this chapter we instead
  14172. jump to functions whose location are given by an address in
  14173. a register; that is, we use \emph{indirect function calls}. The
  14174. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14175. before the register name.\index{subject}{indirect function call}
  14176. \begin{lstlisting}
  14177. callq *%rbx
  14178. \end{lstlisting}
  14179. \subsection{Calling Conventions}
  14180. \label{sec:calling-conventions-fun}
  14181. \index{subject}{calling conventions}
  14182. The \code{callq} instruction provides partial support for implementing
  14183. functions: it pushes the return address on the stack and it jumps to
  14184. the target. However, \code{callq} does not handle
  14185. \begin{enumerate}
  14186. \item parameter passing,
  14187. \item pushing frames on the procedure call stack and popping them off,
  14188. or
  14189. \item determining how registers are shared by different functions.
  14190. \end{enumerate}
  14191. Regarding parameter passing, recall that the x86-64 calling
  14192. convention for Unix-based systems uses the following six registers to
  14193. pass arguments to a function, in the given order:
  14194. \begin{lstlisting}
  14195. rdi rsi rdx rcx r8 r9
  14196. \end{lstlisting}
  14197. If there are more than six arguments, then the calling convention
  14198. mandates using space on the frame of the caller for the rest of the
  14199. arguments. However, to ease the implementation of efficient tail calls
  14200. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14201. arguments.
  14202. %
  14203. The return value of the function is stored in register \code{rax}.
  14204. Regarding frames \index{subject}{frame} and the procedure call stack,
  14205. \index{subject}{procedure call stack} recall from
  14206. section~\ref{sec:x86} that the stack grows down and each function call
  14207. uses a chunk of space on the stack called a frame. The caller sets the
  14208. stack pointer, register \code{rsp}, to the last data item in its
  14209. frame. The callee must not change anything in the caller's frame, that
  14210. is, anything that is at or above the stack pointer. The callee is free
  14211. to use locations that are below the stack pointer.
  14212. Recall that we store variables of tuple type on the root stack. So,
  14213. the prelude\index{subject}{prelude} of a function needs to move the
  14214. root stack pointer \code{r15} up according to the number of variables
  14215. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14216. move the root stack pointer back down. Also, the prelude must
  14217. initialize to \code{0} this frame's slots in the root stack to signal
  14218. to the garbage collector that those slots do not yet contain a valid
  14219. pointer. Otherwise the garbage collector will interpret the garbage
  14220. bits in those slots as memory addresses and try to traverse them,
  14221. causing serious mayhem!
  14222. Regarding the sharing of registers between different functions, recall
  14223. from section~\ref{sec:calling-conventions} that the registers are
  14224. divided into two groups, the caller-saved registers and the
  14225. callee-saved registers. The caller should assume that all the
  14226. caller-saved registers are overwritten with arbitrary values by the
  14227. callee. For that reason we recommend in
  14228. section~\ref{sec:calling-conventions} that variables that are live
  14229. during a function call should not be assigned to caller-saved
  14230. registers.
  14231. On the flip side, if the callee wants to use a callee-saved register,
  14232. the callee must save the contents of those registers on their stack
  14233. frame and then put them back prior to returning to the caller. For
  14234. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14235. the register allocator assigns a variable to a callee-saved register,
  14236. then the prelude of the \code{main} function must save that register
  14237. to the stack and the conclusion of \code{main} must restore it. This
  14238. recommendation now generalizes to all functions.
  14239. Recall that the base pointer, register \code{rbp}, is used as a
  14240. point of reference within a frame, so that each local variable can be
  14241. accessed at a fixed offset from the base pointer
  14242. (section~\ref{sec:x86}).
  14243. %
  14244. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14245. frames.
  14246. \begin{figure}[tbp]
  14247. \centering
  14248. \begin{tcolorbox}[colback=white]
  14249. \begin{tabular}{r|r|l|l} \hline
  14250. Caller View & Callee View & Contents & Frame \\ \hline
  14251. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14252. 0(\key{\%rbp}) & & old \key{rbp} \\
  14253. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14254. \ldots & & \ldots \\
  14255. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14256. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14257. \ldots & & \ldots \\
  14258. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14259. %% & & \\
  14260. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14261. %% & \ldots & \ldots \\
  14262. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14263. \hline
  14264. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14265. & 0(\key{\%rbp}) & old \key{rbp} \\
  14266. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14267. & \ldots & \ldots \\
  14268. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14269. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14270. & \ldots & \ldots \\
  14271. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14272. \end{tabular}
  14273. \end{tcolorbox}
  14274. \caption{Memory layout of caller and callee frames.}
  14275. \label{fig:call-frames}
  14276. \end{figure}
  14277. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14278. %% local variables and for storing the values of callee-saved registers
  14279. %% (we shall refer to all of these collectively as ``locals''), and that
  14280. %% at the beginning of a function we move the stack pointer \code{rsp}
  14281. %% down to make room for them.
  14282. %% We recommend storing the local variables
  14283. %% first and then the callee-saved registers, so that the local variables
  14284. %% can be accessed using \code{rbp} the same as before the addition of
  14285. %% functions.
  14286. %% To make additional room for passing arguments, we shall
  14287. %% move the stack pointer even further down. We count how many stack
  14288. %% arguments are needed for each function call that occurs inside the
  14289. %% body of the function and find their maximum. Adding this number to the
  14290. %% number of locals gives us how much the \code{rsp} should be moved at
  14291. %% the beginning of the function. In preparation for a function call, we
  14292. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14293. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14294. %% so on.
  14295. %% Upon calling the function, the stack arguments are retrieved by the
  14296. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14297. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14298. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14299. %% the layout of the caller and callee frames. Notice how important it is
  14300. %% that we correctly compute the maximum number of arguments needed for
  14301. %% function calls; if that number is too small then the arguments and
  14302. %% local variables will smash into each other!
  14303. \subsection{Efficient Tail Calls}
  14304. \label{sec:tail-call}
  14305. In general, the amount of stack space used by a program is determined
  14306. by the longest chain of nested function calls. That is, if function
  14307. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14308. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14309. large if functions are recursive. However, in some cases we can
  14310. arrange to use only a constant amount of space for a long chain of
  14311. nested function calls.
  14312. A \emph{tail call}\index{subject}{tail call} is a function call that
  14313. happens as the last action in a function body. For example, in the
  14314. following program, the recursive call to \code{tail\_sum} is a tail
  14315. call:
  14316. \begin{center}
  14317. {\if\edition\racketEd
  14318. \begin{lstlisting}
  14319. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14320. (if (eq? n 0)
  14321. r
  14322. (tail_sum (- n 1) (+ n r))))
  14323. (+ (tail_sum 3 0) 36)
  14324. \end{lstlisting}
  14325. \fi}
  14326. {\if\edition\pythonEd\pythonColor
  14327. \begin{lstlisting}
  14328. def tail_sum(n : int, r : int) -> int:
  14329. if n == 0:
  14330. return r
  14331. else:
  14332. return tail_sum(n - 1, n + r)
  14333. print(tail_sum(3, 0) + 36)
  14334. \end{lstlisting}
  14335. \fi}
  14336. \end{center}
  14337. At a tail call, the frame of the caller is no longer needed, so we can
  14338. pop the caller's frame before making the tail
  14339. call. \index{subject}{frame} With this approach, a recursive function
  14340. that makes only tail calls ends up using a constant amount of stack
  14341. space. \racket{Functional languages like Racket rely heavily on
  14342. recursive functions, so the definition of Racket \emph{requires}
  14343. that all tail calls be optimized in this way.}
  14344. Some care is needed with regard to argument passing in tail calls. As
  14345. mentioned, for arguments beyond the sixth, the convention is to use
  14346. space in the caller's frame for passing arguments. However, for a
  14347. tail call we pop the caller's frame and can no longer use it. An
  14348. alternative is to use space in the callee's frame for passing
  14349. arguments. However, this option is also problematic because the caller
  14350. and callee's frames overlap in memory. As we begin to copy the
  14351. arguments from their sources in the caller's frame, the target
  14352. locations in the callee's frame might collide with the sources for
  14353. later arguments! We solve this problem by using the heap instead of
  14354. the stack for passing more than six arguments
  14355. (section~\ref{sec:limit-functions-r4}).
  14356. As mentioned, for a tail call we pop the caller's frame prior to
  14357. making the tail call. The instructions for popping a frame are the
  14358. instructions that we usually place in the conclusion of a
  14359. function. Thus, we also need to place such code immediately before
  14360. each tail call. These instructions include restoring the callee-saved
  14361. registers, so it is fortunate that the argument passing registers are
  14362. all caller-saved registers.
  14363. One note remains regarding which instruction to use to make the tail
  14364. call. When the callee is finished, it should not return to the current
  14365. function but instead return to the function that called the current
  14366. one. Thus, the return address that is already on the stack is the
  14367. right one, and we should not use \key{callq} to make the tail call
  14368. because that would overwrite the return address. Instead we simply use
  14369. the \key{jmp} instruction. As with the indirect function call, we write
  14370. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14371. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14372. jump target because the conclusion can overwrite just about everything
  14373. else.
  14374. \begin{lstlisting}
  14375. jmp *%rax
  14376. \end{lstlisting}
  14377. \section{Shrink \LangFun{}}
  14378. \label{sec:shrink-r4}
  14379. The \code{shrink} pass performs a minor modification to ease the
  14380. later passes. This pass introduces an explicit \code{main} function
  14381. that gobbles up all the top-level statements of the module.
  14382. %
  14383. \racket{It also changes the top \code{ProgramDefsExp} form to
  14384. \code{ProgramDefs}.}
  14385. {\if\edition\racketEd
  14386. \begin{lstlisting}
  14387. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14388. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14389. \end{lstlisting}
  14390. where $\itm{mainDef}$ is
  14391. \begin{lstlisting}
  14392. (Def 'main '() 'Integer '() |$\Exp'$|)
  14393. \end{lstlisting}
  14394. \fi}
  14395. {\if\edition\pythonEd\pythonColor
  14396. \begin{lstlisting}
  14397. Module(|$\Def\ldots\Stmt\ldots$|)
  14398. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14399. \end{lstlisting}
  14400. where $\itm{mainDef}$ is
  14401. \begin{lstlisting}
  14402. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14403. \end{lstlisting}
  14404. \fi}
  14405. \section{Reveal Functions and the \LangFunRef{} Language}
  14406. \label{sec:reveal-functions-r4}
  14407. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14408. in that it conflates the use of function names and local
  14409. variables. This is a problem because we need to compile the use of a
  14410. function name differently from the use of a local variable. In
  14411. particular, we use \code{leaq} to convert the function name (a label
  14412. in x86) to an address in a register. Thus, we create a new pass that
  14413. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14414. $n$ is the arity of the function.\python{\footnote{The arity is not
  14415. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14416. This pass is named \code{reveal\_functions} and the output language
  14417. is \LangFunRef{}.
  14418. %is defined in figure~\ref{fig:f1-syntax}.
  14419. %% The concrete syntax for a
  14420. %% function reference is $\CFUNREF{f}$.
  14421. %% \begin{figure}[tp]
  14422. %% \centering
  14423. %% \fbox{
  14424. %% \begin{minipage}{0.96\textwidth}
  14425. %% {\if\edition\racketEd
  14426. %% \[
  14427. %% \begin{array}{lcl}
  14428. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14429. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14430. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14431. %% \end{array}
  14432. %% \]
  14433. %% \fi}
  14434. %% {\if\edition\pythonEd\pythonColor
  14435. %% \[
  14436. %% \begin{array}{lcl}
  14437. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14438. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14439. %% \end{array}
  14440. %% \]
  14441. %% \fi}
  14442. %% \end{minipage}
  14443. %% }
  14444. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14445. %% (figure~\ref{fig:Lfun-syntax}).}
  14446. %% \label{fig:f1-syntax}
  14447. %% \end{figure}
  14448. %% Distinguishing between calls in tail position and non-tail position
  14449. %% requires the pass to have some notion of context. We recommend using
  14450. %% two mutually recursive functions, one for processing expressions in
  14451. %% tail position and another for the rest.
  14452. \racket{Placing this pass after \code{uniquify} will make sure that
  14453. there are no local variables and functions that share the same
  14454. name.}
  14455. %
  14456. The \code{reveal\_functions} pass should come before the
  14457. \code{remove\_complex\_operands} pass because function references
  14458. should be categorized as complex expressions.
  14459. \section{Limit Functions}
  14460. \label{sec:limit-functions-r4}
  14461. Recall that we wish to limit the number of function parameters to six
  14462. so that we do not need to use the stack for argument passing, which
  14463. makes it easier to implement efficient tail calls. However, because
  14464. the input language \LangFun{} supports arbitrary numbers of function
  14465. arguments, we have some work to do! The \code{limit\_functions} pass
  14466. transforms functions and function calls that involve more than six
  14467. arguments to pass the first five arguments as usual, but it packs the
  14468. rest of the arguments into a tuple and passes it as the sixth
  14469. argument.\footnote{The implementation this pass can be postponed to
  14470. last because you can test the rest of the passes on functions with
  14471. six or fewer parameters.}
  14472. Each function definition with seven or more parameters is transformed as
  14473. follows:
  14474. {\if\edition\racketEd
  14475. \begin{lstlisting}
  14476. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14477. |$\Rightarrow$|
  14478. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14479. \end{lstlisting}
  14480. \fi}
  14481. {\if\edition\pythonEd\pythonColor
  14482. \begin{lstlisting}
  14483. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14484. |$\Rightarrow$|
  14485. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14486. |$T_r$|, None, |$\itm{body}'$|, None)
  14487. \end{lstlisting}
  14488. \fi}
  14489. %
  14490. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14491. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14492. the $k$th element of the tuple, where $k = i - 6$.
  14493. %
  14494. {\if\edition\racketEd
  14495. \begin{lstlisting}
  14496. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14497. \end{lstlisting}
  14498. \fi}
  14499. {\if\edition\pythonEd\pythonColor
  14500. \begin{lstlisting}
  14501. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14502. \end{lstlisting}
  14503. \fi}
  14504. For function calls with too many arguments, the \code{limit\_functions}
  14505. pass transforms them in the following way:
  14506. \begin{tabular}{lll}
  14507. \begin{minipage}{0.3\textwidth}
  14508. {\if\edition\racketEd
  14509. \begin{lstlisting}
  14510. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14511. \end{lstlisting}
  14512. \fi}
  14513. {\if\edition\pythonEd\pythonColor
  14514. \begin{lstlisting}
  14515. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14516. \end{lstlisting}
  14517. \fi}
  14518. \end{minipage}
  14519. &
  14520. $\Rightarrow$
  14521. &
  14522. \begin{minipage}{0.5\textwidth}
  14523. {\if\edition\racketEd
  14524. \begin{lstlisting}
  14525. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14526. \end{lstlisting}
  14527. \fi}
  14528. {\if\edition\pythonEd\pythonColor
  14529. \begin{lstlisting}
  14530. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14531. \end{lstlisting}
  14532. \fi}
  14533. \end{minipage}
  14534. \end{tabular}
  14535. \section{Remove Complex Operands}
  14536. \label{sec:rco-r4}
  14537. The primary decisions to make for this pass are whether to classify
  14538. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14539. atomic or complex expressions. Recall that an atomic expression
  14540. ends up as an immediate argument of an x86 instruction. Function
  14541. application translates to a sequence of instructions, so
  14542. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14543. a complex expression. On the other hand, the arguments of
  14544. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14545. expressions.
  14546. %
  14547. Regarding \code{FunRef}, as discussed previously, the function label
  14548. needs to be converted to an address using the \code{leaq}
  14549. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14550. needs to be classified as a complex expression so that we generate an
  14551. assignment statement with a left-hand side that can serve as the
  14552. target of the \code{leaq}.
  14553. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14554. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14555. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14556. and augments programs to include a list of function definitions.
  14557. %
  14558. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14559. \newcommand{\LfunMonadASTRacket}{
  14560. \begin{array}{lcl}
  14561. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14562. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14563. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14564. \end{array}
  14565. }
  14566. \newcommand{\LfunMonadASTPython}{
  14567. \begin{array}{lcl}
  14568. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14569. \MID \key{TupleType}\LS\Type^+\RS\\
  14570. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14571. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14572. \Stmt &::=& \RETURN{\Exp} \\
  14573. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14574. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14575. \end{array}
  14576. }
  14577. \begin{figure}[tp]
  14578. \centering
  14579. \begin{tcolorbox}[colback=white]
  14580. \footnotesize
  14581. {\if\edition\racketEd
  14582. \[
  14583. \begin{array}{l}
  14584. \gray{\LvarMonadASTRacket} \\ \hline
  14585. \gray{\LifMonadASTRacket} \\ \hline
  14586. \gray{\LwhileMonadASTRacket} \\ \hline
  14587. \gray{\LtupMonadASTRacket} \\ \hline
  14588. \LfunMonadASTRacket \\
  14589. \begin{array}{rcl}
  14590. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14591. \end{array}
  14592. \end{array}
  14593. \]
  14594. \fi}
  14595. {\if\edition\pythonEd\pythonColor
  14596. \[
  14597. \begin{array}{l}
  14598. \gray{\LvarMonadASTPython} \\ \hline
  14599. \gray{\LifMonadASTPython} \\ \hline
  14600. \gray{\LwhileMonadASTPython} \\ \hline
  14601. \gray{\LtupMonadASTPython} \\ \hline
  14602. \LfunMonadASTPython \\
  14603. \begin{array}{rcl}
  14604. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14605. \end{array}
  14606. \end{array}
  14607. \]
  14608. \fi}
  14609. \end{tcolorbox}
  14610. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14611. \label{fig:Lfun-anf-syntax}
  14612. \end{figure}
  14613. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14614. %% \LangFunANF{} of this pass.
  14615. %% \begin{figure}[tp]
  14616. %% \centering
  14617. %% \fbox{
  14618. %% \begin{minipage}{0.96\textwidth}
  14619. %% \small
  14620. %% \[
  14621. %% \begin{array}{rcl}
  14622. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14623. %% \MID \VOID{} } \\
  14624. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14625. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14626. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14627. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14628. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14629. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14630. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14631. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14632. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14633. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14634. %% \end{array}
  14635. %% \]
  14636. %% \end{minipage}
  14637. %% }
  14638. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14639. %% \label{fig:Lfun-anf-syntax}
  14640. %% \end{figure}
  14641. \section{Explicate Control and the \LangCFun{} Language}
  14642. \label{sec:explicate-control-r4}
  14643. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14644. output of \code{explicate\_control}.
  14645. %
  14646. %% \racket{(The concrete syntax is given in
  14647. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14648. %
  14649. The auxiliary functions for assignment\racket{ and tail contexts} should
  14650. be updated with cases for
  14651. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14652. function for predicate context should be updated for
  14653. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14654. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14655. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14656. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14657. auxiliary function for processing function definitions. This code is
  14658. similar to the case for \code{Program} in \LangVec{}. The top-level
  14659. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14660. form of \LangFun{} can then apply this new function to all the
  14661. function definitions.
  14662. {\if\edition\pythonEd\pythonColor
  14663. The translation of \code{Return} statements requires a new auxiliary
  14664. function to handle expressions in tail context, called
  14665. \code{explicate\_tail}. The function should take an expression and the
  14666. dictionary of basic blocks and produce a list of statements in the
  14667. \LangCFun{} language. The \code{explicate\_tail} function should
  14668. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14669. and a default case for other kinds of expressions. The default case
  14670. should produce a \code{Return} statement. The case for \code{Call}
  14671. should change it into \code{TailCall}. The other cases should
  14672. recursively process their subexpressions and statements, choosing the
  14673. appropriate explicate functions for the various contexts.
  14674. \fi}
  14675. \newcommand{\CfunASTRacket}{
  14676. \begin{array}{lcl}
  14677. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14678. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14679. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14680. \end{array}
  14681. }
  14682. \newcommand{\CfunASTPython}{
  14683. \begin{array}{lcl}
  14684. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14685. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14686. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14687. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14688. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14689. \end{array}
  14690. }
  14691. \begin{figure}[tp]
  14692. \begin{tcolorbox}[colback=white]
  14693. \footnotesize
  14694. {\if\edition\racketEd
  14695. \[
  14696. \begin{array}{l}
  14697. \gray{\CvarASTRacket} \\ \hline
  14698. \gray{\CifASTRacket} \\ \hline
  14699. \gray{\CloopASTRacket} \\ \hline
  14700. \gray{\CtupASTRacket} \\ \hline
  14701. \CfunASTRacket \\
  14702. \begin{array}{lcl}
  14703. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14704. \end{array}
  14705. \end{array}
  14706. \]
  14707. \fi}
  14708. {\if\edition\pythonEd\pythonColor
  14709. \[
  14710. \begin{array}{l}
  14711. \gray{\CifASTPython} \\ \hline
  14712. \gray{\CtupASTPython} \\ \hline
  14713. \CfunASTPython \\
  14714. \begin{array}{lcl}
  14715. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14716. \end{array}
  14717. \end{array}
  14718. \]
  14719. \fi}
  14720. \end{tcolorbox}
  14721. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14722. \label{fig:c3-syntax}
  14723. \end{figure}
  14724. \clearpage
  14725. \section{Select Instructions and the \LangXIndCall{} Language}
  14726. \label{sec:select-r4}
  14727. \index{subject}{select instructions}
  14728. The output of select instructions is a program in the \LangXIndCall{}
  14729. language; the definition of its concrete syntax is shown in
  14730. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14731. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14732. directive on the labels of function definitions to make sure the
  14733. bottom three bits are zero, which we put to use in
  14734. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14735. this section. \index{subject}{x86}
  14736. \newcommand{\GrammarXIndCall}{
  14737. \begin{array}{lcl}
  14738. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14739. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14740. \Block &::= & \Instr^{+} \\
  14741. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14742. \end{array}
  14743. }
  14744. \newcommand{\ASTXIndCallRacket}{
  14745. \begin{array}{lcl}
  14746. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14747. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14748. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14749. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14750. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14751. \end{array}
  14752. }
  14753. \begin{figure}[tp]
  14754. \begin{tcolorbox}[colback=white]
  14755. \small
  14756. \[
  14757. \begin{array}{l}
  14758. \gray{\GrammarXInt} \\ \hline
  14759. \gray{\GrammarXIf} \\ \hline
  14760. \gray{\GrammarXGlobal} \\ \hline
  14761. \GrammarXIndCall \\
  14762. \begin{array}{lcl}
  14763. \LangXIndCallM{} &::= & \Def^{*}
  14764. \end{array}
  14765. \end{array}
  14766. \]
  14767. \end{tcolorbox}
  14768. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14769. \label{fig:x86-3-concrete}
  14770. \end{figure}
  14771. \begin{figure}[tp]
  14772. \begin{tcolorbox}[colback=white]
  14773. \small
  14774. {\if\edition\racketEd
  14775. \[\arraycolsep=3pt
  14776. \begin{array}{l}
  14777. \gray{\ASTXIntRacket} \\ \hline
  14778. \gray{\ASTXIfRacket} \\ \hline
  14779. \gray{\ASTXGlobalRacket} \\ \hline
  14780. \ASTXIndCallRacket \\
  14781. \begin{array}{lcl}
  14782. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14783. \end{array}
  14784. \end{array}
  14785. \]
  14786. \fi}
  14787. {\if\edition\pythonEd\pythonColor
  14788. \[
  14789. \begin{array}{lcl}
  14790. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14791. \MID \BYTEREG{\Reg} } \\
  14792. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14793. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14794. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14795. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14796. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14797. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14798. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14799. \end{array}
  14800. \]
  14801. \fi}
  14802. \end{tcolorbox}
  14803. \caption{The abstract syntax of \LangXIndCall{} (extends
  14804. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14805. \label{fig:x86-3}
  14806. \end{figure}
  14807. An assignment of a function reference to a variable becomes a
  14808. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14809. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14810. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14811. node, whose concrete syntax is instruction-pointer-relative
  14812. addressing.
  14813. \begin{center}
  14814. \begin{tabular}{lcl}
  14815. \begin{minipage}{0.35\textwidth}
  14816. {\if\edition\racketEd
  14817. \begin{lstlisting}
  14818. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14819. \end{lstlisting}
  14820. \fi}
  14821. {\if\edition\pythonEd\pythonColor
  14822. \begin{lstlisting}
  14823. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14824. \end{lstlisting}
  14825. \fi}
  14826. \end{minipage}
  14827. &
  14828. $\Rightarrow$\qquad\qquad
  14829. &
  14830. \begin{minipage}{0.3\textwidth}
  14831. \begin{lstlisting}
  14832. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14833. \end{lstlisting}
  14834. \end{minipage}
  14835. \end{tabular}
  14836. \end{center}
  14837. Regarding function definitions, we need to remove the parameters and
  14838. instead perform parameter passing using the conventions discussed in
  14839. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14840. registers. We recommend turning the parameters into local variables
  14841. and generating instructions at the beginning of the function to move
  14842. from the argument-passing registers
  14843. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14844. {\if\edition\racketEd
  14845. \begin{lstlisting}
  14846. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14847. |$\Rightarrow$|
  14848. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14849. \end{lstlisting}
  14850. \fi}
  14851. {\if\edition\pythonEd\pythonColor
  14852. \begin{lstlisting}
  14853. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14854. |$\Rightarrow$|
  14855. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14856. \end{lstlisting}
  14857. \fi}
  14858. The basic blocks $B'$ are the same as $B$ except that the
  14859. \code{start} block is modified to add the instructions for moving from
  14860. the argument registers to the parameter variables. So the \code{start}
  14861. block of $B$ shown on the left of the following is changed to the code
  14862. on the right:
  14863. \begin{center}
  14864. \begin{minipage}{0.3\textwidth}
  14865. \begin{lstlisting}
  14866. start:
  14867. |$\itm{instr}_1$|
  14868. |$\cdots$|
  14869. |$\itm{instr}_n$|
  14870. \end{lstlisting}
  14871. \end{minipage}
  14872. $\Rightarrow$
  14873. \begin{minipage}{0.3\textwidth}
  14874. \begin{lstlisting}
  14875. |$f$|start:
  14876. movq %rdi, |$x_1$|
  14877. movq %rsi, |$x_2$|
  14878. |$\cdots$|
  14879. |$\itm{instr}_1$|
  14880. |$\cdots$|
  14881. |$\itm{instr}_n$|
  14882. \end{lstlisting}
  14883. \end{minipage}
  14884. \end{center}
  14885. Recall that we use the label \code{start} for the initial block of a
  14886. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14887. the conclusion of the program with \code{conclusion}, so that
  14888. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14889. by a jump to \code{conclusion}. With the addition of function
  14890. definitions, there is a start block and conclusion for each function,
  14891. but their labels need to be unique. We recommend prepending the
  14892. function's name to \code{start} and \code{conclusion}, respectively,
  14893. to obtain unique labels.
  14894. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14895. number of parameters the function expects, but the parameters are no
  14896. longer in the syntax of function definitions. Instead, add an entry
  14897. to $\itm{info}$ that maps \code{num-params} to the number of
  14898. parameters to construct $\itm{info}'$.}
  14899. By changing the parameters to local variables, we are giving the
  14900. register allocator control over which registers or stack locations to
  14901. use for them. If you implement the move-biasing challenge
  14902. (section~\ref{sec:move-biasing}), the register allocator will try to
  14903. assign the parameter variables to the corresponding argument register,
  14904. in which case the \code{patch\_instructions} pass will remove the
  14905. \code{movq} instruction. This happens in the example translation given
  14906. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14907. the \code{add} function.
  14908. %
  14909. Also, note that the register allocator will perform liveness analysis
  14910. on this sequence of move instructions and build the interference
  14911. graph. So, for example, $x_1$ will be marked as interfering with
  14912. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14913. which is good because otherwise the first \code{movq} would overwrite
  14914. the argument in \code{rsi} that is needed for $x_2$.
  14915. Next, consider the compilation of function calls. In the mirror image
  14916. of the handling of parameters in function definitions, the arguments
  14917. are moved to the argument-passing registers. Note that the function
  14918. is not given as a label, but its address is produced by the argument
  14919. $\itm{arg}_0$. So, we translate the call into an indirect function
  14920. call. The return value from the function is stored in \code{rax}, so
  14921. it needs to be moved into the \itm{lhs}.
  14922. \begin{lstlisting}
  14923. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14924. |$\Rightarrow$|
  14925. movq |$\itm{arg}_1$|, %rdi
  14926. movq |$\itm{arg}_2$|, %rsi
  14927. |$\vdots$|
  14928. callq *|$\itm{arg}_0$|
  14929. movq %rax, |$\itm{lhs}$|
  14930. \end{lstlisting}
  14931. The \code{IndirectCallq} AST node includes an integer for the arity of
  14932. the function, that is, the number of parameters. That information is
  14933. useful in the \code{uncover\_live} pass for determining which
  14934. argument-passing registers are potentially read during the call.
  14935. For tail calls, the parameter passing is the same as non-tail calls:
  14936. generate instructions to move the arguments into the argument-passing
  14937. registers. After that we need to pop the frame from the procedure
  14938. call stack. However, we do not yet know how big the frame is; that
  14939. gets determined during register allocation. So, instead of generating
  14940. those instructions here, we invent a new instruction that means ``pop
  14941. the frame and then do an indirect jump,'' which we name
  14942. \code{TailJmp}. The abstract syntax for this instruction includes an
  14943. argument that specifies where to jump and an integer that represents
  14944. the arity of the function being called.
  14945. \section{Register Allocation}
  14946. \label{sec:register-allocation-r4}
  14947. The addition of functions requires some changes to all three aspects
  14948. of register allocation, which we discuss in the following subsections.
  14949. \subsection{Liveness Analysis}
  14950. \label{sec:liveness-analysis-r4}
  14951. \index{subject}{liveness analysis}
  14952. %% The rest of the passes need only minor modifications to handle the new
  14953. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14954. %% \code{leaq}.
  14955. The \code{IndirectCallq} instruction should be treated like
  14956. \code{Callq} regarding its written locations $W$, in that they should
  14957. include all the caller-saved registers. Recall that the reason for
  14958. that is to force variables that are live across a function call to be assigned to callee-saved
  14959. registers or to be spilled to the stack.
  14960. Regarding the set of read locations $R$, the arity fields of
  14961. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14962. argument-passing registers should be considered as read by those
  14963. instructions. Also, the target field of \code{TailJmp} and
  14964. \code{IndirectCallq} should be included in the set of read locations
  14965. $R$.
  14966. \subsection{Build Interference Graph}
  14967. \label{sec:build-interference-r4}
  14968. With the addition of function definitions, we compute a separate interference
  14969. graph for each function (not just one for the whole program).
  14970. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14971. spill tuple-typed variables that are live during a call to
  14972. \code{collect}, the garbage collector. With the addition of functions
  14973. to our language, we need to revisit this issue. Functions that perform
  14974. allocation contain calls to the collector. Thus, we should not only
  14975. spill a tuple-typed variable when it is live during a call to
  14976. \code{collect}, but we should spill the variable if it is live during
  14977. a call to any user-defined function. Thus, in the
  14978. \code{build\_interference} pass, we recommend adding interference
  14979. edges between call-live tuple-typed variables and the callee-saved
  14980. registers (in addition to creating edges between
  14981. call-live variables and the caller-saved registers).
  14982. \subsection{Allocate Registers}
  14983. The primary change to the \code{allocate\_registers} pass is adding an
  14984. auxiliary function for handling definitions (the \Def{} nonterminal
  14985. shown in figure~\ref{fig:x86-3}) with one case for function
  14986. definitions. The logic is the same as described in
  14987. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14988. allocation is performed many times, once for each function definition,
  14989. instead of just once for the whole program.
  14990. \section{Patch Instructions}
  14991. In \code{patch\_instructions}, you should deal with the x86
  14992. idiosyncrasy that the destination argument of \code{leaq} must be a
  14993. register. Additionally, you should ensure that the argument of
  14994. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14995. trample many other registers before the tail call, as explained in the
  14996. next section.
  14997. \section{Generate Prelude and Conclusion}
  14998. Now that register allocation is complete, we can translate the
  14999. \code{TailJmp} into a sequence of instructions. A naive translation of
  15000. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15001. before the jump we need to pop the current frame to achieve efficient
  15002. tail calls. This sequence of instructions is the same as the code for
  15003. the conclusion of a function, except that the \code{retq} is replaced with
  15004. \code{jmp *$\itm{arg}$}.
  15005. Regarding function definitions, we generate a prelude and conclusion
  15006. for each one. This code is similar to the prelude and conclusion
  15007. generated for the \code{main} function presented in
  15008. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15009. carry out the following steps:
  15010. % TODO: .align the functions!
  15011. \begin{enumerate}
  15012. %% \item Start with \code{.global} and \code{.align} directives followed
  15013. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15014. %% example.)
  15015. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15016. pointer.
  15017. \item Push to the stack all the callee-saved registers that were
  15018. used for register allocation.
  15019. \item Move the stack pointer \code{rsp} down to make room for the
  15020. regular spills (aligned to 16 bytes).
  15021. \item Move the root stack pointer \code{r15} up by the size of the
  15022. root-stack frame for this function, which depends on the number of
  15023. spilled tuple-typed variables. \label{root-stack-init}
  15024. \item Initialize to zero all new entries in the root-stack frame.
  15025. \item Jump to the start block.
  15026. \end{enumerate}
  15027. The prelude of the \code{main} function has an additional task: call
  15028. the \code{initialize} function to set up the garbage collector, and
  15029. then move the value of the global \code{rootstack\_begin} in
  15030. \code{r15}. This initialization should happen before step
  15031. \ref{root-stack-init}, which depends on \code{r15}.
  15032. The conclusion of every function should do the following:
  15033. \begin{enumerate}
  15034. \item Move the stack pointer back up past the regular spills.
  15035. \item Restore the callee-saved registers by popping them from the
  15036. stack.
  15037. \item Move the root stack pointer back down by the size of the
  15038. root-stack frame for this function.
  15039. \item Restore \code{rbp} by popping it from the stack.
  15040. \item Return to the caller with the \code{retq} instruction.
  15041. \end{enumerate}
  15042. The output of this pass is \LangXIndCallFlat{}, which differs from
  15043. \LangXIndCall{} in that there is no longer an AST node for function
  15044. definitions. Instead, a program is just
  15045. \racket{an association list}\python{a dictionary}
  15046. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15047. {\if\edition\racketEd
  15048. \[
  15049. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15050. \]
  15051. \fi}
  15052. {\if\edition\pythonEd
  15053. \[
  15054. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15055. \]
  15056. \fi}
  15057. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15058. compiling \LangFun{} to x86.
  15059. \begin{exercise}\normalfont\normalsize
  15060. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15061. Create eight new programs that use functions including examples that
  15062. pass functions and return functions from other functions, recursive
  15063. functions, functions that create tuples, and functions that make tail
  15064. calls. Test your compiler on these new programs and all your
  15065. previously created test programs.
  15066. \end{exercise}
  15067. \begin{figure}[tbp]
  15068. \begin{tcolorbox}[colback=white]
  15069. {\if\edition\racketEd
  15070. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15071. \node (Lfun) at (0,2) {\large \LangFun{}};
  15072. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15073. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15074. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15075. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15076. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15077. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15078. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15079. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15080. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15081. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15082. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15083. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15084. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15085. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15086. \path[->,bend left=15] (Lfun) edge [above] node
  15087. {\ttfamily\footnotesize shrink} (Lfun-1);
  15088. \path[->,bend left=15] (Lfun-1) edge [above] node
  15089. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15090. \path[->,bend left=15] (Lfun-2) edge [above] node
  15091. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15092. \path[->,bend left=15] (F1-1) edge [left] node
  15093. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15094. \path[->,bend left=15] (F1-2) edge [below] node
  15095. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15096. \path[->,bend left=15] (F1-3) edge [below] node
  15097. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15098. \path[->,bend right=15] (F1-4) edge [above] node
  15099. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15100. \path[->,bend right=15] (F1-5) edge [right] node
  15101. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15102. \path[->,bend right=15] (C3-2) edge [right] node
  15103. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15104. \path[->,bend left=15] (x86-2) edge [right] node
  15105. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15106. \path[->,bend right=15] (x86-2-1) edge [below] node
  15107. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15108. \path[->,bend right=15] (x86-2-2) edge [right] node
  15109. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15110. \path[->,bend left=15] (x86-3) edge [above] node
  15111. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15112. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15113. \end{tikzpicture}
  15114. \fi}
  15115. {\if\edition\pythonEd\pythonColor
  15116. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15117. \node (Lfun) at (0,2) {\large \LangFun{}};
  15118. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15119. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15120. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15121. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15122. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15123. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15124. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15125. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15126. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15127. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15128. \path[->,bend left=15] (Lfun) edge [above] node
  15129. {\ttfamily\footnotesize shrink} (Lfun-2);
  15130. \path[->,bend left=15] (Lfun-2) edge [above] node
  15131. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15132. \path[->,bend left=15] (F1-1) edge [above] node
  15133. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15134. \path[->,bend left=15] (F1-2) edge [right] node
  15135. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15136. \path[->,bend right=15] (F1-4) edge [above] node
  15137. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15138. \path[->,bend right=15] (F1-5) edge [right] node
  15139. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15140. \path[->,bend left=15] (C3-2) edge [right] node
  15141. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15142. \path[->,bend right=15] (x86-2) edge [below] node
  15143. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15144. \path[->,bend left=15] (x86-3) edge [above] node
  15145. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15146. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15147. \end{tikzpicture}
  15148. \fi}
  15149. \end{tcolorbox}
  15150. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15151. \label{fig:Lfun-passes}
  15152. \end{figure}
  15153. \section{An Example Translation}
  15154. \label{sec:functions-example}
  15155. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15156. function in \LangFun{} to x86. The figure includes the results of
  15157. \code{explicate\_control} and \code{select\_instructions}.
  15158. \begin{figure}[hbtp]
  15159. \begin{tcolorbox}[colback=white]
  15160. \begin{tabular}{ll}
  15161. \begin{minipage}{0.4\textwidth}
  15162. % s3_2.rkt
  15163. {\if\edition\racketEd
  15164. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15165. (define (add [x : Integer]
  15166. [y : Integer])
  15167. : Integer
  15168. (+ x y))
  15169. (add 40 2)
  15170. \end{lstlisting}
  15171. \fi}
  15172. {\if\edition\pythonEd\pythonColor
  15173. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15174. def add(x:int, y:int) -> int:
  15175. return x + y
  15176. print(add(40, 2))
  15177. \end{lstlisting}
  15178. \fi}
  15179. $\Downarrow$
  15180. {\if\edition\racketEd
  15181. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15182. (define (add86 [x87 : Integer]
  15183. [y88 : Integer])
  15184. : Integer
  15185. add86start:
  15186. return (+ x87 y88);
  15187. )
  15188. (define (main) : Integer ()
  15189. mainstart:
  15190. tmp89 = (fun-ref add86 2);
  15191. (tail-call tmp89 40 2)
  15192. )
  15193. \end{lstlisting}
  15194. \fi}
  15195. {\if\edition\pythonEd\pythonColor
  15196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15197. def add(x:int, y:int) -> int:
  15198. addstart:
  15199. return x + y
  15200. def main() -> int:
  15201. mainstart:
  15202. fun.0 = add
  15203. tmp.1 = fun.0(40, 2)
  15204. print(tmp.1)
  15205. return 0
  15206. \end{lstlisting}
  15207. \fi}
  15208. \end{minipage}
  15209. &
  15210. $\Rightarrow$
  15211. \begin{minipage}{0.5\textwidth}
  15212. {\if\edition\racketEd
  15213. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15214. (define (add86) : Integer
  15215. add86start:
  15216. movq %rdi, x87
  15217. movq %rsi, y88
  15218. movq x87, %rax
  15219. addq y88, %rax
  15220. jmp inc1389conclusion
  15221. )
  15222. (define (main) : Integer
  15223. mainstart:
  15224. leaq (fun-ref add86 2), tmp89
  15225. movq $40, %rdi
  15226. movq $2, %rsi
  15227. tail-jmp tmp89
  15228. )
  15229. \end{lstlisting}
  15230. \fi}
  15231. {\if\edition\pythonEd\pythonColor
  15232. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15233. def add() -> int:
  15234. addstart:
  15235. movq %rdi, x
  15236. movq %rsi, y
  15237. movq x, %rax
  15238. addq y, %rax
  15239. jmp addconclusion
  15240. def main() -> int:
  15241. mainstart:
  15242. leaq add, fun.0
  15243. movq $40, %rdi
  15244. movq $2, %rsi
  15245. callq *fun.0
  15246. movq %rax, tmp.1
  15247. movq tmp.1, %rdi
  15248. callq print_int
  15249. movq $0, %rax
  15250. jmp mainconclusion
  15251. \end{lstlisting}
  15252. \fi}
  15253. $\Downarrow$
  15254. \end{minipage}
  15255. \end{tabular}
  15256. \begin{tabular}{ll}
  15257. \begin{minipage}{0.3\textwidth}
  15258. {\if\edition\racketEd
  15259. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15260. .globl add86
  15261. .align 8
  15262. add86:
  15263. pushq %rbp
  15264. movq %rsp, %rbp
  15265. jmp add86start
  15266. add86start:
  15267. movq %rdi, %rax
  15268. addq %rsi, %rax
  15269. jmp add86conclusion
  15270. add86conclusion:
  15271. popq %rbp
  15272. retq
  15273. \end{lstlisting}
  15274. \fi}
  15275. {\if\edition\pythonEd\pythonColor
  15276. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15277. .align 8
  15278. add:
  15279. pushq %rbp
  15280. movq %rsp, %rbp
  15281. subq $0, %rsp
  15282. jmp addstart
  15283. addstart:
  15284. movq %rdi, %rdx
  15285. movq %rsi, %rcx
  15286. movq %rdx, %rax
  15287. addq %rcx, %rax
  15288. jmp addconclusion
  15289. addconclusion:
  15290. subq $0, %r15
  15291. addq $0, %rsp
  15292. popq %rbp
  15293. retq
  15294. \end{lstlisting}
  15295. \fi}
  15296. \end{minipage}
  15297. &
  15298. \begin{minipage}{0.5\textwidth}
  15299. {\if\edition\racketEd
  15300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15301. .globl main
  15302. .align 8
  15303. main:
  15304. pushq %rbp
  15305. movq %rsp, %rbp
  15306. movq $16384, %rdi
  15307. movq $16384, %rsi
  15308. callq initialize
  15309. movq rootstack_begin(%rip), %r15
  15310. jmp mainstart
  15311. mainstart:
  15312. leaq add86(%rip), %rcx
  15313. movq $40, %rdi
  15314. movq $2, %rsi
  15315. movq %rcx, %rax
  15316. popq %rbp
  15317. jmp *%rax
  15318. mainconclusion:
  15319. popq %rbp
  15320. retq
  15321. \end{lstlisting}
  15322. \fi}
  15323. {\if\edition\pythonEd\pythonColor
  15324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15325. .globl main
  15326. .align 8
  15327. main:
  15328. pushq %rbp
  15329. movq %rsp, %rbp
  15330. subq $0, %rsp
  15331. movq $65536, %rdi
  15332. movq $65536, %rsi
  15333. callq initialize
  15334. movq rootstack_begin(%rip), %r15
  15335. jmp mainstart
  15336. mainstart:
  15337. leaq add(%rip), %rcx
  15338. movq $40, %rdi
  15339. movq $2, %rsi
  15340. callq *%rcx
  15341. movq %rax, %rcx
  15342. movq %rcx, %rdi
  15343. callq print_int
  15344. movq $0, %rax
  15345. jmp mainconclusion
  15346. mainconclusion:
  15347. subq $0, %r15
  15348. addq $0, %rsp
  15349. popq %rbp
  15350. retq
  15351. \end{lstlisting}
  15352. \fi}
  15353. \end{minipage}
  15354. \end{tabular}
  15355. \end{tcolorbox}
  15356. \caption{Example compilation of a simple function to x86.}
  15357. \label{fig:add-fun}
  15358. \end{figure}
  15359. % Challenge idea: inlining! (simple version)
  15360. % Further Reading
  15361. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15362. \chapter{Lexically Scoped Functions}
  15363. \label{ch:Llambda}
  15364. \setcounter{footnote}{0}
  15365. This chapter studies lexically scoped functions. Lexical
  15366. scoping\index{subject}{lexical scoping} means that a function's body
  15367. may refer to variables whose binding site is outside of the function,
  15368. in an enclosing scope.
  15369. %
  15370. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15371. in \LangLam{}, which extends \LangFun{} with the
  15372. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15373. functions. The body of the \key{lambda} refers to three variables:
  15374. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15375. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15376. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15377. function \code{f}}, and \code{x} is a parameter of function
  15378. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15379. result value. The main expression of the program includes two calls to
  15380. \code{f} with different arguments for \code{x}: first \code{5} and
  15381. then \code{3}. The functions returned from \code{f} are bound to
  15382. variables \code{g} and \code{h}. Even though these two functions were
  15383. created by the same \code{lambda}, they are really different functions
  15384. because they use different values for \code{x}. Applying \code{g} to
  15385. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15386. produces \code{22}, so the result of the program is \code{42}.
  15387. \begin{figure}[btp]
  15388. \begin{tcolorbox}[colback=white]
  15389. {\if\edition\racketEd
  15390. % lambda_test_21.rkt
  15391. \begin{lstlisting}
  15392. (define (f [x : Integer]) : (Integer -> Integer)
  15393. (let ([y 4])
  15394. (lambda: ([z : Integer]) : Integer
  15395. (+ x (+ y z)))))
  15396. (let ([g (f 5)])
  15397. (let ([h (f 3)])
  15398. (+ (g 11) (h 15))))
  15399. \end{lstlisting}
  15400. \fi}
  15401. {\if\edition\pythonEd\pythonColor
  15402. \begin{lstlisting}
  15403. def f(x : int) -> Callable[[int], int]:
  15404. y = 4
  15405. return lambda z: x + y + z
  15406. g = f(5)
  15407. h = f(3)
  15408. print(g(11) + h(15))
  15409. \end{lstlisting}
  15410. \fi}
  15411. \end{tcolorbox}
  15412. \caption{Example of a lexically scoped function.}
  15413. \label{fig:lexical-scoping}
  15414. \end{figure}
  15415. The approach that we take for implementing lexically scoped functions
  15416. is to compile them into top-level function definitions, translating
  15417. from \LangLam{} into \LangFun{}. However, the compiler must give
  15418. special treatment to variable occurrences such as \code{x} and
  15419. \code{y} in the body of the \code{lambda} shown in
  15420. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15421. may not refer to variables defined outside of it. To identify such
  15422. variable occurrences, we review the standard notion of free variable.
  15423. \begin{definition}\normalfont
  15424. A variable is \emph{free in expression} $e$ if the variable occurs
  15425. inside $e$ but does not have an enclosing definition that is also in
  15426. $e$.\index{subject}{free variable}
  15427. \end{definition}
  15428. For example, in the expression
  15429. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15430. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15431. only \code{x} and \code{y} are free in the following expression,
  15432. because \code{z} is defined by the \code{lambda}
  15433. {\if\edition\racketEd
  15434. \begin{lstlisting}
  15435. (lambda: ([z : Integer]) : Integer
  15436. (+ x (+ y z)))
  15437. \end{lstlisting}
  15438. \fi}
  15439. {\if\edition\pythonEd\pythonColor
  15440. \begin{lstlisting}
  15441. lambda z: x + y + z
  15442. \end{lstlisting}
  15443. \fi}
  15444. %
  15445. \noindent Thus the free variables of a \code{lambda} are the ones that
  15446. need special treatment. We need to transport at runtime the values
  15447. of those variables from the point where the \code{lambda} was created
  15448. to the point where the \code{lambda} is applied. An efficient solution
  15449. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15450. values of the free variables together with a function pointer into a
  15451. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15452. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15453. closure}
  15454. %
  15455. By design, we have all the ingredients to make closures:
  15456. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15457. function pointers. The function pointer resides at index $0$, and the
  15458. values for the free variables fill in the rest of the tuple.
  15459. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15460. to see how closures work. It is a three-step dance. The program calls
  15461. function \code{f}, which creates a closure for the \code{lambda}. The
  15462. closure is a tuple whose first element is a pointer to the top-level
  15463. function that we will generate for the \code{lambda}; the second
  15464. element is the value of \code{x}, which is \code{5}; and the third
  15465. element is \code{4}, the value of \code{y}. The closure does not
  15466. contain an element for \code{z} because \code{z} is not a free
  15467. variable of the \code{lambda}. Creating the closure is step 1 of the
  15468. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15469. shown in figure~\ref{fig:closures}.
  15470. %
  15471. The second call to \code{f} creates another closure, this time with
  15472. \code{3} in the second slot (for \code{x}). This closure is also
  15473. returned from \code{f} but bound to \code{h}, which is also shown in
  15474. figure~\ref{fig:closures}.
  15475. \begin{figure}[tbp]
  15476. \centering
  15477. \begin{minipage}{0.65\textwidth}
  15478. \begin{tcolorbox}[colback=white]
  15479. \includegraphics[width=\textwidth]{figs/closures}
  15480. \end{tcolorbox}
  15481. \end{minipage}
  15482. \caption{Flat closure representations for the two functions
  15483. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15484. \label{fig:closures}
  15485. \end{figure}
  15486. Continuing with the example, consider the application of \code{g} to
  15487. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15488. closure, we obtain the function pointer from the first element of the
  15489. closure and call it, passing in the closure itself and then the
  15490. regular arguments, in this case \code{11}. This technique for applying
  15491. a closure is step 2 of the dance.
  15492. %
  15493. But doesn't this \code{lambda} take only one argument, for parameter
  15494. \code{z}? The third and final step of the dance is generating a
  15495. top-level function for a \code{lambda}. We add an additional
  15496. parameter for the closure and insert an initialization at the beginning
  15497. of the function for each free variable, to bind those variables to the
  15498. appropriate elements from the closure parameter.
  15499. %
  15500. This three-step dance is known as \emph{closure
  15501. conversion}\index{subject}{closure conversion}. We discuss the
  15502. details of closure conversion in section~\ref{sec:closure-conversion}
  15503. and show the code generated from the example in
  15504. section~\ref{sec:example-lambda}. First, we define the syntax and
  15505. semantics of \LangLam{} in section~\ref{sec:r5}.
  15506. \section{The \LangLam{} Language}
  15507. \label{sec:r5}
  15508. The definitions of the concrete syntax and abstract syntax for
  15509. \LangLam{}, a language with anonymous functions and lexical scoping,
  15510. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15511. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15512. for \LangFun{}, which already has syntax for function application.
  15513. %
  15514. \python{The syntax also includes an assignment statement that includes
  15515. a type annotation for the variable on the left-hand side, which
  15516. facilitates the type checking of \code{lambda} expressions that we
  15517. discuss later in this section.}
  15518. %
  15519. \racket{The \code{procedure-arity} operation returns the number of parameters
  15520. of a given function, an operation that we need for the translation
  15521. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15522. %
  15523. \python{The \code{arity} operation returns the number of parameters of
  15524. a given function, an operation that we need for the translation
  15525. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15526. The \code{arity} operation is not in Python, but the same functionality
  15527. is available in a more complex form. We include \code{arity} in the
  15528. \LangLam{} source language to enable testing.}
  15529. \newcommand{\LlambdaGrammarRacket}{
  15530. \begin{array}{lcl}
  15531. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15532. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15533. \end{array}
  15534. }
  15535. \newcommand{\LlambdaASTRacket}{
  15536. \begin{array}{lcl}
  15537. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15538. \itm{op} &::=& \code{procedure-arity}
  15539. \end{array}
  15540. }
  15541. \newcommand{\LlambdaGrammarPython}{
  15542. \begin{array}{lcl}
  15543. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15544. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15545. \end{array}
  15546. }
  15547. \newcommand{\LlambdaASTPython}{
  15548. \begin{array}{lcl}
  15549. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15550. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15551. \end{array}
  15552. }
  15553. % include AnnAssign in ASTPython
  15554. \begin{figure}[tp]
  15555. \centering
  15556. \begin{tcolorbox}[colback=white]
  15557. \small
  15558. {\if\edition\racketEd
  15559. \[
  15560. \begin{array}{l}
  15561. \gray{\LintGrammarRacket{}} \\ \hline
  15562. \gray{\LvarGrammarRacket{}} \\ \hline
  15563. \gray{\LifGrammarRacket{}} \\ \hline
  15564. \gray{\LwhileGrammarRacket} \\ \hline
  15565. \gray{\LtupGrammarRacket} \\ \hline
  15566. \gray{\LfunGrammarRacket} \\ \hline
  15567. \LlambdaGrammarRacket \\
  15568. \begin{array}{lcl}
  15569. \LangLamM{} &::=& \Def\ldots \; \Exp
  15570. \end{array}
  15571. \end{array}
  15572. \]
  15573. \fi}
  15574. {\if\edition\pythonEd\pythonColor
  15575. \[
  15576. \begin{array}{l}
  15577. \gray{\LintGrammarPython{}} \\ \hline
  15578. \gray{\LvarGrammarPython{}} \\ \hline
  15579. \gray{\LifGrammarPython{}} \\ \hline
  15580. \gray{\LwhileGrammarPython} \\ \hline
  15581. \gray{\LtupGrammarPython} \\ \hline
  15582. \gray{\LfunGrammarPython} \\ \hline
  15583. \LlambdaGrammarPython \\
  15584. \begin{array}{lcl}
  15585. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15586. \end{array}
  15587. \end{array}
  15588. \]
  15589. \fi}
  15590. \end{tcolorbox}
  15591. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15592. with \key{lambda}.}
  15593. \label{fig:Llam-concrete-syntax}
  15594. \end{figure}
  15595. \begin{figure}[tp]
  15596. \centering
  15597. \begin{tcolorbox}[colback=white]
  15598. \small
  15599. {\if\edition\racketEd
  15600. \[\arraycolsep=3pt
  15601. \begin{array}{l}
  15602. \gray{\LintOpAST} \\ \hline
  15603. \gray{\LvarASTRacket{}} \\ \hline
  15604. \gray{\LifASTRacket{}} \\ \hline
  15605. \gray{\LwhileASTRacket{}} \\ \hline
  15606. \gray{\LtupASTRacket{}} \\ \hline
  15607. \gray{\LfunASTRacket} \\ \hline
  15608. \LlambdaASTRacket \\
  15609. \begin{array}{lcl}
  15610. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15611. \end{array}
  15612. \end{array}
  15613. \]
  15614. \fi}
  15615. {\if\edition\pythonEd\pythonColor
  15616. \[
  15617. \begin{array}{l}
  15618. \gray{\LintASTPython} \\ \hline
  15619. \gray{\LvarASTPython{}} \\ \hline
  15620. \gray{\LifASTPython{}} \\ \hline
  15621. \gray{\LwhileASTPython{}} \\ \hline
  15622. \gray{\LtupASTPython{}} \\ \hline
  15623. \gray{\LfunASTPython} \\ \hline
  15624. \LlambdaASTPython \\
  15625. \begin{array}{lcl}
  15626. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15627. \end{array}
  15628. \end{array}
  15629. \]
  15630. \fi}
  15631. \end{tcolorbox}
  15632. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15633. \label{fig:Llam-syntax}
  15634. \end{figure}
  15635. Figure~\ref{fig:interp-Llambda} shows the definitional
  15636. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15637. \key{Lambda} saves the current environment inside the returned
  15638. function value. Recall that during function application, the
  15639. environment stored in the function value, extended with the mapping of
  15640. parameters to argument values, is used to interpret the body of the
  15641. function.
  15642. \begin{figure}[tbp]
  15643. \begin{tcolorbox}[colback=white]
  15644. {\if\edition\racketEd
  15645. \begin{lstlisting}
  15646. (define interp-Llambda-class
  15647. (class interp-Lfun-class
  15648. (super-new)
  15649. (define/override (interp-op op)
  15650. (match op
  15651. ['procedure-arity
  15652. (lambda (v)
  15653. (match v
  15654. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15655. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15656. [else (super interp-op op)]))
  15657. (define/override ((interp-exp env) e)
  15658. (define recur (interp-exp env))
  15659. (match e
  15660. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15661. `(function ,xs ,body ,env)]
  15662. [else ((super interp-exp env) e)]))
  15663. ))
  15664. (define (interp-Llambda p)
  15665. (send (new interp-Llambda-class) interp-program p))
  15666. \end{lstlisting}
  15667. \fi}
  15668. {\if\edition\pythonEd\pythonColor
  15669. \begin{lstlisting}
  15670. class InterpLlambda(InterpLfun):
  15671. def arity(self, v):
  15672. match v:
  15673. case Function(name, params, body, env):
  15674. return len(params)
  15675. case _:
  15676. raise Exception('Llambda arity unexpected ' + repr(v))
  15677. def interp_exp(self, e, env):
  15678. match e:
  15679. case Call(Name('arity'), [fun]):
  15680. f = self.interp_exp(fun, env)
  15681. return self.arity(f)
  15682. case Lambda(params, body):
  15683. return Function('lambda', params, [Return(body)], env)
  15684. case _:
  15685. return super().interp_exp(e, env)
  15686. def interp_stmt(self, s, env, cont):
  15687. match s:
  15688. case AnnAssign(lhs, typ, value, simple):
  15689. env[lhs.id] = self.interp_exp(value, env)
  15690. return self.interp_stmts(cont, env)
  15691. case Pass():
  15692. return self.interp_stmts(cont, env)
  15693. case _:
  15694. return super().interp_stmt(s, env, cont)
  15695. \end{lstlisting}
  15696. \fi}
  15697. \end{tcolorbox}
  15698. \caption{Interpreter for \LangLam{}.}
  15699. \label{fig:interp-Llambda}
  15700. \end{figure}
  15701. {\if\edition\racketEd
  15702. %
  15703. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15704. \key{lambda} form. The body of the \key{lambda} is checked in an
  15705. environment that includes the current environment (because it is
  15706. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15707. require the body's type to match the declared return type.
  15708. %
  15709. \fi}
  15710. {\if\edition\pythonEd\pythonColor
  15711. %
  15712. Figures~\ref{fig:type-check-Llambda} and
  15713. \ref{fig:type-check-Llambda-part2} define the type checker for
  15714. \LangLam{}, which is more complex than one might expect. The reason
  15715. for the added complexity is that the syntax of \key{lambda} does not
  15716. include type annotations for the parameters or return type. Instead
  15717. they must be inferred. There are many approaches to type inference
  15718. from which to choose, of varying degrees of complexity. We choose one
  15719. of the simpler approaches, bidirectional type
  15720. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15721. book is compilation, not type inference.
  15722. The main idea of bidirectional type inference is to add an auxiliary
  15723. function, here named \code{check\_exp}, that takes an expected type
  15724. and checks whether the given expression is of that type. Thus, in
  15725. \code{check\_exp}, type information flows in a top-down manner with
  15726. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15727. function, where type information flows in a primarily bottom-up
  15728. manner.
  15729. %
  15730. The idea then is to use \code{check\_exp} in all the places where we
  15731. already know what the type of an expression should be, such as in the
  15732. \code{return} statement of a top-level function definition or on the
  15733. right-hand side of an annotated assignment statement.
  15734. With regard to \code{lambda}, it is straightforward to check a
  15735. \code{lambda} inside \code{check\_exp} because the expected type
  15736. provides the parameter types and the return type. On the other hand,
  15737. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15738. that we do not allow \code{lambda} in contexts in which we don't already
  15739. know its type. This restriction does not incur a loss of
  15740. expressiveness for \LangLam{} because it is straightforward to modify
  15741. a program to sidestep the restriction, for example, by using an
  15742. annotated assignment statement to assign the \code{lambda} to a
  15743. temporary variable.
  15744. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15745. checker records their type in a \code{has\_type} field. This type
  15746. information is used further on in this chapter.
  15747. %
  15748. \fi}
  15749. \begin{figure}[tbp]
  15750. \begin{tcolorbox}[colback=white]
  15751. {\if\edition\racketEd
  15752. \begin{lstlisting}
  15753. (define (type-check-Llambda env)
  15754. (lambda (e)
  15755. (match e
  15756. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15757. (define-values (new-body bodyT)
  15758. ((type-check-exp (append (map cons xs Ts) env)) body))
  15759. (define ty `(,@Ts -> ,rT))
  15760. (cond
  15761. [(equal? rT bodyT)
  15762. (values (HasType (Lambda params rT new-body) ty) ty)]
  15763. [else
  15764. (error "mismatch in return type" bodyT rT)])]
  15765. ...
  15766. )))
  15767. \end{lstlisting}
  15768. \fi}
  15769. {\if\edition\pythonEd\pythonColor
  15770. \begin{lstlisting}
  15771. class TypeCheckLlambda(TypeCheckLfun):
  15772. def type_check_exp(self, e, env):
  15773. match e:
  15774. case Name(id):
  15775. e.has_type = env[id]
  15776. return env[id]
  15777. case Lambda(params, body):
  15778. raise Exception('cannot synthesize a type for a lambda')
  15779. case Call(Name('arity'), [func]):
  15780. func_t = self.type_check_exp(func, env)
  15781. match func_t:
  15782. case FunctionType(params_t, return_t):
  15783. return IntType()
  15784. case _:
  15785. raise Exception('in arity, unexpected ' + repr(func_t))
  15786. case _:
  15787. return super().type_check_exp(e, env)
  15788. def check_exp(self, e, ty, env):
  15789. match e:
  15790. case Lambda(params, body):
  15791. e.has_type = ty
  15792. match ty:
  15793. case FunctionType(params_t, return_t):
  15794. new_env = env.copy().update(zip(params, params_t))
  15795. self.check_exp(body, return_t, new_env)
  15796. case _:
  15797. raise Exception('lambda does not have type ' + str(ty))
  15798. case Call(func, args):
  15799. func_t = self.type_check_exp(func, env)
  15800. match func_t:
  15801. case FunctionType(params_t, return_t):
  15802. for (arg, param_t) in zip(args, params_t):
  15803. self.check_exp(arg, param_t, env)
  15804. self.check_type_equal(return_t, ty, e)
  15805. case _:
  15806. raise Exception('type_check_exp: in call, unexpected ' + \
  15807. repr(func_t))
  15808. case _:
  15809. t = self.type_check_exp(e, env)
  15810. self.check_type_equal(t, ty, e)
  15811. \end{lstlisting}
  15812. \fi}
  15813. \end{tcolorbox}
  15814. \caption{Type checking \LangLam{}\python{, part 1}.}
  15815. \label{fig:type-check-Llambda}
  15816. \end{figure}
  15817. {\if\edition\pythonEd\pythonColor
  15818. \begin{figure}[tbp]
  15819. \begin{tcolorbox}[colback=white]
  15820. \begin{lstlisting}
  15821. def check_stmts(self, ss, return_ty, env):
  15822. if len(ss) == 0:
  15823. return
  15824. match ss[0]:
  15825. case FunctionDef(name, params, body, dl, returns, comment):
  15826. new_env = env.copy().update(params)
  15827. rt = self.check_stmts(body, returns, new_env)
  15828. self.check_stmts(ss[1:], return_ty, env)
  15829. case Return(value):
  15830. self.check_exp(value, return_ty, env)
  15831. case Assign([Name(id)], value):
  15832. if id in env:
  15833. self.check_exp(value, env[id], env)
  15834. else:
  15835. env[id] = self.type_check_exp(value, env)
  15836. self.check_stmts(ss[1:], return_ty, env)
  15837. case Assign([Subscript(tup, Constant(index), Store())], value):
  15838. tup_t = self.type_check_exp(tup, env)
  15839. match tup_t:
  15840. case TupleType(ts):
  15841. self.check_exp(value, ts[index], env)
  15842. case _:
  15843. raise Exception('expected a tuple, not ' + repr(tup_t))
  15844. self.check_stmts(ss[1:], return_ty, env)
  15845. case AnnAssign(Name(id), ty_annot, value, simple):
  15846. ss[0].annotation = ty_annot
  15847. if id in env:
  15848. self.check_type_equal(env[id], ty_annot)
  15849. else:
  15850. env[id] = ty_annot
  15851. self.check_exp(value, ty_annot, env)
  15852. self.check_stmts(ss[1:], return_ty, env)
  15853. case _:
  15854. self.type_check_stmts(ss, env)
  15855. def type_check(self, p):
  15856. match p:
  15857. case Module(body):
  15858. env = {}
  15859. for s in body:
  15860. match s:
  15861. case FunctionDef(name, params, bod, dl, returns, comment):
  15862. params_t = [t for (x,t) in params]
  15863. env[name] = FunctionType(params_t, returns)
  15864. self.check_stmts(body, int, env)
  15865. \end{lstlisting}
  15866. \end{tcolorbox}
  15867. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15868. \label{fig:type-check-Llambda-part2}
  15869. \end{figure}
  15870. \fi}
  15871. \clearpage
  15872. \section{Assignment and Lexically Scoped Functions}
  15873. \label{sec:assignment-scoping}
  15874. The combination of lexically scoped functions and assignment to
  15875. variables raises a challenge with the flat-closure approach to
  15876. implementing lexically scoped functions. Consider the following
  15877. example in which function \code{f} has a free variable \code{x} that
  15878. is changed after \code{f} is created but before the call to \code{f}.
  15879. % loop_test_11.rkt
  15880. {\if\edition\racketEd
  15881. \begin{lstlisting}
  15882. (let ([x 0])
  15883. (let ([y 0])
  15884. (let ([z 20])
  15885. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15886. (begin
  15887. (set! x 10)
  15888. (set! y 12)
  15889. (f y))))))
  15890. \end{lstlisting}
  15891. \fi}
  15892. {\if\edition\pythonEd\pythonColor
  15893. % box_free_assign.py
  15894. \begin{lstlisting}
  15895. def g(z : int) -> int:
  15896. x = 0
  15897. y = 0
  15898. f : Callable[[int],int] = lambda a: a + x + z
  15899. x = 10
  15900. y = 12
  15901. return f(y)
  15902. print(g(20))
  15903. \end{lstlisting}
  15904. \fi} The correct output for this example is \code{42} because the call
  15905. to \code{f} is required to use the current value of \code{x} (which is
  15906. \code{10}). Unfortunately, the closure conversion pass
  15907. (section~\ref{sec:closure-conversion}) generates code for the
  15908. \code{lambda} that copies the old value of \code{x} into a
  15909. closure. Thus, if we naively applied closure conversion, the output of
  15910. this program would be \code{32}.
  15911. A first attempt at solving this problem would be to save a pointer to
  15912. \code{x} in the closure and change the occurrences of \code{x} inside
  15913. the lambda to dereference the pointer. Of course, this would require
  15914. assigning \code{x} to the stack and not to a register. However, the
  15915. problem goes a bit deeper.
  15916. Consider the following example that returns a function that refers to
  15917. a local variable of the enclosing function:
  15918. \begin{center}
  15919. \begin{minipage}{\textwidth}
  15920. {\if\edition\racketEd
  15921. \begin{lstlisting}
  15922. (define (f) : ( -> Integer)
  15923. (let ([x 0])
  15924. (let ([g (lambda: () : Integer x)])
  15925. (begin
  15926. (set! x 42)
  15927. g))))
  15928. ((f))
  15929. \end{lstlisting}
  15930. \fi}
  15931. {\if\edition\pythonEd\pythonColor
  15932. % counter.py
  15933. \begin{lstlisting}
  15934. def f():
  15935. x = 0
  15936. g = lambda: x
  15937. x = 42
  15938. return g
  15939. print(f()())
  15940. \end{lstlisting}
  15941. \fi}
  15942. \end{minipage}
  15943. \end{center}
  15944. In this example, the lifetime of \code{x} extends beyond the lifetime
  15945. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15946. stack frame for the call to \code{f}, it would be gone by the time we
  15947. called \code{g}, leaving us with dangling pointers for
  15948. \code{x}. This example demonstrates that when a variable occurs free
  15949. inside a function, its lifetime becomes indefinite. Thus, the value of
  15950. the variable needs to live on the heap. The verb
  15951. \emph{box}\index{subject}{box} is often used for allocating a single
  15952. value on the heap, producing a pointer, and
  15953. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15954. %
  15955. We introduce a new pass named \code{convert\_assignments} to address
  15956. this challenge.
  15957. %
  15958. \python{But before diving into that, we have one more
  15959. problem to discuss.}
  15960. {\if\edition\pythonEd\pythonColor
  15961. \section{Uniquify Variables}
  15962. \label{sec:uniquify-lambda}
  15963. With the addition of \code{lambda} we have a complication to deal
  15964. with: name shadowing. Consider the following program with a function
  15965. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15966. \code{lambda} expressions. The first \code{lambda} has a parameter
  15967. that is also named \code{x}.
  15968. \begin{lstlisting}
  15969. def f(x:int, y:int) -> Callable[[int], int]:
  15970. g : Callable[[int],int] = (lambda x: x + y)
  15971. h : Callable[[int],int] = (lambda y: x + y)
  15972. x = input_int()
  15973. return g
  15974. print(f(0, 10)(32))
  15975. \end{lstlisting}
  15976. Many of our compiler passes rely on being able to connect variable
  15977. uses with their definitions using just the name of the
  15978. variable. However, in the example above, the name of the variable does
  15979. not uniquely determine its definition. To solve this problem we
  15980. recommend implementing a pass named \code{uniquify} that renames every
  15981. variable in the program to make sure that they are all unique.
  15982. The following shows the result of \code{uniquify} for the example
  15983. above. The \code{x} parameter of function \code{f} is renamed to
  15984. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15985. renamed to \code{x\_4}.
  15986. \begin{lstlisting}
  15987. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15988. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15989. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15990. x_0 = input_int()
  15991. return g_2
  15992. def main() -> int :
  15993. print(f(0, 10)(32))
  15994. return 0
  15995. \end{lstlisting}
  15996. \fi} % pythonEd
  15997. %% \section{Reveal Functions}
  15998. %% \label{sec:reveal-functions-r5}
  15999. %% \racket{To support the \code{procedure-arity} operator we need to
  16000. %% communicate the arity of a function to the point of closure
  16001. %% creation.}
  16002. %% %
  16003. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16004. %% function at runtime. Thus, we need to communicate the arity of a
  16005. %% function to the point of closure creation.}
  16006. %% %
  16007. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16008. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16009. %% \[
  16010. %% \begin{array}{lcl}
  16011. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16012. %% \end{array}
  16013. %% \]
  16014. \section{Assignment Conversion}
  16015. \label{sec:convert-assignments}
  16016. The purpose of the \code{convert\_assignments} pass is to address the
  16017. challenge regarding the interaction between variable assignments and
  16018. closure conversion. First we identify which variables need to be
  16019. boxed, and then we transform the program to box those variables. In
  16020. general, boxing introduces runtime overhead that we would like to
  16021. avoid, so we should box as few variables as possible. We recommend
  16022. boxing the variables in the intersection of the following two sets of
  16023. variables:
  16024. \begin{enumerate}
  16025. \item The variables that are free in a \code{lambda}.
  16026. \item The variables that appear on the left-hand side of an
  16027. assignment.
  16028. \end{enumerate}
  16029. The first condition is a must but the second condition is
  16030. conservative. It is possible to develop a more liberal condition using
  16031. static program analysis.
  16032. Consider again the first example from
  16033. section~\ref{sec:assignment-scoping}:
  16034. %
  16035. {\if\edition\racketEd
  16036. \begin{lstlisting}
  16037. (let ([x 0])
  16038. (let ([y 0])
  16039. (let ([z 20])
  16040. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16041. (begin
  16042. (set! x 10)
  16043. (set! y 12)
  16044. (f y))))))
  16045. \end{lstlisting}
  16046. \fi}
  16047. {\if\edition\pythonEd\pythonColor
  16048. \begin{lstlisting}
  16049. def g(z : int) -> int:
  16050. x = 0
  16051. y = 0
  16052. f : Callable[[int],int] = lambda a: a + x + z
  16053. x = 10
  16054. y = 12
  16055. return f(y)
  16056. print(g(20))
  16057. \end{lstlisting}
  16058. \fi}
  16059. %
  16060. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16061. side of assignments. The variables \code{x} and \code{z} occur free
  16062. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16063. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16064. three transformations: initialize \code{x} with a tuple whose element
  16065. is uninitialized, replace reads from \code{x} with tuple reads, and
  16066. replace each assignment to \code{x} with a tuple write. The output of
  16067. \code{convert\_assignments} for this example is as follows:
  16068. %
  16069. {\if\edition\racketEd
  16070. \begin{lstlisting}
  16071. (define (main) : Integer
  16072. (let ([x0 (vector 0)])
  16073. (let ([y1 0])
  16074. (let ([z2 20])
  16075. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16076. (+ a3 (+ (vector-ref x0 0) z2)))])
  16077. (begin
  16078. (vector-set! x0 0 10)
  16079. (set! y1 12)
  16080. (f4 y1)))))))
  16081. \end{lstlisting}
  16082. \fi}
  16083. %
  16084. {\if\edition\pythonEd\pythonColor
  16085. \begin{lstlisting}
  16086. def g(z : int)-> int:
  16087. x = (uninitialized(int),)
  16088. x[0] = 0
  16089. y = 0
  16090. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16091. x[0] = 10
  16092. y = 12
  16093. return f(y)
  16094. def main() -> int:
  16095. print(g(20))
  16096. return 0
  16097. \end{lstlisting}
  16098. \fi}
  16099. To compute the free variables of all the \code{lambda} expressions, we
  16100. recommend defining the following two auxiliary functions:
  16101. \begin{enumerate}
  16102. \item \code{free\_variables} computes the free variables of an expression, and
  16103. \item \code{free\_in\_lambda} collects all the variables that are
  16104. free in any of the \code{lambda} expressions, using
  16105. \code{free\_variables} in the case for each \code{lambda}.
  16106. \end{enumerate}
  16107. {\if\edition\racketEd
  16108. %
  16109. To compute the variables that are assigned to, we recommend updating
  16110. the \code{collect-set!} function that we introduced in
  16111. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16112. as \code{Lambda}.
  16113. %
  16114. \fi}
  16115. {\if\edition\pythonEd\pythonColor
  16116. %
  16117. To compute the variables that are assigned to, we recommend defining
  16118. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16119. the set of variables that occur in the left-hand side of an assignment
  16120. statement and otherwise returns the empty set.
  16121. %
  16122. \fi}
  16123. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16124. free in a \code{lambda} and that are assigned to in the enclosing
  16125. function definition.
  16126. Next we discuss the \code{convert\_assignments} pass. In the case for
  16127. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16128. $\VAR{x}$ to a tuple read.
  16129. %
  16130. {\if\edition\racketEd
  16131. \begin{lstlisting}
  16132. (Var |$x$|)
  16133. |$\Rightarrow$|
  16134. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16135. \end{lstlisting}
  16136. \fi}
  16137. %
  16138. {\if\edition\pythonEd\pythonColor
  16139. \begin{lstlisting}
  16140. Name(|$x$|)
  16141. |$\Rightarrow$|
  16142. Subscript(Name(|$x$|), Constant(0), Load())
  16143. \end{lstlisting}
  16144. \fi}
  16145. %
  16146. \noindent In the case for assignment, recursively process the
  16147. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16148. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16149. as follows:
  16150. %
  16151. {\if\edition\racketEd
  16152. \begin{lstlisting}
  16153. (SetBang |$x$| |$\itm{rhs}$|)
  16154. |$\Rightarrow$|
  16155. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16156. \end{lstlisting}
  16157. \fi}
  16158. {\if\edition\pythonEd\pythonColor
  16159. \begin{lstlisting}
  16160. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16161. |$\Rightarrow$|
  16162. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16163. \end{lstlisting}
  16164. \fi}
  16165. %
  16166. {\if\edition\racketEd
  16167. The case for \code{Lambda} is nontrivial, but it is similar to the
  16168. case for function definitions, which we discuss next.
  16169. \fi}
  16170. %
  16171. To translate a function definition, we first compute $\mathit{AF}$,
  16172. the intersection of the variables that are free in a \code{lambda} and
  16173. that are assigned to. We then apply assignment conversion to the body
  16174. of the function definition. Finally, we box the parameters of this
  16175. function definition that are in $\mathit{AF}$. For example,
  16176. the parameter \code{x} of the following function \code{g}
  16177. needs to be boxed:
  16178. {\if\edition\racketEd
  16179. \begin{lstlisting}
  16180. (define (g [x : Integer]) : Integer
  16181. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16182. (begin
  16183. (set! x 10)
  16184. (f 32))))
  16185. \end{lstlisting}
  16186. \fi}
  16187. %
  16188. {\if\edition\pythonEd\pythonColor
  16189. \begin{lstlisting}
  16190. def g(x : int) -> int:
  16191. f : Callable[[int],int] = lambda a: a + x
  16192. x = 10
  16193. return f(32)
  16194. \end{lstlisting}
  16195. \fi}
  16196. %
  16197. \noindent We box parameter \code{x} by creating a local variable named
  16198. \code{x} that is initialized to a tuple whose contents is the value of
  16199. the parameter, which is renamed to \code{x\_0}.
  16200. %
  16201. {\if\edition\racketEd
  16202. \begin{lstlisting}
  16203. (define (g [x_0 : Integer]) : Integer
  16204. (let ([x (vector x_0)])
  16205. (let ([f (lambda: ([a : Integer]) : Integer
  16206. (+ a (vector-ref x 0)))])
  16207. (begin
  16208. (vector-set! x 0 10)
  16209. (f 32)))))
  16210. \end{lstlisting}
  16211. \fi}
  16212. %
  16213. {\if\edition\pythonEd\pythonColor
  16214. \begin{lstlisting}
  16215. def g(x_0 : int)-> int:
  16216. x = (x_0,)
  16217. f : Callable[[int], int] = (lambda a: a + x[0])
  16218. x[0] = 10
  16219. return f(32)
  16220. \end{lstlisting}
  16221. \fi}
  16222. \section{Closure Conversion}
  16223. \label{sec:closure-conversion}
  16224. \index{subject}{closure conversion}
  16225. The compiling of lexically scoped functions into top-level function
  16226. definitions and flat closures is accomplished in the pass
  16227. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16228. and before \code{limit\_functions}.
  16229. As usual, we implement the pass as a recursive function over the
  16230. AST. The interesting cases are for \key{lambda} and function
  16231. application. We transform a \key{lambda} expression into an expression
  16232. that creates a closure, that is, a tuple for which the first element
  16233. is a function pointer and the rest of the elements are the values of
  16234. the free variables of the \key{lambda}.
  16235. %
  16236. However, we use the \code{Closure} AST node instead of using a tuple
  16237. so that we can record the arity.
  16238. %
  16239. In the generated code that follows, \itm{fvs} is the list of free
  16240. variables of the lambda and \itm{name} is a unique symbol generated to
  16241. identify the lambda.
  16242. %
  16243. \racket{The \itm{arity} is the number of parameters (the length of
  16244. \itm{ps}).}
  16245. %
  16246. {\if\edition\racketEd
  16247. \begin{lstlisting}
  16248. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16249. |$\Rightarrow$|
  16250. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16251. \end{lstlisting}
  16252. \fi}
  16253. %
  16254. {\if\edition\pythonEd\pythonColor
  16255. \begin{lstlisting}
  16256. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16257. |$\Rightarrow$|
  16258. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16259. \end{lstlisting}
  16260. \fi}
  16261. %
  16262. In addition to transforming each \key{Lambda} AST node into a
  16263. tuple, we create a top-level function definition for each
  16264. \key{Lambda}, as shown next.\\
  16265. \begin{minipage}{0.8\textwidth}
  16266. {\if\edition\racketEd
  16267. \begin{lstlisting}
  16268. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16269. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16270. ...
  16271. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16272. |\itm{body'}|)...))
  16273. \end{lstlisting}
  16274. \fi}
  16275. {\if\edition\pythonEd\pythonColor
  16276. \begin{lstlisting}
  16277. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16278. |$\itm{fvs}_1$| = clos[1]
  16279. |$\ldots$|
  16280. |$\itm{fvs}_m$| = clos[|$m$|]
  16281. |\itm{body'}|
  16282. \end{lstlisting}
  16283. \fi}
  16284. \end{minipage}\\
  16285. %
  16286. The \code{clos} parameter refers to the closure. The type
  16287. \itm{closTy} is a tuple type for which the first element type is
  16288. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16289. rest of the element types are the types of the free variables in the
  16290. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16291. is nontrivial to give a type to the function in the closure's
  16292. type.\footnote{To give an accurate type to a closure, we would need to
  16293. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16294. %
  16295. \racket{Translate the type
  16296. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16297. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16298. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16299. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16300. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16301. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16302. %% The dummy type is considered to be equal to any other type during type
  16303. %% checking.
  16304. The free variables become local variables that are initialized with
  16305. their values in the closure.
  16306. Closure conversion turns every function into a tuple, so the type
  16307. annotations in the program must also be translated. We recommend
  16308. defining an auxiliary recursive function for this purpose. Function
  16309. types should be translated as follows:
  16310. %
  16311. {\if\edition\racketEd
  16312. \begin{lstlisting}
  16313. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16314. |$\Rightarrow$|
  16315. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16316. \end{lstlisting}
  16317. \fi}
  16318. {\if\edition\pythonEd\pythonColor
  16319. \begin{lstlisting}
  16320. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16321. |$\Rightarrow$|
  16322. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16323. \end{lstlisting}
  16324. \fi}
  16325. %
  16326. This type indicates that the first thing in the tuple is a
  16327. function. The first parameter of the function is a tuple (a closure)
  16328. and the rest of the parameters are the ones from the original
  16329. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16330. omits the types of the free variables because (1) those types are not
  16331. available in this context, and (2) we do not need them in the code that
  16332. is generated for function application. So this type describes only the
  16333. first component of the closure tuple. At runtime the tuple may have
  16334. more components, but we ignore them at this point.
  16335. We transform function application into code that retrieves the
  16336. function from the closure and then calls the function, passing the
  16337. closure as the first argument. We place $e'$ in a temporary variable
  16338. to avoid code duplication.
  16339. \begin{center}
  16340. \begin{minipage}{\textwidth}
  16341. {\if\edition\racketEd
  16342. \begin{lstlisting}
  16343. (Apply |$e$| |$\itm{es}$|)
  16344. |$\Rightarrow$|
  16345. (Let |$\itm{tmp}$| |$e'$|
  16346. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16347. \end{lstlisting}
  16348. \fi}
  16349. %
  16350. {\if\edition\pythonEd\pythonColor
  16351. \begin{lstlisting}
  16352. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16353. |$\Rightarrow$|
  16354. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16355. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16356. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16357. \end{lstlisting}
  16358. \fi}
  16359. \end{minipage}
  16360. \end{center}
  16361. There is also the question of what to do with references to top-level
  16362. function definitions. To maintain a uniform translation of function
  16363. application, we turn function references into closures.
  16364. \begin{tabular}{lll}
  16365. \begin{minipage}{0.2\textwidth}
  16366. {\if\edition\racketEd
  16367. \begin{lstlisting}
  16368. (FunRef |$f$| |$n$|)
  16369. \end{lstlisting}
  16370. \fi}
  16371. {\if\edition\pythonEd\pythonColor
  16372. \begin{lstlisting}
  16373. FunRef(|$f$|, |$n$|)
  16374. \end{lstlisting}
  16375. \fi}
  16376. \end{minipage}
  16377. &
  16378. $\Rightarrow\qquad$
  16379. &
  16380. \begin{minipage}{0.5\textwidth}
  16381. {\if\edition\racketEd
  16382. \begin{lstlisting}
  16383. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16384. \end{lstlisting}
  16385. \fi}
  16386. {\if\edition\pythonEd\pythonColor
  16387. \begin{lstlisting}
  16388. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16389. \end{lstlisting}
  16390. \fi}
  16391. \end{minipage}
  16392. \end{tabular} \\
  16393. We no longer need the annotated assignment statement \code{AnnAssign}
  16394. to support the type checking of \code{lambda} expressions, so we
  16395. translate it to a regular \code{Assign} statement.
  16396. The top-level function definitions need to be updated to take an extra
  16397. closure parameter, but that parameter is ignored in the body of those
  16398. functions.
  16399. \subsection{An Example Translation}
  16400. \label{sec:example-lambda}
  16401. Figure~\ref{fig:lexical-functions-example} shows the result of
  16402. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16403. program demonstrating lexical scoping that we discussed at the
  16404. beginning of this chapter.
  16405. \begin{figure}[tbp]
  16406. \begin{tcolorbox}[colback=white]
  16407. \begin{minipage}{0.8\textwidth}
  16408. {\if\edition\racketEd
  16409. % tests/lambda_test_6.rkt
  16410. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16411. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16412. (let ([y8 4])
  16413. (lambda: ([z9 : Integer]) : Integer
  16414. (+ x7 (+ y8 z9)))))
  16415. (define (main) : Integer
  16416. (let ([g0 ((fun-ref f6 1) 5)])
  16417. (let ([h1 ((fun-ref f6 1) 3)])
  16418. (+ (g0 11) (h1 15)))))
  16419. \end{lstlisting}
  16420. $\Rightarrow$
  16421. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16422. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16423. (let ([y8 4])
  16424. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16425. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16426. (let ([x7 (vector-ref fvs3 1)])
  16427. (let ([y8 (vector-ref fvs3 2)])
  16428. (+ x7 (+ y8 z9)))))
  16429. (define (main) : Integer
  16430. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16431. ((vector-ref clos5 0) clos5 5))])
  16432. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16433. ((vector-ref clos6 0) clos6 3))])
  16434. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16435. \end{lstlisting}
  16436. \fi}
  16437. %
  16438. {\if\edition\pythonEd\pythonColor
  16439. % free_var.py
  16440. \begin{lstlisting}
  16441. def f(x: int) -> Callable[[int],int]:
  16442. y = 4
  16443. return lambda z: x + y + z
  16444. g = f(5)
  16445. h = f(3)
  16446. print(g(11) + h(15))
  16447. \end{lstlisting}
  16448. $\Rightarrow$
  16449. \begin{lstlisting}
  16450. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16451. x = fvs_1[1]
  16452. y = fvs_1[2]
  16453. return (x + y[0] + z)
  16454. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16455. y = (uninitialized(int),)
  16456. y[0] = 4
  16457. return closure{1}({lambda_0}, x, y)
  16458. def main() -> int:
  16459. g = (begin: clos_3 = closure{1}({f})
  16460. clos_3[0](clos_3, 5))
  16461. h = (begin: clos_4 = closure{1}({f})
  16462. clos_4[0](clos_4, 3))
  16463. print((begin: clos_5 = g
  16464. clos_5[0](clos_5, 11))
  16465. + (begin: clos_6 = h
  16466. clos_6[0](clos_6, 15)))
  16467. return 0
  16468. \end{lstlisting}
  16469. \fi}
  16470. \end{minipage}
  16471. \end{tcolorbox}
  16472. \caption{Example of closure conversion.}
  16473. \label{fig:lexical-functions-example}
  16474. \end{figure}
  16475. \begin{exercise}\normalfont\normalsize
  16476. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16477. Create five new programs that use \key{lambda} functions and make use of
  16478. lexical scoping. Test your compiler on these new programs and all
  16479. your previously created test programs.
  16480. \end{exercise}
  16481. \section{Expose Allocation}
  16482. \label{sec:expose-allocation-r5}
  16483. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16484. that allocates and initializes a tuple, similar to the translation of
  16485. the tuple creation in section~\ref{sec:expose-allocation}.
  16486. The only difference is replacing the use of
  16487. \ALLOC{\itm{len}}{\itm{type}} with
  16488. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16489. \section{Explicate Control and \LangCLam{}}
  16490. \label{sec:explicate-r5}
  16491. The output language of \code{explicate\_control} is \LangCLam{}; the
  16492. definition of its abstract syntax is shown in
  16493. figure~\ref{fig:Clam-syntax}.
  16494. %
  16495. \racket{The only differences with respect to \LangCFun{} are the
  16496. addition of the \code{AllocateClosure} form to the grammar for
  16497. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16498. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16499. similar to the handling of other expressions such as primitive
  16500. operators.}
  16501. %
  16502. \python{The differences with respect to \LangCFun{} are the
  16503. additions of \code{Uninitialized}, \code{AllocateClosure},
  16504. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16505. \code{explicate\_control} pass is similar to the handling of other
  16506. expressions such as primitive operators.}
  16507. \newcommand{\ClambdaASTRacket}{
  16508. \begin{array}{lcl}
  16509. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16510. \itm{op} &::= & \code{procedure-arity}
  16511. \end{array}
  16512. }
  16513. \newcommand{\ClambdaASTPython}{
  16514. \begin{array}{lcl}
  16515. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16516. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16517. &\MID& \ARITY{\Atm}
  16518. \end{array}
  16519. }
  16520. \begin{figure}[tp]
  16521. \begin{tcolorbox}[colback=white]
  16522. \small
  16523. {\if\edition\racketEd
  16524. \[
  16525. \begin{array}{l}
  16526. \gray{\CvarASTRacket} \\ \hline
  16527. \gray{\CifASTRacket} \\ \hline
  16528. \gray{\CloopASTRacket} \\ \hline
  16529. \gray{\CtupASTRacket} \\ \hline
  16530. \gray{\CfunASTRacket} \\ \hline
  16531. \ClambdaASTRacket \\
  16532. \begin{array}{lcl}
  16533. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16534. \end{array}
  16535. \end{array}
  16536. \]
  16537. \fi}
  16538. {\if\edition\pythonEd\pythonColor
  16539. \[
  16540. \begin{array}{l}
  16541. \gray{\CifASTPython} \\ \hline
  16542. \gray{\CtupASTPython} \\ \hline
  16543. \gray{\CfunASTPython} \\ \hline
  16544. \ClambdaASTPython \\
  16545. \begin{array}{lcl}
  16546. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16547. \end{array}
  16548. \end{array}
  16549. \]
  16550. \fi}
  16551. \end{tcolorbox}
  16552. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16553. \label{fig:Clam-syntax}
  16554. \end{figure}
  16555. \section{Select Instructions}
  16556. \label{sec:select-instructions-Llambda}
  16557. \index{subject}{select instructions}
  16558. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16559. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16560. (section~\ref{sec:select-instructions-gc}). The only difference is
  16561. that you should place the \itm{arity} in the tag that is stored at
  16562. position $0$ of the tuple. Recall that in
  16563. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16564. was not used. We store the arity in the $5$ bits starting at position
  16565. $58$.
  16566. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16567. instructions that access the tag from position $0$ of the vector and
  16568. extract the $5$ bits starting at position $58$ from the tag.}
  16569. %
  16570. \python{Compile a call to the \code{arity} operator to a sequence of
  16571. instructions that access the tag from position $0$ of the tuple
  16572. (representing a closure) and extract the $5$ bits starting at position
  16573. $58$ from the tag.}
  16574. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16575. needed for the compilation of \LangLam{}.
  16576. \begin{figure}[bthp]
  16577. \begin{tcolorbox}[colback=white]
  16578. {\if\edition\racketEd
  16579. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16580. \node (Lfun) at (0,2) {\large \LangLam{}};
  16581. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16582. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16583. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16584. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16585. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16586. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16587. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16588. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16589. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16590. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16591. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16592. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16593. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16594. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16595. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16596. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16597. \path[->,bend left=15] (Lfun) edge [above] node
  16598. {\ttfamily\footnotesize shrink} (Lfun-2);
  16599. \path[->,bend left=15] (Lfun-2) edge [above] node
  16600. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16601. \path[->,bend left=15] (Lfun-3) edge [above] node
  16602. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16603. \path[->,bend left=15] (F1-0) edge [left] node
  16604. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16605. \path[->,bend left=15] (F1-1) edge [below] node
  16606. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16607. \path[->,bend right=15] (F1-2) edge [above] node
  16608. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16609. \path[->,bend right=15] (F1-3) edge [above] node
  16610. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16611. \path[->,bend left=15] (F1-4) edge [right] node
  16612. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16613. \path[->,bend right=15] (F1-5) edge [below] node
  16614. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16615. \path[->,bend left=15] (F1-6) edge [above] node
  16616. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16617. \path[->] (C3-2) edge [right] node
  16618. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16619. \path[->,bend right=15] (x86-2) edge [right] node
  16620. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16621. \path[->,bend right=15] (x86-2-1) edge [below] node
  16622. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16623. \path[->,bend right=15] (x86-2-2) edge [right] node
  16624. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16625. \path[->,bend left=15] (x86-3) edge [above] node
  16626. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16627. \path[->,bend left=15] (x86-4) edge [right] node
  16628. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16629. \end{tikzpicture}
  16630. \fi}
  16631. {\if\edition\pythonEd\pythonColor
  16632. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16633. \node (Lfun) at (0,2) {\large \LangLam{}};
  16634. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16635. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16636. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16637. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16638. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16639. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16640. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16641. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16642. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16643. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16644. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16645. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16646. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16647. \path[->,bend left=15] (Lfun) edge [above] node
  16648. {\ttfamily\footnotesize shrink} (Lfun-2);
  16649. \path[->,bend left=15] (Lfun-2) edge [above] node
  16650. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16651. \path[->,bend left=15] (Lfun-3) edge [above] node
  16652. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16653. \path[->,bend left=15] (F1-0) edge [left] node
  16654. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16655. \path[->,bend left=15] (F1-1) edge [below] node
  16656. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16657. \path[->,bend left=15] (F1-2) edge [below] node
  16658. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16659. \path[->,bend right=15] (F1-3) edge [above] node
  16660. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16661. \path[->,bend right=15] (F1-5) edge [right] node
  16662. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16663. \path[->,bend left=15] (F1-6) edge [right] node
  16664. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16665. \path[->,bend right=15] (C3-2) edge [right] node
  16666. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16667. \path[->,bend right=15] (x86-2) edge [below] node
  16668. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16669. \path[->,bend right=15] (x86-3) edge [below] node
  16670. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16671. \path[->,bend left=15] (x86-4) edge [above] node
  16672. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16673. \end{tikzpicture}
  16674. \fi}
  16675. \end{tcolorbox}
  16676. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16677. functions.}
  16678. \label{fig:Llambda-passes}
  16679. \end{figure}
  16680. \clearpage
  16681. \section{Challenge: Optimize Closures}
  16682. \label{sec:optimize-closures}
  16683. In this chapter we compile lexically scoped functions into a
  16684. relatively efficient representation: flat closures. However, even this
  16685. representation comes with some overhead. For example, consider the
  16686. following program with a function \code{tail\_sum} that does not have
  16687. any free variables and where all the uses of \code{tail\_sum} are in
  16688. applications in which we know that only \code{tail\_sum} is being applied
  16689. (and not any other functions):
  16690. \begin{center}
  16691. \begin{minipage}{0.95\textwidth}
  16692. {\if\edition\racketEd
  16693. \begin{lstlisting}
  16694. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16695. (if (eq? n 0)
  16696. s
  16697. (tail_sum (- n 1) (+ n s))))
  16698. (+ (tail_sum 3 0) 36)
  16699. \end{lstlisting}
  16700. \fi}
  16701. {\if\edition\pythonEd\pythonColor
  16702. \begin{lstlisting}
  16703. def tail_sum(n : int, s : int) -> int:
  16704. if n == 0:
  16705. return s
  16706. else:
  16707. return tail_sum(n - 1, n + s)
  16708. print(tail_sum(3, 0) + 36)
  16709. \end{lstlisting}
  16710. \fi}
  16711. \end{minipage}
  16712. \end{center}
  16713. As described in this chapter, we uniformly apply closure conversion to
  16714. all functions, obtaining the following output for this program:
  16715. \begin{center}
  16716. \begin{minipage}{0.95\textwidth}
  16717. {\if\edition\racketEd
  16718. \begin{lstlisting}
  16719. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16720. (if (eq? n2 0)
  16721. s3
  16722. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16723. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16724. (define (main) : Integer
  16725. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16726. ((vector-ref clos6 0) clos6 3 0)) 27))
  16727. \end{lstlisting}
  16728. \fi}
  16729. {\if\edition\pythonEd\pythonColor
  16730. \begin{lstlisting}
  16731. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16732. if n_0 == 0:
  16733. return s_1
  16734. else:
  16735. return (begin: clos_2 = (tail_sum,)
  16736. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16737. def main() -> int :
  16738. print((begin: clos_4 = (tail_sum,)
  16739. clos_4[0](clos_4, 3, 0)) + 36)
  16740. return 0
  16741. \end{lstlisting}
  16742. \fi}
  16743. \end{minipage}
  16744. \end{center}
  16745. If this program were compiled according to the previous chapter, there
  16746. would be no allocation and the calls to \code{tail\_sum} would be
  16747. direct calls. In contrast, the program presented here allocates memory
  16748. for each closure and the calls to \code{tail\_sum} are indirect. These
  16749. two differences incur considerable overhead in a program such as this,
  16750. in which the allocations and indirect calls occur inside a tight loop.
  16751. One might think that this problem is trivial to solve: can't we just
  16752. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16753. and compile them to direct calls instead of treating it like a call to
  16754. a closure? We would also drop the new \code{fvs} parameter of
  16755. \code{tail\_sum}.
  16756. %
  16757. However, this problem is not so trivial, because a global function may
  16758. \emph{escape} and become involved in applications that also involve
  16759. closures. Consider the following example in which the application
  16760. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16761. application because the \code{lambda} may flow into \code{f}, but the
  16762. \code{inc} function might also flow into \code{f}:
  16763. \begin{center}
  16764. \begin{minipage}{\textwidth}
  16765. % lambda_test_30.rkt
  16766. {\if\edition\racketEd
  16767. \begin{lstlisting}
  16768. (define (inc [x : Integer]) : Integer
  16769. (+ x 1))
  16770. (let ([y (read)])
  16771. (let ([f (if (eq? (read) 0)
  16772. inc
  16773. (lambda: ([x : Integer]) : Integer (- x y)))])
  16774. (f 41)))
  16775. \end{lstlisting}
  16776. \fi}
  16777. {\if\edition\pythonEd\pythonColor
  16778. \begin{lstlisting}
  16779. def add1(x : int) -> int:
  16780. return x + 1
  16781. y = input_int()
  16782. g : Callable[[int], int] = lambda x: x - y
  16783. f = add1 if input_int() == 0 else g
  16784. print(f(41))
  16785. \end{lstlisting}
  16786. \fi}
  16787. \end{minipage}
  16788. \end{center}
  16789. If a global function name is used in any way other than as the
  16790. operator in a direct call, then we say that the function
  16791. \emph{escapes}. If a global function does not escape, then we do not
  16792. need to perform closure conversion on the function.
  16793. \begin{exercise}\normalfont\normalsize
  16794. Implement an auxiliary function for detecting which global
  16795. functions escape. Using that function, implement an improved version
  16796. of closure conversion that does not apply closure conversion to
  16797. global functions that do not escape but instead compiles them as
  16798. regular functions. Create several new test cases that check whether
  16799. your compiler properly detects whether global functions escape or not.
  16800. \end{exercise}
  16801. So far we have reduced the overhead of calling global functions, but
  16802. it would also be nice to reduce the overhead of calling a
  16803. \code{lambda} when we can determine at compile time which
  16804. \code{lambda} will be called. We refer to such calls as \emph{known
  16805. calls}. Consider the following example in which a \code{lambda} is
  16806. bound to \code{f} and then applied.
  16807. {\if\edition\racketEd
  16808. % lambda_test_9.rkt
  16809. \begin{lstlisting}
  16810. (let ([y (read)])
  16811. (let ([f (lambda: ([x : Integer]) : Integer
  16812. (+ x y))])
  16813. (f 21)))
  16814. \end{lstlisting}
  16815. \fi}
  16816. {\if\edition\pythonEd\pythonColor
  16817. \begin{lstlisting}
  16818. y = input_int()
  16819. f : Callable[[int],int] = lambda x: x + y
  16820. print(f(21))
  16821. \end{lstlisting}
  16822. \fi}
  16823. %
  16824. \noindent Closure conversion compiles the application
  16825. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16826. %
  16827. {\if\edition\racketEd
  16828. \begin{lstlisting}
  16829. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16830. (let ([y2 (vector-ref fvs6 1)])
  16831. (+ x3 y2)))
  16832. (define (main) : Integer
  16833. (let ([y2 (read)])
  16834. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16835. ((vector-ref f4 0) f4 21))))
  16836. \end{lstlisting}
  16837. \fi}
  16838. {\if\edition\pythonEd\pythonColor
  16839. \begin{lstlisting}
  16840. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16841. y_1 = fvs_4[1]
  16842. return x_2 + y_1[0]
  16843. def main() -> int:
  16844. y_1 = (777,)
  16845. y_1[0] = input_int()
  16846. f_0 = (lambda_3, y_1)
  16847. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16848. return 0
  16849. \end{lstlisting}
  16850. \fi}
  16851. %
  16852. \noindent However, we can instead compile the application
  16853. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16854. %
  16855. {\if\edition\racketEd
  16856. \begin{lstlisting}
  16857. (define (main) : Integer
  16858. (let ([y2 (read)])
  16859. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16860. ((fun-ref lambda5 1) f4 21))))
  16861. \end{lstlisting}
  16862. \fi}
  16863. {\if\edition\pythonEd\pythonColor
  16864. \begin{lstlisting}
  16865. def main() -> int:
  16866. y_1 = (777,)
  16867. y_1[0] = input_int()
  16868. f_0 = (lambda_3, y_1)
  16869. print(lambda_3(f_0, 21))
  16870. return 0
  16871. \end{lstlisting}
  16872. \fi}
  16873. The problem of determining which \code{lambda} will be called from a
  16874. particular application is quite challenging in general and the topic
  16875. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16876. following exercise we recommend that you compile an application to a
  16877. direct call when the operator is a variable and \racket{the variable
  16878. is \code{let}-bound to a closure}\python{the previous assignment to
  16879. the variable is a closure}. This can be accomplished by maintaining
  16880. an environment that maps variables to function names. Extend the
  16881. environment whenever you encounter a closure on the right-hand side of
  16882. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16883. name of the global function for the closure. This pass should come
  16884. after closure conversion.
  16885. \begin{exercise}\normalfont\normalsize
  16886. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16887. compiles known calls into direct calls. Verify that your compiler is
  16888. successful in this regard on several example programs.
  16889. \end{exercise}
  16890. These exercises only scratch the surface of closure optimization. A
  16891. good next step for the interested reader is to look at the work of
  16892. \citet{Keep:2012ab}.
  16893. \section{Further Reading}
  16894. The notion of lexically scoped functions predates modern computers by
  16895. about a decade. They were invented by \citet{Church:1932aa}, who
  16896. proposed the lambda calculus as a foundation for logic. Anonymous
  16897. functions were included in the LISP~\citep{McCarthy:1960dz}
  16898. programming language but were initially dynamically scoped. The Scheme
  16899. dialect of LISP adopted lexical scoping, and
  16900. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16901. Scheme programs. However, environments were represented as linked
  16902. lists, so variable look-up was linear in the size of the
  16903. environment. \citet{Appel91} gives a detailed description of several
  16904. closure representations. In this chapter we represent environments
  16905. using flat closures, which were invented by
  16906. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16907. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16908. closures, variable look-up is constant time but the time to create a
  16909. closure is proportional to the number of its free variables. Flat
  16910. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16911. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16912. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16913. % compilers)
  16914. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16915. \chapter{Dynamic Typing}
  16916. \label{ch:Ldyn}
  16917. \index{subject}{dynamic typing}
  16918. \setcounter{footnote}{0}
  16919. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16920. typed language that is a subset of \racket{Racket}\python{Python}. The
  16921. focus on dynamic typing is in contrast to the previous chapters, which
  16922. have studied the compilation of statically typed languages. In
  16923. dynamically typed languages such as \LangDyn{}, a particular
  16924. expression may produce a value of a different type each time it is
  16925. executed. Consider the following example with a conditional \code{if}
  16926. expression that may return a Boolean or an integer depending on the
  16927. input to the program:
  16928. % part of dynamic_test_25.rkt
  16929. {\if\edition\racketEd
  16930. \begin{lstlisting}
  16931. (not (if (eq? (read) 1) #f 0))
  16932. \end{lstlisting}
  16933. \fi}
  16934. {\if\edition\pythonEd\pythonColor
  16935. \begin{lstlisting}
  16936. not (False if input_int() == 1 else 0)
  16937. \end{lstlisting}
  16938. \fi}
  16939. Languages that allow expressions to produce different kinds of values
  16940. are called \emph{polymorphic}, a word composed of the Greek roots
  16941. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16942. There are several kinds of polymorphism in programming languages, such as
  16943. subtype polymorphism\index{subject}{subtype polymorphism} and
  16944. parametric polymorphism\index{subject}{parametric polymorphism}
  16945. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16946. study in this chapter does not have a special name; it is the kind
  16947. that arises in dynamically typed languages.
  16948. Another characteristic of dynamically typed languages is that
  16949. their primitive operations, such as \code{not}, are often defined to operate
  16950. on many different types of values. In fact, in
  16951. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16952. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16953. given anything else it returns \FALSE{}.
  16954. Furthermore, even when primitive operations restrict their inputs to
  16955. values of a certain type, this restriction is enforced at runtime
  16956. instead of during compilation. For example, the tuple read
  16957. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16958. results in a runtime error because the first argument must
  16959. be a tuple, not a Boolean.
  16960. \section{The \LangDyn{} Language}
  16961. \newcommand{\LdynGrammarRacket}{
  16962. \begin{array}{rcl}
  16963. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16964. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16965. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16966. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16967. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16968. \end{array}
  16969. }
  16970. \newcommand{\LdynASTRacket}{
  16971. \begin{array}{lcl}
  16972. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16973. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16974. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16975. \end{array}
  16976. }
  16977. \begin{figure}[tp]
  16978. \centering
  16979. \begin{tcolorbox}[colback=white]
  16980. \small
  16981. {\if\edition\racketEd
  16982. \[
  16983. \begin{array}{l}
  16984. \gray{\LintGrammarRacket{}} \\ \hline
  16985. \gray{\LvarGrammarRacket{}} \\ \hline
  16986. \gray{\LifGrammarRacket{}} \\ \hline
  16987. \gray{\LwhileGrammarRacket} \\ \hline
  16988. \gray{\LtupGrammarRacket} \\ \hline
  16989. \LdynGrammarRacket \\
  16990. \begin{array}{rcl}
  16991. \LangDynM{} &::=& \Def\ldots\; \Exp
  16992. \end{array}
  16993. \end{array}
  16994. \]
  16995. \fi}
  16996. {\if\edition\pythonEd\pythonColor
  16997. \[
  16998. \begin{array}{rcl}
  16999. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17000. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17001. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17002. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17003. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17004. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17005. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17006. \MID \CLEN{\Exp} \\
  17007. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17008. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17009. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17010. \MID \Var\mathop{\key{=}}\Exp \\
  17011. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17012. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17013. &\MID& \CRETURN{\Exp} \\
  17014. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17015. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17016. \end{array}
  17017. \]
  17018. \fi}
  17019. \end{tcolorbox}
  17020. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17021. \label{fig:r7-concrete-syntax}
  17022. \end{figure}
  17023. \begin{figure}[tp]
  17024. \centering
  17025. \begin{tcolorbox}[colback=white]
  17026. \small
  17027. {\if\edition\racketEd
  17028. \[
  17029. \begin{array}{l}
  17030. \gray{\LintASTRacket{}} \\ \hline
  17031. \gray{\LvarASTRacket{}} \\ \hline
  17032. \gray{\LifASTRacket{}} \\ \hline
  17033. \gray{\LwhileASTRacket} \\ \hline
  17034. \gray{\LtupASTRacket} \\ \hline
  17035. \LdynASTRacket \\
  17036. \begin{array}{lcl}
  17037. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17038. \end{array}
  17039. \end{array}
  17040. \]
  17041. \fi}
  17042. {\if\edition\pythonEd\pythonColor
  17043. \[
  17044. \begin{array}{rcl}
  17045. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17046. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17047. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17048. \MID \code{Is()} \\
  17049. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17050. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17051. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17052. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17053. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17054. &\MID& \VAR{\Var{}}
  17055. \MID \BOOL{\itm{bool}}
  17056. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17057. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17058. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17059. &\MID& \LEN{\Exp} \\
  17060. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17061. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17062. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17063. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17064. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17065. &\MID& \RETURN{\Exp} \\
  17066. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17067. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17068. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17069. \end{array}
  17070. \]
  17071. \fi}
  17072. \end{tcolorbox}
  17073. \caption{The abstract syntax of \LangDyn{}.}
  17074. \label{fig:r7-syntax}
  17075. \end{figure}
  17076. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17077. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17078. %
  17079. There is no type checker for \LangDyn{} because it checks types only
  17080. at runtime.
  17081. The definitional interpreter for \LangDyn{} is presented in
  17082. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17083. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17084. \INT{n}. Instead of simply returning the integer \code{n} (as
  17085. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17086. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17087. value} that combines an underlying value with a tag that identifies
  17088. what kind of value it is. We define the following \racket{struct}\python{class}
  17089. to represent tagged values:
  17090. %
  17091. {\if\edition\racketEd
  17092. \begin{lstlisting}
  17093. (struct Tagged (value tag) #:transparent)
  17094. \end{lstlisting}
  17095. \fi}
  17096. {\if\edition\pythonEd\pythonColor
  17097. \begin{minipage}{\textwidth}
  17098. \begin{lstlisting}
  17099. @dataclass(eq=True)
  17100. class Tagged(Value):
  17101. value : Value
  17102. tag : str
  17103. def __str__(self):
  17104. return str(self.value)
  17105. \end{lstlisting}
  17106. \end{minipage}
  17107. \fi}
  17108. %
  17109. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17110. \code{Vector}, and \code{Procedure}.}
  17111. %
  17112. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17113. \skey{tuple}, and \skey{function}.}
  17114. %
  17115. Tags are closely related to types but do not always capture all the
  17116. information that a type does.
  17117. %
  17118. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17119. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17120. Any)} is tagged with \code{Procedure}.}
  17121. %
  17122. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17123. is tagged with \skey{tuple} and a function of type
  17124. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17125. is tagged with \skey{function}.}
  17126. Next consider the match case for accessing the element of a tuple.
  17127. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17128. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17129. argument is a tuple and the second is an integer.
  17130. \racket{
  17131. If they are not, a \code{trapped-error} is raised. Recall from
  17132. section~\ref{sec:interp_Lint} that when a definition interpreter
  17133. raises a \code{trapped-error} error, the compiled code must also
  17134. signal an error by exiting with return code \code{255}. A
  17135. \code{trapped-error} is also raised if the index is not less than the
  17136. length of the vector.
  17137. }
  17138. %
  17139. \python{If they are not, an exception is raised. The compiled code
  17140. must also signal an error by exiting with return code \code{255}. A
  17141. exception is also raised if the index is not less than the length of the
  17142. tuple or if it is negative.}
  17143. \begin{figure}[tbp]
  17144. \begin{tcolorbox}[colback=white]
  17145. {\if\edition\racketEd
  17146. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17147. (define ((interp-Ldyn-exp env) ast)
  17148. (define recur (interp-Ldyn-exp env))
  17149. (match ast
  17150. [(Var x) (dict-ref env x)]
  17151. [(Int n) (Tagged n 'Integer)]
  17152. [(Bool b) (Tagged b 'Boolean)]
  17153. [(Lambda xs rt body)
  17154. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17155. [(Prim 'vector es)
  17156. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17157. [(Prim 'vector-ref (list e1 e2))
  17158. (define vec (recur e1)) (define i (recur e2))
  17159. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17160. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17161. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17162. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17163. [(Prim 'vector-set! (list e1 e2 e3))
  17164. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17165. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17166. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17167. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17168. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17169. (Tagged (void) 'Void)]
  17170. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17171. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17172. [(Prim 'or (list e1 e2))
  17173. (define v1 (recur e1))
  17174. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17175. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17176. [(Prim op (list e1))
  17177. #:when (set-member? type-predicates op)
  17178. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17179. [(Prim op es)
  17180. (define args (map recur es))
  17181. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17182. (unless (for/or ([expected-tags (op-tags op)])
  17183. (equal? expected-tags tags))
  17184. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17185. (tag-value
  17186. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17187. [(If q t f)
  17188. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17189. [(Apply f es)
  17190. (define new-f (recur f)) (define args (map recur es))
  17191. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17192. (match f-val
  17193. [`(function ,xs ,body ,lam-env)
  17194. (unless (eq? (length xs) (length args))
  17195. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17196. (define new-env (append (map cons xs args) lam-env))
  17197. ((interp-Ldyn-exp new-env) body)]
  17198. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17199. \end{lstlisting}
  17200. \fi}
  17201. {\if\edition\pythonEd\pythonColor
  17202. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17203. class InterpLdyn(InterpLlambda):
  17204. def interp_exp(self, e, env):
  17205. match e:
  17206. case Constant(n):
  17207. return self.tag(super().interp_exp(e, env))
  17208. case Tuple(es, Load()):
  17209. return self.tag(super().interp_exp(e, env))
  17210. case Lambda(params, body):
  17211. return self.tag(super().interp_exp(e, env))
  17212. case Call(Name('input_int'), []):
  17213. return self.tag(super().interp_exp(e, env))
  17214. case BinOp(left, Add(), right):
  17215. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17216. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17217. case BinOp(left, Sub(), right):
  17218. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17219. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17220. case UnaryOp(USub(), e1):
  17221. v = self.interp_exp(e1, env)
  17222. return self.tag(- self.untag(v, 'int', e))
  17223. case IfExp(test, body, orelse):
  17224. v = self.interp_exp(test, env)
  17225. if self.untag(v, 'bool', e):
  17226. return self.interp_exp(body, env)
  17227. else:
  17228. return self.interp_exp(orelse, env)
  17229. case UnaryOp(Not(), e1):
  17230. v = self.interp_exp(e1, env)
  17231. return self.tag(not self.untag(v, 'bool', e))
  17232. case BoolOp(And(), values):
  17233. left = values[0]; right = values[1]
  17234. l = self.interp_exp(left, env)
  17235. if self.untag(l, 'bool', e):
  17236. return self.interp_exp(right, env)
  17237. else:
  17238. return self.tag(False)
  17239. case BoolOp(Or(), values):
  17240. left = values[0]; right = values[1]
  17241. l = self.interp_exp(left, env)
  17242. if self.untag(l, 'bool', e):
  17243. return self.tag(True)
  17244. else:
  17245. return self.interp_exp(right, env)
  17246. \end{lstlisting}
  17247. \fi}
  17248. \end{tcolorbox}
  17249. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17250. \label{fig:interp-Ldyn}
  17251. \end{figure}
  17252. {\if\edition\pythonEd\pythonColor
  17253. \begin{figure}[tbp]
  17254. \begin{tcolorbox}[colback=white]
  17255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17256. # interp_exp continued
  17257. case Compare(left, [cmp], [right]):
  17258. l = self.interp_exp(left, env)
  17259. r = self.interp_exp(right, env)
  17260. if l.tag == r.tag:
  17261. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17262. else:
  17263. raise Exception('interp Compare unexpected '
  17264. + repr(l) + ' ' + repr(r))
  17265. case Subscript(tup, index, Load()):
  17266. t = self.interp_exp(tup, env)
  17267. n = self.interp_exp(index, env)
  17268. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17269. case Call(Name('len'), [tup]):
  17270. t = self.interp_exp(tup, env)
  17271. return self.tag(len(self.untag(t, 'tuple', e)))
  17272. case _:
  17273. return self.tag(super().interp_exp(e, env))
  17274. def interp_stmt(self, s, env, cont):
  17275. match s:
  17276. case If(test, body, orelse):
  17277. v = self.interp_exp(test, env)
  17278. match self.untag(v, 'bool', s):
  17279. case True:
  17280. return self.interp_stmts(body + cont, env)
  17281. case False:
  17282. return self.interp_stmts(orelse + cont, env)
  17283. case While(test, body, []):
  17284. v = self.interp_exp(test, env)
  17285. if self.untag(v, 'bool', test):
  17286. self.interp_stmts(body + [s] + cont, env)
  17287. else:
  17288. return self.interp_stmts(cont, env)
  17289. case Assign([Subscript(tup, index)], value):
  17290. tup = self.interp_exp(tup, env)
  17291. index = self.interp_exp(index, env)
  17292. tup_v = self.untag(tup, 'tuple', s)
  17293. index_v = self.untag(index, 'int', s)
  17294. tup_v[index_v] = self.interp_exp(value, env)
  17295. return self.interp_stmts(cont, env)
  17296. case FunctionDef(name, params, bod, dl, returns, comment):
  17297. if isinstance(params, ast.arguments):
  17298. ps = [p.arg for p in params.args]
  17299. else:
  17300. ps = [x for (x,t) in params]
  17301. env[name] = self.tag(Function(name, ps, bod, env))
  17302. return self.interp_stmts(cont, env)
  17303. case _:
  17304. return super().interp_stmt(s, env, cont)
  17305. \end{lstlisting}
  17306. \end{tcolorbox}
  17307. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17308. \label{fig:interp-Ldyn-2}
  17309. \end{figure}
  17310. \fi}
  17311. \begin{figure}[tbp]
  17312. \begin{tcolorbox}[colback=white]
  17313. {\if\edition\racketEd
  17314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17315. (define (interp-op op)
  17316. (match op
  17317. ['+ fx+]
  17318. ['- fx-]
  17319. ['read read-fixnum]
  17320. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17321. ['< (lambda (v1 v2)
  17322. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17323. ['<= (lambda (v1 v2)
  17324. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17325. ['> (lambda (v1 v2)
  17326. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17327. ['>= (lambda (v1 v2)
  17328. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17329. ['boolean? boolean?]
  17330. ['integer? fixnum?]
  17331. ['void? void?]
  17332. ['vector? vector?]
  17333. ['vector-length vector-length]
  17334. ['procedure? (match-lambda
  17335. [`(functions ,xs ,body ,env) #t] [else #f])]
  17336. [else (error 'interp-op "unknown operator" op)]))
  17337. (define (op-tags op)
  17338. (match op
  17339. ['+ '((Integer Integer))]
  17340. ['- '((Integer Integer) (Integer))]
  17341. ['read '(())]
  17342. ['not '((Boolean))]
  17343. ['< '((Integer Integer))]
  17344. ['<= '((Integer Integer))]
  17345. ['> '((Integer Integer))]
  17346. ['>= '((Integer Integer))]
  17347. ['vector-length '((Vector))]))
  17348. (define type-predicates
  17349. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17350. (define (tag-value v)
  17351. (cond [(boolean? v) (Tagged v 'Boolean)]
  17352. [(fixnum? v) (Tagged v 'Integer)]
  17353. [(procedure? v) (Tagged v 'Procedure)]
  17354. [(vector? v) (Tagged v 'Vector)]
  17355. [(void? v) (Tagged v 'Void)]
  17356. [else (error 'tag-value "unidentified value ~a" v)]))
  17357. (define (check-tag val expected ast)
  17358. (define tag (Tagged-tag val))
  17359. (unless (eq? tag expected)
  17360. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17361. \end{lstlisting}
  17362. \fi}
  17363. {\if\edition\pythonEd\pythonColor
  17364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17365. class InterpLdyn(InterpLlambda):
  17366. def tag(self, v):
  17367. if v is True or v is False:
  17368. return Tagged(v, 'bool')
  17369. elif isinstance(v, int):
  17370. return Tagged(v, 'int')
  17371. elif isinstance(v, Function):
  17372. return Tagged(v, 'function')
  17373. elif isinstance(v, tuple):
  17374. return Tagged(v, 'tuple')
  17375. elif isinstance(v, type(None)):
  17376. return Tagged(v, 'none')
  17377. else:
  17378. raise Exception('tag: unexpected ' + repr(v))
  17379. def untag(self, v, expected_tag, ast):
  17380. match v:
  17381. case Tagged(val, tag) if tag == expected_tag:
  17382. return val
  17383. case _:
  17384. raise TrappedError('expected Tagged value with '
  17385. + expected_tag + ', not ' + ' ' + repr(v))
  17386. def apply_fun(self, fun, args, e):
  17387. f = self.untag(fun, 'function', e)
  17388. return super().apply_fun(f, args, e)
  17389. \end{lstlisting}
  17390. \fi}
  17391. \end{tcolorbox}
  17392. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17393. \label{fig:interp-Ldyn-aux}
  17394. \end{figure}
  17395. %\clearpage
  17396. \section{Representation of Tagged Values}
  17397. The interpreter for \LangDyn{} introduced a new kind of value: the
  17398. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17399. represent tagged values at the bit level. Because almost every
  17400. operation in \LangDyn{} involves manipulating tagged values, the
  17401. representation must be efficient. Recall that all our values are 64
  17402. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17403. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17404. $011$ for procedures, and $101$ for the void value\python{,
  17405. \key{None}}. We define the following auxiliary function for mapping
  17406. types to tag codes:
  17407. %
  17408. {\if\edition\racketEd
  17409. \begin{align*}
  17410. \itm{tagof}(\key{Integer}) &= 001 \\
  17411. \itm{tagof}(\key{Boolean}) &= 100 \\
  17412. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17413. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17414. \itm{tagof}(\key{Void}) &= 101
  17415. \end{align*}
  17416. \fi}
  17417. {\if\edition\pythonEd\pythonColor
  17418. \begin{align*}
  17419. \itm{tagof}(\key{IntType()}) &= 001 \\
  17420. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17421. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17422. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17423. \itm{tagof}(\key{type(None)}) &= 101
  17424. \end{align*}
  17425. \fi}
  17426. %
  17427. This stealing of 3 bits comes at some price: integers are now restricted
  17428. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17429. affect tuples and procedures because those values are addresses, and
  17430. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17431. they are always $000$. Thus, we do not lose information by overwriting
  17432. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17433. to recover the original address.
  17434. To make tagged values into first-class entities, we can give them a
  17435. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17436. operations such as \code{Inject} and \code{Project} for creating and
  17437. using them, yielding the statically typed \LangAny{} intermediate
  17438. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17439. section~\ref{sec:compile-r7}; in the next section we describe the
  17440. \LangAny{} language in greater detail.
  17441. \section{The \LangAny{} Language}
  17442. \label{sec:Rany-lang}
  17443. \newcommand{\LanyASTRacket}{
  17444. \begin{array}{lcl}
  17445. \Type &::= & \ANYTY \\
  17446. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17447. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17448. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17449. \itm{op} &::= & \code{any-vector-length}
  17450. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17451. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17452. \MID \code{procedure?} \MID \code{void?} \\
  17453. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17454. \end{array}
  17455. }
  17456. \newcommand{\LanyASTPython}{
  17457. \begin{array}{lcl}
  17458. \Type &::= & \key{AnyType()} \\
  17459. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17460. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17461. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17462. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17463. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17464. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17465. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17466. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17467. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17468. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17469. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17470. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17471. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17472. \end{array}
  17473. }
  17474. \begin{figure}[tp]
  17475. \centering
  17476. \begin{tcolorbox}[colback=white]
  17477. \small
  17478. {\if\edition\racketEd
  17479. \[
  17480. \begin{array}{l}
  17481. \gray{\LintOpAST} \\ \hline
  17482. \gray{\LvarASTRacket{}} \\ \hline
  17483. \gray{\LifASTRacket{}} \\ \hline
  17484. \gray{\LwhileASTRacket{}} \\ \hline
  17485. \gray{\LtupASTRacket{}} \\ \hline
  17486. \gray{\LfunASTRacket} \\ \hline
  17487. \gray{\LlambdaASTRacket} \\ \hline
  17488. \LanyASTRacket \\
  17489. \begin{array}{lcl}
  17490. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17491. \end{array}
  17492. \end{array}
  17493. \]
  17494. \fi}
  17495. {\if\edition\pythonEd\pythonColor
  17496. \[
  17497. \begin{array}{l}
  17498. \gray{\LintASTPython} \\ \hline
  17499. \gray{\LvarASTPython{}} \\ \hline
  17500. \gray{\LifASTPython{}} \\ \hline
  17501. \gray{\LwhileASTPython{}} \\ \hline
  17502. \gray{\LtupASTPython{}} \\ \hline
  17503. \gray{\LfunASTPython} \\ \hline
  17504. \gray{\LlambdaASTPython} \\ \hline
  17505. \LanyASTPython \\
  17506. \begin{array}{lcl}
  17507. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17508. \end{array}
  17509. \end{array}
  17510. \]
  17511. \fi}
  17512. \end{tcolorbox}
  17513. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17514. \label{fig:Lany-syntax}
  17515. \end{figure}
  17516. The definition of the abstract syntax of \LangAny{} is given in
  17517. figure~\ref{fig:Lany-syntax}.
  17518. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17519. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17520. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17521. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17522. converts the tagged value produced by expression $e$ into a value of
  17523. type $T$ or halts the program if the type tag does not match $T$.
  17524. %
  17525. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17526. restricted to be a flat type (the nonterminal $\FType$) which
  17527. simplifies the implementation and complies with the needs for
  17528. compiling \LangDyn{}.
  17529. The \racket{\code{any-vector}} operators
  17530. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17531. operations so that they can be applied to a value of type
  17532. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17533. tuple operations in that the index is not restricted to a literal
  17534. integer in the grammar but is allowed to be any expression.
  17535. \racket{The type predicates such as
  17536. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17537. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17538. the predicate and return {\FALSE} otherwise.}
  17539. The type checker for \LangAny{} is shown in
  17540. figure~\ref{fig:type-check-Lany}
  17541. %
  17542. \racket{ and uses the auxiliary functions presented in
  17543. figure~\ref{fig:type-check-Lany-aux}}.
  17544. %
  17545. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17546. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17547. \begin{figure}[btp]
  17548. \begin{tcolorbox}[colback=white]
  17549. {\if\edition\racketEd
  17550. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17551. (define type-check-Lany-class
  17552. (class type-check-Llambda-class
  17553. (super-new)
  17554. (inherit check-type-equal?)
  17555. (define/override (type-check-exp env)
  17556. (lambda (e)
  17557. (define recur (type-check-exp env))
  17558. (match e
  17559. [(Inject e1 ty)
  17560. (unless (flat-ty? ty)
  17561. (error 'type-check "may only inject from flat type, not ~a" ty))
  17562. (define-values (new-e1 e-ty) (recur e1))
  17563. (check-type-equal? e-ty ty e)
  17564. (values (Inject new-e1 ty) 'Any)]
  17565. [(Project e1 ty)
  17566. (unless (flat-ty? ty)
  17567. (error 'type-check "may only project to flat type, not ~a" ty))
  17568. (define-values (new-e1 e-ty) (recur e1))
  17569. (check-type-equal? e-ty 'Any e)
  17570. (values (Project new-e1 ty) ty)]
  17571. [(Prim 'any-vector-length (list e1))
  17572. (define-values (e1^ t1) (recur e1))
  17573. (check-type-equal? t1 'Any e)
  17574. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17575. [(Prim 'any-vector-ref (list e1 e2))
  17576. (define-values (e1^ t1) (recur e1))
  17577. (define-values (e2^ t2) (recur e2))
  17578. (check-type-equal? t1 'Any e)
  17579. (check-type-equal? t2 'Integer e)
  17580. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17581. [(Prim 'any-vector-set! (list e1 e2 e3))
  17582. (define-values (e1^ t1) (recur e1))
  17583. (define-values (e2^ t2) (recur e2))
  17584. (define-values (e3^ t3) (recur e3))
  17585. (check-type-equal? t1 'Any e)
  17586. (check-type-equal? t2 'Integer e)
  17587. (check-type-equal? t3 'Any e)
  17588. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17589. [(Prim pred (list e1))
  17590. #:when (set-member? (type-predicates) pred)
  17591. (define-values (new-e1 e-ty) (recur e1))
  17592. (check-type-equal? e-ty 'Any e)
  17593. (values (Prim pred (list new-e1)) 'Boolean)]
  17594. [(Prim 'eq? (list arg1 arg2))
  17595. (define-values (e1 t1) (recur arg1))
  17596. (define-values (e2 t2) (recur arg2))
  17597. (match* (t1 t2)
  17598. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17599. [(other wise) (check-type-equal? t1 t2 e)])
  17600. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17601. [else ((super type-check-exp env) e)])))
  17602. ))
  17603. \end{lstlisting}
  17604. \fi}
  17605. {\if\edition\pythonEd\pythonColor
  17606. \begin{lstlisting}
  17607. class TypeCheckLany(TypeCheckLlambda):
  17608. def type_check_exp(self, e, env):
  17609. match e:
  17610. case Inject(value, typ):
  17611. self.check_exp(value, typ, env)
  17612. return AnyType()
  17613. case Project(value, typ):
  17614. self.check_exp(value, AnyType(), env)
  17615. return typ
  17616. case Call(Name('any_tuple_load'), [tup, index]):
  17617. self.check_exp(tup, AnyType(), env)
  17618. self.check_exp(index, IntType(), env)
  17619. return AnyType()
  17620. case Call(Name('any_len'), [tup]):
  17621. self.check_exp(tup, AnyType(), env)
  17622. return IntType()
  17623. case Call(Name('arity'), [fun]):
  17624. ty = self.type_check_exp(fun, env)
  17625. match ty:
  17626. case FunctionType(ps, rt):
  17627. return IntType()
  17628. case TupleType([FunctionType(ps,rs)]):
  17629. return IntType()
  17630. case _:
  17631. raise Exception('type check arity unexpected ' + repr(ty))
  17632. case Call(Name('make_any'), [value, tag]):
  17633. self.type_check_exp(value, env)
  17634. self.check_exp(tag, IntType(), env)
  17635. return AnyType()
  17636. case AnnLambda(params, returns, body):
  17637. new_env = {x:t for (x,t) in env.items()}
  17638. for (x,t) in params:
  17639. new_env[x] = t
  17640. return_t = self.type_check_exp(body, new_env)
  17641. self.check_type_equal(returns, return_t, e)
  17642. return FunctionType([t for (x,t) in params], return_t)
  17643. case _:
  17644. return super().type_check_exp(e, env)
  17645. \end{lstlisting}
  17646. \fi}
  17647. \end{tcolorbox}
  17648. \caption{Type checker for the \LangAny{} language.}
  17649. \label{fig:type-check-Lany}
  17650. \end{figure}
  17651. {\if\edition\racketEd
  17652. \begin{figure}[tbp]
  17653. \begin{tcolorbox}[colback=white]
  17654. \begin{lstlisting}
  17655. (define/override (operator-types)
  17656. (append
  17657. '((integer? . ((Any) . Boolean))
  17658. (vector? . ((Any) . Boolean))
  17659. (procedure? . ((Any) . Boolean))
  17660. (void? . ((Any) . Boolean)))
  17661. (super operator-types)))
  17662. (define/public (type-predicates)
  17663. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17664. (define/public (flat-ty? ty)
  17665. (match ty
  17666. [(or `Integer `Boolean `Void) #t]
  17667. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17668. [`(,ts ... -> ,rt)
  17669. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17670. [else #f]))
  17671. \end{lstlisting}
  17672. \end{tcolorbox}
  17673. \caption{Auxiliary methods for type checking \LangAny{}.}
  17674. \label{fig:type-check-Lany-aux}
  17675. \end{figure}
  17676. \fi}
  17677. \begin{figure}[tbp]
  17678. \begin{tcolorbox}[colback=white]
  17679. {\if\edition\racketEd
  17680. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17681. (define interp-Lany-class
  17682. (class interp-Llambda-class
  17683. (super-new)
  17684. (define/override (interp-op op)
  17685. (match op
  17686. ['boolean? (match-lambda
  17687. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17688. [else #f])]
  17689. ['integer? (match-lambda
  17690. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17691. [else #f])]
  17692. ['vector? (match-lambda
  17693. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17694. [else #f])]
  17695. ['procedure? (match-lambda
  17696. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17697. [else #f])]
  17698. ['eq? (match-lambda*
  17699. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17700. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17701. [ls (apply (super interp-op op) ls)])]
  17702. ['any-vector-ref (lambda (v i)
  17703. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17704. ['any-vector-set! (lambda (v i a)
  17705. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17706. ['any-vector-length (lambda (v)
  17707. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17708. [else (super interp-op op)]))
  17709. (define/override ((interp-exp env) e)
  17710. (define recur (interp-exp env))
  17711. (match e
  17712. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17713. [(Project e ty2) (apply-project (recur e) ty2)]
  17714. [else ((super interp-exp env) e)]))
  17715. ))
  17716. (define (interp-Lany p)
  17717. (send (new interp-Lany-class) interp-program p))
  17718. \end{lstlisting}
  17719. \fi}
  17720. {\if\edition\pythonEd\pythonColor
  17721. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17722. class InterpLany(InterpLlambda):
  17723. def interp_exp(self, e, env):
  17724. match e:
  17725. case Inject(value, typ):
  17726. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17727. case Project(value, typ):
  17728. match self.interp_exp(value, env):
  17729. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17730. return val
  17731. case _:
  17732. raise Exception('failed project to ' + self.type_to_tag(typ))
  17733. case Call(Name('any_tuple_load'), [tup, index]):
  17734. match self.interp_exp(tup, env):
  17735. case Tagged(v, tag):
  17736. return v[self.interp_exp(index, env)]
  17737. case _:
  17738. raise Exception('in any_tuple_load untagged value')
  17739. case Call(Name('any_len'), [value]):
  17740. match self.interp_exp(value, env):
  17741. case Tagged(value, tag):
  17742. return len(value)
  17743. case _:
  17744. raise Exception('interp any_len untagged value')
  17745. case Call(Name('arity'), [fun]):
  17746. return self.arity(self.interp_exp(fun, env))
  17747. case _:
  17748. return super().interp_exp(e, env)
  17749. \end{lstlisting}
  17750. \fi}
  17751. \end{tcolorbox}
  17752. \caption{Interpreter for \LangAny{}.}
  17753. \label{fig:interp-Lany}
  17754. \end{figure}
  17755. \begin{figure}[btp]
  17756. \begin{tcolorbox}[colback=white]
  17757. {\if\edition\racketEd
  17758. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17759. (define/public (apply-inject v tg) (Tagged v tg))
  17760. (define/public (apply-project v ty2)
  17761. (define tag2 (any-tag ty2))
  17762. (match v
  17763. [(Tagged v1 tag1)
  17764. (cond
  17765. [(eq? tag1 tag2)
  17766. (match ty2
  17767. [`(Vector ,ts ...)
  17768. (define l1 ((interp-op 'vector-length) v1))
  17769. (cond
  17770. [(eq? l1 (length ts)) v1]
  17771. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17772. l1 (length ts))])]
  17773. [`(,ts ... -> ,rt)
  17774. (match v1
  17775. [`(function ,xs ,body ,env)
  17776. (cond [(eq? (length xs) (length ts)) v1]
  17777. [else
  17778. (error 'apply-project "arity mismatch ~a != ~a"
  17779. (length xs) (length ts))])]
  17780. [else (error 'apply-project "expected function not ~a" v1)])]
  17781. [else v1])]
  17782. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17783. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17784. \end{lstlisting}
  17785. \fi}
  17786. {\if\edition\pythonEd\pythonColor
  17787. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17788. class InterpLany(InterpLlambda):
  17789. def type_to_tag(self, typ):
  17790. match typ:
  17791. case FunctionType(params, rt):
  17792. return 'function'
  17793. case TupleType(fields):
  17794. return 'tuple'
  17795. case IntType():
  17796. return 'int'
  17797. case BoolType():
  17798. return 'bool'
  17799. case _:
  17800. raise Exception('type_to_tag unexpected ' + repr(typ))
  17801. def arity(self, v):
  17802. match v:
  17803. case Function(name, params, body, env):
  17804. return len(params)
  17805. case _:
  17806. raise Exception('Lany arity unexpected ' + repr(v))
  17807. \end{lstlisting}
  17808. \fi}
  17809. \end{tcolorbox}
  17810. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17811. \label{fig:interp-Lany-aux}
  17812. \end{figure}
  17813. \clearpage
  17814. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17815. \label{sec:compile-r7}
  17816. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17817. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17818. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17819. is that given any subexpression $e$ in the \LangDyn{} program, the
  17820. pass will produce an expression $e'$ in \LangAny{} that has type
  17821. \ANYTY{}. For example, the first row in
  17822. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17823. \TRUE{}, which must be injected to produce an expression of type
  17824. \ANYTY{}.
  17825. %
  17826. The compilation of addition is shown in the second row of
  17827. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17828. representative of many primitive operations: the arguments have type
  17829. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17830. be performed.
  17831. The compilation of \key{lambda} (third row of
  17832. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17833. produce type annotations: we simply use \ANYTY{}.
  17834. %
  17835. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17836. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17837. this pass has to account for some differences in behavior between
  17838. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17839. permissive than \LangAny{} regarding what kind of values can be used
  17840. in various places. For example, the condition of an \key{if} does
  17841. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17842. of the same type (in that case the result is \code{\#f}).}
  17843. \begin{figure}[btp]
  17844. \centering
  17845. \begin{tcolorbox}[colback=white]
  17846. {\if\edition\racketEd
  17847. \begin{tabular}{lll}
  17848. \begin{minipage}{0.27\textwidth}
  17849. \begin{lstlisting}
  17850. #t
  17851. \end{lstlisting}
  17852. \end{minipage}
  17853. &
  17854. $\Rightarrow$
  17855. &
  17856. \begin{minipage}{0.65\textwidth}
  17857. \begin{lstlisting}
  17858. (inject #t Boolean)
  17859. \end{lstlisting}
  17860. \end{minipage}
  17861. \\[2ex]\hline
  17862. \begin{minipage}{0.27\textwidth}
  17863. \begin{lstlisting}
  17864. (+ |$e_1$| |$e_2$|)
  17865. \end{lstlisting}
  17866. \end{minipage}
  17867. &
  17868. $\Rightarrow$
  17869. &
  17870. \begin{minipage}{0.65\textwidth}
  17871. \begin{lstlisting}
  17872. (inject
  17873. (+ (project |$e'_1$| Integer)
  17874. (project |$e'_2$| Integer))
  17875. Integer)
  17876. \end{lstlisting}
  17877. \end{minipage}
  17878. \\[2ex]\hline
  17879. \begin{minipage}{0.27\textwidth}
  17880. \begin{lstlisting}
  17881. (lambda (|$x_1 \ldots$|) |$e$|)
  17882. \end{lstlisting}
  17883. \end{minipage}
  17884. &
  17885. $\Rightarrow$
  17886. &
  17887. \begin{minipage}{0.65\textwidth}
  17888. \begin{lstlisting}
  17889. (inject
  17890. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17891. (Any|$\ldots$|Any -> Any))
  17892. \end{lstlisting}
  17893. \end{minipage}
  17894. \\[2ex]\hline
  17895. \begin{minipage}{0.27\textwidth}
  17896. \begin{lstlisting}
  17897. (|$e_0$| |$e_1 \ldots e_n$|)
  17898. \end{lstlisting}
  17899. \end{minipage}
  17900. &
  17901. $\Rightarrow$
  17902. &
  17903. \begin{minipage}{0.65\textwidth}
  17904. \begin{lstlisting}
  17905. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17906. \end{lstlisting}
  17907. \end{minipage}
  17908. \\[2ex]\hline
  17909. \begin{minipage}{0.27\textwidth}
  17910. \begin{lstlisting}
  17911. (vector-ref |$e_1$| |$e_2$|)
  17912. \end{lstlisting}
  17913. \end{minipage}
  17914. &
  17915. $\Rightarrow$
  17916. &
  17917. \begin{minipage}{0.65\textwidth}
  17918. \begin{lstlisting}
  17919. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17920. \end{lstlisting}
  17921. \end{minipage}
  17922. \\[2ex]\hline
  17923. \begin{minipage}{0.27\textwidth}
  17924. \begin{lstlisting}
  17925. (if |$e_1$| |$e_2$| |$e_3$|)
  17926. \end{lstlisting}
  17927. \end{minipage}
  17928. &
  17929. $\Rightarrow$
  17930. &
  17931. \begin{minipage}{0.65\textwidth}
  17932. \begin{lstlisting}
  17933. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17934. \end{lstlisting}
  17935. \end{minipage}
  17936. \\[2ex]\hline
  17937. \begin{minipage}{0.27\textwidth}
  17938. \begin{lstlisting}
  17939. (eq? |$e_1$| |$e_2$|)
  17940. \end{lstlisting}
  17941. \end{minipage}
  17942. &
  17943. $\Rightarrow$
  17944. &
  17945. \begin{minipage}{0.65\textwidth}
  17946. \begin{lstlisting}
  17947. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17948. \end{lstlisting}
  17949. \end{minipage}
  17950. \\[2ex]\hline
  17951. \begin{minipage}{0.27\textwidth}
  17952. \begin{lstlisting}
  17953. (not |$e_1$|)
  17954. \end{lstlisting}
  17955. \end{minipage}
  17956. &
  17957. $\Rightarrow$
  17958. &
  17959. \begin{minipage}{0.65\textwidth}
  17960. \begin{lstlisting}
  17961. (if (eq? |$e'_1$| (inject #f Boolean))
  17962. (inject #t Boolean) (inject #f Boolean))
  17963. \end{lstlisting}
  17964. \end{minipage}
  17965. \end{tabular}
  17966. \fi}
  17967. {\if\edition\pythonEd\pythonColor
  17968. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17969. \begin{minipage}{0.23\textwidth}
  17970. \begin{lstlisting}
  17971. True
  17972. \end{lstlisting}
  17973. \end{minipage}
  17974. &
  17975. $\Rightarrow$
  17976. &
  17977. \begin{minipage}{0.7\textwidth}
  17978. \begin{lstlisting}
  17979. Inject(True, BoolType())
  17980. \end{lstlisting}
  17981. \end{minipage}
  17982. \\[2ex]\hline
  17983. \begin{minipage}{0.23\textwidth}
  17984. \begin{lstlisting}
  17985. |$e_1$| + |$e_2$|
  17986. \end{lstlisting}
  17987. \end{minipage}
  17988. &
  17989. $\Rightarrow$
  17990. &
  17991. \begin{minipage}{0.7\textwidth}
  17992. \begin{lstlisting}
  17993. Inject(Project(|$e'_1$|, IntType())
  17994. + Project(|$e'_2$|, IntType()),
  17995. IntType())
  17996. \end{lstlisting}
  17997. \end{minipage}
  17998. \\[2ex]\hline
  17999. \begin{minipage}{0.23\textwidth}
  18000. \begin{lstlisting}
  18001. lambda |$x_1 \ldots$|: |$e$|
  18002. \end{lstlisting}
  18003. \end{minipage}
  18004. &
  18005. $\Rightarrow$
  18006. &
  18007. \begin{minipage}{0.7\textwidth}
  18008. \begin{lstlisting}
  18009. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18010. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18011. \end{lstlisting}
  18012. \end{minipage}
  18013. \\[2ex]\hline
  18014. \begin{minipage}{0.23\textwidth}
  18015. \begin{lstlisting}
  18016. |$e_0$|(|$e_1 \ldots e_n$|)
  18017. \end{lstlisting}
  18018. \end{minipage}
  18019. &
  18020. $\Rightarrow$
  18021. &
  18022. \begin{minipage}{0.7\textwidth}
  18023. \begin{lstlisting}
  18024. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18025. AnyType())), |$e'_1, \ldots, e'_n$|)
  18026. \end{lstlisting}
  18027. \end{minipage}
  18028. \\[2ex]\hline
  18029. \begin{minipage}{0.23\textwidth}
  18030. \begin{lstlisting}
  18031. |$e_1$|[|$e_2$|]
  18032. \end{lstlisting}
  18033. \end{minipage}
  18034. &
  18035. $\Rightarrow$
  18036. &
  18037. \begin{minipage}{0.7\textwidth}
  18038. \begin{lstlisting}
  18039. Call(Name('any_tuple_load'),
  18040. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18041. \end{lstlisting}
  18042. \end{minipage}
  18043. %% \begin{minipage}{0.23\textwidth}
  18044. %% \begin{lstlisting}
  18045. %% |$e_2$| if |$e_1$| else |$e_3$|
  18046. %% \end{lstlisting}
  18047. %% \end{minipage}
  18048. %% &
  18049. %% $\Rightarrow$
  18050. %% &
  18051. %% \begin{minipage}{0.7\textwidth}
  18052. %% \begin{lstlisting}
  18053. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18054. %% \end{lstlisting}
  18055. %% \end{minipage}
  18056. %% \\[2ex]\hline
  18057. %% \begin{minipage}{0.23\textwidth}
  18058. %% \begin{lstlisting}
  18059. %% (eq? |$e_1$| |$e_2$|)
  18060. %% \end{lstlisting}
  18061. %% \end{minipage}
  18062. %% &
  18063. %% $\Rightarrow$
  18064. %% &
  18065. %% \begin{minipage}{0.7\textwidth}
  18066. %% \begin{lstlisting}
  18067. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18068. %% \end{lstlisting}
  18069. %% \end{minipage}
  18070. %% \\[2ex]\hline
  18071. %% \begin{minipage}{0.23\textwidth}
  18072. %% \begin{lstlisting}
  18073. %% (not |$e_1$|)
  18074. %% \end{lstlisting}
  18075. %% \end{minipage}
  18076. %% &
  18077. %% $\Rightarrow$
  18078. %% &
  18079. %% \begin{minipage}{0.7\textwidth}
  18080. %% \begin{lstlisting}
  18081. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18082. %% (inject #t Boolean) (inject #f Boolean))
  18083. %% \end{lstlisting}
  18084. %% \end{minipage}
  18085. %% \\[2ex]\hline
  18086. \\\hline
  18087. \end{tabular}
  18088. \fi}
  18089. \end{tcolorbox}
  18090. \caption{Cast insertion.}
  18091. \label{fig:compile-r7-Lany}
  18092. \end{figure}
  18093. \section{Reveal Casts}
  18094. \label{sec:reveal-casts-Lany}
  18095. % TODO: define R'_6
  18096. In the \code{reveal\_casts} pass, we recommend compiling
  18097. \code{Project} into a conditional expression that checks whether the
  18098. value's tag matches the target type; if it does, the value is
  18099. converted to a value of the target type by removing the tag; if it
  18100. does not, the program exits.
  18101. %
  18102. {\if\edition\racketEd
  18103. %
  18104. To perform these actions we need a new primitive operation,
  18105. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18106. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18107. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18108. underlying value from a tagged value. The \code{ValueOf} form
  18109. includes the type for the underlying value that is used by the type
  18110. checker.
  18111. %
  18112. \fi}
  18113. %
  18114. {\if\edition\pythonEd\pythonColor
  18115. %
  18116. To perform these actions we need two new AST classes: \code{TagOf} and
  18117. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18118. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18119. the underlying value from a tagged value. The \code{ValueOf}
  18120. operation includes the type for the underlying value that is used by
  18121. the type checker.
  18122. %
  18123. \fi}
  18124. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18125. \code{Project} can be translated as follows:
  18126. \begin{center}
  18127. \begin{minipage}{1.0\textwidth}
  18128. {\if\edition\racketEd
  18129. \begin{lstlisting}
  18130. (Project |$e$| |$\FType$|)
  18131. |$\Rightarrow$|
  18132. (Let |$\itm{tmp}$| |$e'$|
  18133. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18134. (Int |$\itm{tagof}(\FType)$|)))
  18135. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18136. (Exit)))
  18137. \end{lstlisting}
  18138. \fi}
  18139. {\if\edition\pythonEd\pythonColor
  18140. \begin{lstlisting}
  18141. Project(|$e$|, |$\FType$|)
  18142. |$\Rightarrow$|
  18143. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18144. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18145. [Constant(|$\itm{tagof}(\FType)$|)]),
  18146. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18147. Call(Name('exit'), [])))
  18148. \end{lstlisting}
  18149. \fi}
  18150. \end{minipage}
  18151. \end{center}
  18152. If the target type of the projection is a tuple or function type, then
  18153. there is a bit more work to do. For tuples, check that the length of
  18154. the tuple type matches the length of the tuple. For functions, check
  18155. that the number of parameters in the function type matches the
  18156. function's arity.
  18157. Regarding \code{Inject}, we recommend compiling it to a slightly
  18158. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18159. takes a tag instead of a type.
  18160. \begin{center}
  18161. \begin{minipage}{1.0\textwidth}
  18162. {\if\edition\racketEd
  18163. \begin{lstlisting}
  18164. (Inject |$e$| |$\FType$|)
  18165. |$\Rightarrow$|
  18166. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18167. \end{lstlisting}
  18168. \fi}
  18169. {\if\edition\pythonEd\pythonColor
  18170. \begin{lstlisting}
  18171. Inject(|$e$|, |$\FType$|)
  18172. |$\Rightarrow$|
  18173. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18174. \end{lstlisting}
  18175. \fi}
  18176. \end{minipage}
  18177. \end{center}
  18178. {\if\edition\pythonEd\pythonColor
  18179. %
  18180. The introduction of \code{make\_any} makes it difficult to use
  18181. bidirectional type checking because we no longer have an expected type
  18182. to use for type checking the expression $e'$. Thus, we run into
  18183. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18184. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18185. annotated lambda) that contains its return type and the types of its
  18186. parameters.
  18187. %
  18188. \fi}
  18189. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18190. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18191. translation of \code{Project}.}
  18192. {\if\edition\racketEd
  18193. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18194. combine the projection action with the vector operation. Also, the
  18195. read and write operations allow arbitrary expressions for the index, so
  18196. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18197. cannot guarantee that the index is within bounds. Thus, we insert code
  18198. to perform bounds checking at runtime. The translation for
  18199. \code{any-vector-ref} is as follows, and the other two operations are
  18200. translated in a similar way:
  18201. \begin{center}
  18202. \begin{minipage}{0.95\textwidth}
  18203. \begin{lstlisting}
  18204. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18205. |$\Rightarrow$|
  18206. (Let |$v$| |$e'_1$|
  18207. (Let |$i$| |$e'_2$|
  18208. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18209. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18210. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18211. (Exit))
  18212. (Exit))))
  18213. \end{lstlisting}
  18214. \end{minipage}
  18215. \end{center}
  18216. \fi}
  18217. %
  18218. {\if\edition\pythonEd\pythonColor
  18219. %
  18220. The \code{any\_tuple\_load} operation combines the projection action
  18221. with the load operation. Also, the load operation allows arbitrary
  18222. expressions for the index, so the type checker for \LangAny{}
  18223. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18224. within bounds. Thus, we insert code to perform bounds checking at
  18225. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18226. \begin{lstlisting}
  18227. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18228. |$\Rightarrow$|
  18229. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18230. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18231. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18232. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18233. Call(Name('exit'), [])),
  18234. Call(Name('exit'), [])))
  18235. \end{lstlisting}
  18236. \fi}
  18237. {\if\edition\pythonEd\pythonColor
  18238. \section{Assignment Conversion}
  18239. \label{sec:convert-assignments-Lany}
  18240. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18241. \code{AnnLambda} AST classes.
  18242. \section{Closure Conversion}
  18243. \label{sec:closure-conversion-Lany}
  18244. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18245. \code{AnnLambda} AST classes.
  18246. \fi}
  18247. \section{Remove Complex Operands}
  18248. \label{sec:rco-Lany}
  18249. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18250. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18251. %
  18252. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18253. complex expressions. Their subexpressions must be atomic.}
  18254. \section{Explicate Control and \LangCAny{}}
  18255. \label{sec:explicate-Lany}
  18256. The output of \code{explicate\_control} is the \LangCAny{} language,
  18257. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18258. %
  18259. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18260. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18261. note that the index argument of \code{vector-ref} and
  18262. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18263. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18264. %
  18265. \python{Update the auxiliary functions \code{explicate\_tail},
  18266. \code{explicate\_effect}, and \code{explicate\_pred} as
  18267. appropriate to handle the new expressions in \LangCAny{}. }
  18268. \newcommand{\CanyASTPython}{
  18269. \begin{array}{lcl}
  18270. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18271. &\MID& \key{TagOf}\LP \Atm \RP
  18272. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18273. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18274. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18275. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18276. \end{array}
  18277. }
  18278. \newcommand{\CanyASTRacket}{
  18279. \begin{array}{lcl}
  18280. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18281. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18282. &\MID& \VALUEOF{\Atm}{\FType} \\
  18283. \Tail &::= & \LP\key{Exit}\RP
  18284. \end{array}
  18285. }
  18286. \begin{figure}[tp]
  18287. \begin{tcolorbox}[colback=white]
  18288. \small
  18289. {\if\edition\racketEd
  18290. \[
  18291. \begin{array}{l}
  18292. \gray{\CvarASTRacket} \\ \hline
  18293. \gray{\CifASTRacket} \\ \hline
  18294. \gray{\CloopASTRacket} \\ \hline
  18295. \gray{\CtupASTRacket} \\ \hline
  18296. \gray{\CfunASTRacket} \\ \hline
  18297. \gray{\ClambdaASTRacket} \\ \hline
  18298. \CanyASTRacket \\
  18299. \begin{array}{lcl}
  18300. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18301. \end{array}
  18302. \end{array}
  18303. \]
  18304. \fi}
  18305. {\if\edition\pythonEd\pythonColor
  18306. \[
  18307. \begin{array}{l}
  18308. \gray{\CifASTPython} \\ \hline
  18309. \gray{\CtupASTPython} \\ \hline
  18310. \gray{\CfunASTPython} \\ \hline
  18311. \gray{\ClambdaASTPython} \\ \hline
  18312. \CanyASTPython \\
  18313. \begin{array}{lcl}
  18314. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18315. \end{array}
  18316. \end{array}
  18317. \]
  18318. \fi}
  18319. \end{tcolorbox}
  18320. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18321. \label{fig:c5-syntax}
  18322. \end{figure}
  18323. \section{Select Instructions}
  18324. \label{sec:select-Lany}
  18325. \index{subject}{select instructions}
  18326. In the \code{select\_instructions} pass, we translate the primitive
  18327. operations on the \ANYTY{} type to x86 instructions that manipulate
  18328. the three tag bits of the tagged value. In the following descriptions,
  18329. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18330. of translating $e$ into an x86 argument:
  18331. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18332. We recommend compiling the
  18333. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18334. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18335. shifts the destination to the left by the number of bits specified by its
  18336. source argument (in this case three, the length of the tag), and it
  18337. preserves the sign of the integer. We use the \key{orq} instruction to
  18338. combine the tag and the value to form the tagged value.
  18339. {\if\edition\racketEd
  18340. \begin{lstlisting}
  18341. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18342. |$\Rightarrow$|
  18343. movq |$e'$|, |\itm{lhs'}|
  18344. salq $3, |\itm{lhs'}|
  18345. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18346. \end{lstlisting}
  18347. \fi}
  18348. %
  18349. {\if\edition\pythonEd\pythonColor
  18350. \begin{lstlisting}
  18351. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18352. |$\Rightarrow$|
  18353. movq |$e'$|, |\itm{lhs'}|
  18354. salq $3, |\itm{lhs'}|
  18355. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18356. \end{lstlisting}
  18357. \fi}
  18358. %
  18359. The instruction selection\index{subject}{instruction selection} for
  18360. tuples and procedures is different because there is no need to shift
  18361. them to the left. The rightmost 3 bits are already zeros, so we simply
  18362. combine the value and the tag using \key{orq}. \\
  18363. %
  18364. {\if\edition\racketEd
  18365. \begin{center}
  18366. \begin{minipage}{\textwidth}
  18367. \begin{lstlisting}
  18368. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18369. |$\Rightarrow$|
  18370. movq |$e'$|, |\itm{lhs'}|
  18371. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18372. \end{lstlisting}
  18373. \end{minipage}
  18374. \end{center}
  18375. \fi}
  18376. %
  18377. {\if\edition\pythonEd\pythonColor
  18378. \begin{lstlisting}
  18379. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18380. |$\Rightarrow$|
  18381. movq |$e'$|, |\itm{lhs'}|
  18382. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18383. \end{lstlisting}
  18384. \fi}
  18385. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18386. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18387. operation extracts the type tag from a value of type \ANYTY{}. The
  18388. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18389. bitwise-and of the value with $111$ ($7$ decimal).
  18390. %
  18391. {\if\edition\racketEd
  18392. \begin{lstlisting}
  18393. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18394. |$\Rightarrow$|
  18395. movq |$e'$|, |\itm{lhs'}|
  18396. andq $7, |\itm{lhs'}|
  18397. \end{lstlisting}
  18398. \fi}
  18399. %
  18400. {\if\edition\pythonEd\pythonColor
  18401. \begin{lstlisting}
  18402. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18403. |$\Rightarrow$|
  18404. movq |$e'$|, |\itm{lhs'}|
  18405. andq $7, |\itm{lhs'}|
  18406. \end{lstlisting}
  18407. \fi}
  18408. \paragraph{\code{ValueOf}}
  18409. The instructions for \key{ValueOf} also differ, depending on whether
  18410. the type $T$ is a pointer (tuple or function) or not (integer or
  18411. Boolean). The following shows the instruction
  18412. selection for integers and
  18413. Booleans, in which we produce an untagged value by shifting it to the
  18414. right by 3 bits:
  18415. %
  18416. {\if\edition\racketEd
  18417. \begin{lstlisting}
  18418. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18419. |$\Rightarrow$|
  18420. movq |$e'$|, |\itm{lhs'}|
  18421. sarq $3, |\itm{lhs'}|
  18422. \end{lstlisting}
  18423. \fi}
  18424. %
  18425. {\if\edition\pythonEd\pythonColor
  18426. \begin{lstlisting}
  18427. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18428. |$\Rightarrow$|
  18429. movq |$e'$|, |\itm{lhs'}|
  18430. sarq $3, |\itm{lhs'}|
  18431. \end{lstlisting}
  18432. \fi}
  18433. %
  18434. In the case for tuples and procedures, we zero out the rightmost 3
  18435. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18436. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18437. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18438. Finally, we apply \code{andq} with the tagged value to get the desired
  18439. result.
  18440. %
  18441. {\if\edition\racketEd
  18442. \begin{lstlisting}
  18443. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18444. |$\Rightarrow$|
  18445. movq $|$-8$|, |\itm{lhs'}|
  18446. andq |$e'$|, |\itm{lhs'}|
  18447. \end{lstlisting}
  18448. \fi}
  18449. %
  18450. {\if\edition\pythonEd\pythonColor
  18451. \begin{lstlisting}
  18452. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18453. |$\Rightarrow$|
  18454. movq $|$-8$|, |\itm{lhs'}|
  18455. andq |$e'$|, |\itm{lhs'}|
  18456. \end{lstlisting}
  18457. \fi}
  18458. %% \paragraph{Type Predicates} We leave it to the reader to
  18459. %% devise a sequence of instructions to implement the type predicates
  18460. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18461. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18462. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18463. operation combines the effect of \code{ValueOf} with accessing the
  18464. length of a tuple from the tag stored at the zero index of the tuple.
  18465. {\if\edition\racketEd
  18466. \begin{lstlisting}
  18467. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18468. |$\Longrightarrow$|
  18469. movq $|$-8$|, %r11
  18470. andq |$e_1'$|, %r11
  18471. movq 0(%r11), %r11
  18472. andq $126, %r11
  18473. sarq $1, %r11
  18474. movq %r11, |$\itm{lhs'}$|
  18475. \end{lstlisting}
  18476. \fi}
  18477. {\if\edition\pythonEd\pythonColor
  18478. \begin{lstlisting}
  18479. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18480. |$\Longrightarrow$|
  18481. movq $|$-8$|, %r11
  18482. andq |$e_1'$|, %r11
  18483. movq 0(%r11), %r11
  18484. andq $126, %r11
  18485. sarq $1, %r11
  18486. movq %r11, |$\itm{lhs'}$|
  18487. \end{lstlisting}
  18488. \fi}
  18489. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18490. This operation combines the effect of \code{ValueOf} with reading an
  18491. element of the tuple (see
  18492. section~\ref{sec:select-instructions-gc}). However, the index may be
  18493. an arbitrary atom, so instead of computing the offset at compile time,
  18494. we must generate instructions to compute the offset at runtime as
  18495. follows. Note the use of the new instruction \code{imulq}.
  18496. \begin{center}
  18497. \begin{minipage}{0.96\textwidth}
  18498. {\if\edition\racketEd
  18499. \begin{lstlisting}
  18500. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18501. |$\Longrightarrow$|
  18502. movq |$\neg 111$|, %r11
  18503. andq |$e_1'$|, %r11
  18504. movq |$e_2'$|, %rax
  18505. addq $1, %rax
  18506. imulq $8, %rax
  18507. addq %rax, %r11
  18508. movq 0(%r11) |$\itm{lhs'}$|
  18509. \end{lstlisting}
  18510. \fi}
  18511. %
  18512. {\if\edition\pythonEd\pythonColor
  18513. \begin{lstlisting}
  18514. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18515. |$\Longrightarrow$|
  18516. movq $|$-8$|, %r11
  18517. andq |$e_1'$|, %r11
  18518. movq |$e_2'$|, %rax
  18519. addq $1, %rax
  18520. imulq $8, %rax
  18521. addq %rax, %r11
  18522. movq 0(%r11) |$\itm{lhs'}$|
  18523. \end{lstlisting}
  18524. \fi}
  18525. \end{minipage}
  18526. \end{center}
  18527. % $ pacify font lock
  18528. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18529. %% The code generation for
  18530. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18531. %% analogous to the above translation for reading from a tuple.
  18532. \section{Register Allocation for \LangAny{} }
  18533. \label{sec:register-allocation-Lany}
  18534. \index{subject}{register allocation}
  18535. There is an interesting interaction between tagged values and garbage
  18536. collection that has an impact on register allocation. A variable of
  18537. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18538. that needs to be inspected and copied during garbage collection. Thus,
  18539. we need to treat variables of type \ANYTY{} in a similar way to
  18540. variables of tuple type for purposes of register allocation,
  18541. with particular attention to the following:
  18542. \begin{itemize}
  18543. \item If a variable of type \ANYTY{} is live during a function call,
  18544. then it must be spilled. This can be accomplished by changing
  18545. \code{build\_interference} to mark all variables of type \ANYTY{}
  18546. that are live after a \code{callq} to be interfering with all the
  18547. registers.
  18548. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18549. the root stack instead of the normal procedure call stack.
  18550. \end{itemize}
  18551. Another concern regarding the root stack is that the garbage collector
  18552. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18553. tagged value that points to a tuple, and (3) a tagged value that is
  18554. not a tuple. We enable this differentiation by choosing not to use the
  18555. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18556. reserved for identifying plain old pointers to tuples. That way, if
  18557. one of the first three bits is set, then we have a tagged value and
  18558. inspecting the tag can differentiate between tuples ($010$) and the
  18559. other kinds of values.
  18560. %% \begin{exercise}\normalfont
  18561. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18562. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18563. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18564. %% compiler on these new programs and all of your previously created test
  18565. %% programs.
  18566. %% \end{exercise}
  18567. \begin{exercise}\normalfont\normalsize
  18568. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18569. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18570. by removing type annotations. Add five more test programs that
  18571. specifically rely on the language being dynamically typed. That is,
  18572. they should not be legal programs in a statically typed language, but
  18573. nevertheless they should be valid \LangDyn{} programs that run to
  18574. completion without error.
  18575. \end{exercise}
  18576. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18577. for the compilation of \LangDyn{}.
  18578. \begin{figure}[bthp]
  18579. \begin{tcolorbox}[colback=white]
  18580. {\if\edition\racketEd
  18581. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18582. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18583. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18584. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18585. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18586. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18587. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18588. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18589. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18590. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18591. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18592. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18593. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18594. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18595. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18596. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18597. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18598. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18599. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18600. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18601. \path[->,bend left=15] (Lfun) edge [above] node
  18602. {\ttfamily\footnotesize shrink} (Lfun-2);
  18603. \path[->,bend left=15] (Lfun-2) edge [above] node
  18604. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18605. \path[->,bend left=15] (Lfun-3) edge [above] node
  18606. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18607. \path[->,bend left=15] (Lfun-4) edge [left] node
  18608. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18609. \path[->,bend left=15] (Lfun-5) edge [below] node
  18610. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18611. \path[->,bend left=15] (Lfun-6) edge [below] node
  18612. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18613. \path[->,bend right=15] (Lfun-7) edge [above] node
  18614. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18615. \path[->,bend right=15] (F1-2) edge [right] node
  18616. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18617. \path[->,bend right=15] (F1-3) edge [below] node
  18618. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18619. \path[->,bend right=15] (F1-4) edge [below] node
  18620. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18621. \path[->,bend left=15] (F1-5) edge [above] node
  18622. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18623. \path[->,bend left=10] (F1-6) edge [below] node
  18624. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18625. \path[->,bend left=15] (C3-2) edge [right] node
  18626. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18627. \path[->,bend right=15] (x86-2) edge [right] node
  18628. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18629. \path[->,bend right=15] (x86-2-1) edge [below] node
  18630. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18631. \path[->,bend right=15] (x86-2-2) edge [right] node
  18632. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18633. \path[->,bend left=15] (x86-3) edge [above] node
  18634. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18635. \path[->,bend left=15] (x86-4) edge [right] node
  18636. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18637. \end{tikzpicture}
  18638. \fi}
  18639. {\if\edition\pythonEd\pythonColor
  18640. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18641. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18642. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18643. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18644. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18645. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18646. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18647. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18648. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18649. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18650. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18651. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18652. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18653. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18654. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18655. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18656. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18657. \path[->,bend left=15] (Lfun) edge [above] node
  18658. {\ttfamily\footnotesize shrink} (Lfun-2);
  18659. \path[->,bend left=15] (Lfun-2) edge [above] node
  18660. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18661. \path[->,bend left=15] (Lfun-3) edge [above] node
  18662. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18663. \path[->,bend left=15] (Lfun-4) edge [left] node
  18664. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18665. \path[->,bend left=15] (Lfun-5) edge [below] node
  18666. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18667. \path[->,bend right=15] (Lfun-6) edge [above] node
  18668. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18669. \path[->,bend right=15] (Lfun-7) edge [above] node
  18670. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18671. \path[->,bend right=15] (F1-2) edge [right] node
  18672. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18673. \path[->,bend right=15] (F1-3) edge [below] node
  18674. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18675. \path[->,bend left=15] (F1-5) edge [above] node
  18676. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18677. \path[->,bend left=10] (F1-6) edge [below] node
  18678. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18679. \path[->,bend right=15] (C3-2) edge [right] node
  18680. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18681. \path[->,bend right=15] (x86-2) edge [below] node
  18682. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18683. \path[->,bend right=15] (x86-3) edge [below] node
  18684. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18685. \path[->,bend left=15] (x86-4) edge [above] node
  18686. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18687. \end{tikzpicture}
  18688. \fi}
  18689. \end{tcolorbox}
  18690. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18691. \label{fig:Ldyn-passes}
  18692. \end{figure}
  18693. % Further Reading
  18694. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18695. %% {\if\edition\pythonEd\pythonColor
  18696. %% \chapter{Objects}
  18697. %% \label{ch:Lobject}
  18698. %% \index{subject}{objects}
  18699. %% \index{subject}{classes}
  18700. %% \setcounter{footnote}{0}
  18701. %% \fi}
  18702. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18703. \chapter{Gradual Typing}
  18704. \label{ch:Lgrad}
  18705. \index{subject}{gradual typing}
  18706. \setcounter{footnote}{0}
  18707. This chapter studies the language \LangGrad{}, in which the programmer
  18708. can choose between static and dynamic type checking in different parts
  18709. of a program, thereby mixing the statically typed \LangLam{} language
  18710. with the dynamically typed \LangDyn{}. There are several approaches to
  18711. mixing static and dynamic typing, including multilanguage
  18712. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18713. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18714. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18715. programmer controls the amount of static versus dynamic checking by
  18716. adding or removing type annotations on parameters and
  18717. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18718. The definition of the concrete syntax of \LangGrad{} is shown in
  18719. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18720. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18721. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18722. annotations are optional, which is specified in the grammar using the
  18723. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18724. annotations are not optional, but we use the \CANYTY{} type when a type
  18725. annotation is absent.
  18726. %
  18727. Both the type checker and the interpreter for \LangGrad{} require some
  18728. interesting changes to enable gradual typing, which we discuss in the
  18729. next two sections.
  18730. \newcommand{\LgradGrammarRacket}{
  18731. \begin{array}{lcl}
  18732. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18733. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18734. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18735. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18736. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18737. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18738. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18739. \end{array}
  18740. }
  18741. \newcommand{\LgradASTRacket}{
  18742. \begin{array}{lcl}
  18743. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18744. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18745. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18746. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18747. \itm{op} &::=& \code{procedure-arity} \\
  18748. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18749. \end{array}
  18750. }
  18751. \newcommand{\LgradGrammarPython}{
  18752. \begin{array}{lcl}
  18753. \Type &::=& \key{Any}
  18754. \MID \key{int}
  18755. \MID \key{bool}
  18756. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18757. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18758. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18759. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18760. \MID \CARITY{\Exp} \\
  18761. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18762. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18763. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18764. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18765. \end{array}
  18766. }
  18767. \newcommand{\LgradASTPython}{
  18768. \begin{array}{lcl}
  18769. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18770. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18771. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18772. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18773. &\MID& \ARITY{\Exp} \\
  18774. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18775. \MID \RETURN{\Exp} \\
  18776. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18777. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18778. \end{array}
  18779. }
  18780. \begin{figure}[tbp]
  18781. \centering
  18782. \begin{tcolorbox}[colback=white]
  18783. \vspace{-5pt}
  18784. \small
  18785. {\if\edition\racketEd
  18786. \[
  18787. \begin{array}{l}
  18788. \gray{\LintGrammarRacket{}} \\ \hline
  18789. \gray{\LvarGrammarRacket{}} \\ \hline
  18790. \gray{\LifGrammarRacket{}} \\ \hline
  18791. \gray{\LwhileGrammarRacket} \\ \hline
  18792. \gray{\LtupGrammarRacket} \\ \hline
  18793. \LgradGrammarRacket \\
  18794. \begin{array}{lcl}
  18795. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18796. \end{array}
  18797. \end{array}
  18798. \]
  18799. \fi}
  18800. {\if\edition\pythonEd\pythonColor
  18801. \[
  18802. \begin{array}{l}
  18803. \gray{\LintGrammarPython{}} \\ \hline
  18804. \gray{\LvarGrammarPython{}} \\ \hline
  18805. \gray{\LifGrammarPython{}} \\ \hline
  18806. \gray{\LwhileGrammarPython} \\ \hline
  18807. \gray{\LtupGrammarPython} \\ \hline
  18808. \LgradGrammarPython \\
  18809. \begin{array}{lcl}
  18810. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18811. \end{array}
  18812. \end{array}
  18813. \]
  18814. \fi}
  18815. \end{tcolorbox}
  18816. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18817. \label{fig:Lgrad-concrete-syntax}
  18818. \end{figure}
  18819. \begin{figure}[tbp]
  18820. \centering
  18821. \begin{tcolorbox}[colback=white]
  18822. \small
  18823. {\if\edition\racketEd
  18824. \[
  18825. \begin{array}{l}
  18826. \gray{\LintOpAST} \\ \hline
  18827. \gray{\LvarASTRacket{}} \\ \hline
  18828. \gray{\LifASTRacket{}} \\ \hline
  18829. \gray{\LwhileASTRacket{}} \\ \hline
  18830. \gray{\LtupASTRacket{}} \\ \hline
  18831. \LgradASTRacket \\
  18832. \begin{array}{lcl}
  18833. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18834. \end{array}
  18835. \end{array}
  18836. \]
  18837. \fi}
  18838. {\if\edition\pythonEd\pythonColor
  18839. \[
  18840. \begin{array}{l}
  18841. \gray{\LintASTPython{}} \\ \hline
  18842. \gray{\LvarASTPython{}} \\ \hline
  18843. \gray{\LifASTPython{}} \\ \hline
  18844. \gray{\LwhileASTPython} \\ \hline
  18845. \gray{\LtupASTPython} \\ \hline
  18846. \LgradASTPython \\
  18847. \begin{array}{lcl}
  18848. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18849. \end{array}
  18850. \end{array}
  18851. \]
  18852. \fi}
  18853. \end{tcolorbox}
  18854. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18855. \label{fig:Lgrad-syntax}
  18856. \end{figure}
  18857. % TODO: more road map -Jeremy
  18858. %\clearpage
  18859. \section{Type Checking \LangGrad{}}
  18860. \label{sec:gradual-type-check}
  18861. We begin by discussing the type checking of a partially typed variant
  18862. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18863. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18864. statically typed, so there is nothing special happening there with
  18865. respect to type checking. On the other hand, the \code{inc} function
  18866. does not have type annotations, so the type checker assigns the type
  18867. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18868. \code{+} operator inside \code{inc}. It expects both arguments to have
  18869. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18870. a gradually typed language, such differences are allowed so long as
  18871. the types are \emph{consistent}; that is, they are equal except in
  18872. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18873. is consistent with every other type. Figure~\ref{fig:consistent}
  18874. shows the definition of the
  18875. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18876. %
  18877. So the type checker allows the \code{+} operator to be applied
  18878. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18879. %
  18880. Next consider the call to the \code{map} function shown in
  18881. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18882. tuple. The \code{inc} function has type
  18883. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18884. but parameter \code{f} of \code{map} has type
  18885. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18886. The type checker for \LangGrad{} accepts this call because the two types are
  18887. consistent.
  18888. \begin{figure}[hbtp]
  18889. % gradual_test_9.rkt
  18890. \begin{tcolorbox}[colback=white]
  18891. {\if\edition\racketEd
  18892. \begin{lstlisting}
  18893. (define (map [f : (Integer -> Integer)]
  18894. [v : (Vector Integer Integer)])
  18895. : (Vector Integer Integer)
  18896. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18897. (define (inc x) (+ x 1))
  18898. (vector-ref (map inc (vector 0 41)) 1)
  18899. \end{lstlisting}
  18900. \fi}
  18901. {\if\edition\pythonEd\pythonColor
  18902. \begin{lstlisting}
  18903. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18904. return f(v[0]), f(v[1])
  18905. def inc(x):
  18906. return x + 1
  18907. t = map(inc, (0, 41))
  18908. print(t[1])
  18909. \end{lstlisting}
  18910. \fi}
  18911. \end{tcolorbox}
  18912. \caption{A partially typed version of the \code{map} example.}
  18913. \label{fig:gradual-map}
  18914. \end{figure}
  18915. \begin{figure}[tbp]
  18916. \begin{tcolorbox}[colback=white]
  18917. {\if\edition\racketEd
  18918. \begin{lstlisting}
  18919. (define/public (consistent? t1 t2)
  18920. (match* (t1 t2)
  18921. [('Integer 'Integer) #t]
  18922. [('Boolean 'Boolean) #t]
  18923. [('Void 'Void) #t]
  18924. [('Any t2) #t]
  18925. [(t1 'Any) #t]
  18926. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18927. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18928. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18929. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18930. (consistent? rt1 rt2))]
  18931. [(other wise) #f]))
  18932. \end{lstlisting}
  18933. \fi}
  18934. {\if\edition\pythonEd\pythonColor
  18935. \begin{lstlisting}
  18936. def consistent(self, t1, t2):
  18937. match (t1, t2):
  18938. case (AnyType(), _):
  18939. return True
  18940. case (_, AnyType()):
  18941. return True
  18942. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18943. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18944. case (TupleType(ts1), TupleType(ts2)):
  18945. return all(map(self.consistent, ts1, ts2))
  18946. case (_, _):
  18947. return t1 == t2
  18948. \end{lstlisting}
  18949. \fi}
  18950. \vspace{-5pt}
  18951. \end{tcolorbox}
  18952. \caption{The consistency method on types.}
  18953. \label{fig:consistent}
  18954. \end{figure}
  18955. It is also helpful to consider how gradual typing handles programs with an
  18956. error, such as applying \code{map} to a function that sometimes
  18957. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18958. type checker for \LangGrad{} accepts this program because the type of
  18959. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18960. \code{map}; that is,
  18961. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18962. is consistent with
  18963. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18964. One might say that a gradual type checker is optimistic in that it
  18965. accepts programs that might execute without a runtime type error.
  18966. %
  18967. The definition of the type checker for \LangGrad{} is shown in
  18968. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18969. and \ref{fig:type-check-Lgradual-3}.
  18970. %% \begin{figure}[tp]
  18971. %% \centering
  18972. %% \fbox{
  18973. %% \begin{minipage}{0.96\textwidth}
  18974. %% \small
  18975. %% \[
  18976. %% \begin{array}{lcl}
  18977. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18978. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18979. %% \end{array}
  18980. %% \]
  18981. %% \end{minipage}
  18982. %% }
  18983. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18984. %% \label{fig:Lgrad-prime-syntax}
  18985. %% \end{figure}
  18986. \begin{figure}[tbp]
  18987. \begin{tcolorbox}[colback=white]
  18988. {\if\edition\racketEd
  18989. \begin{lstlisting}
  18990. (define (map [f : (Integer -> Integer)]
  18991. [v : (Vector Integer Integer)])
  18992. : (Vector Integer Integer)
  18993. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18994. (define (inc x) (+ x 1))
  18995. (define (true) #t)
  18996. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18997. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18998. \end{lstlisting}
  18999. \fi}
  19000. {\if\edition\pythonEd\pythonColor
  19001. \begin{lstlisting}
  19002. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19003. return f(v[0]), f(v[1])
  19004. def inc(x):
  19005. return x + 1
  19006. def true():
  19007. return True
  19008. def maybe_inc(x):
  19009. return inc(x) if input_int() == 0 else true()
  19010. t = map(maybe_inc, (0, 41))
  19011. print(t[1])
  19012. \end{lstlisting}
  19013. \fi}
  19014. \vspace{-5pt}
  19015. \end{tcolorbox}
  19016. \caption{A variant of the \code{map} example with an error.}
  19017. \label{fig:map-maybe_inc}
  19018. \end{figure}
  19019. Running this program with input \code{1} triggers an
  19020. error when the \code{maybe\_inc} function returns
  19021. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19022. performs checking at runtime to ensure the integrity of the static
  19023. types, such as the
  19024. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19025. annotation on
  19026. parameter \code{f} of \code{map}.
  19027. Here we give a preview of how the runtime checking is accomplished;
  19028. the following sections provide the details.
  19029. The runtime checking is carried out by a new \code{Cast} AST node that
  19030. is generated in a new pass named \code{cast\_insert}. The output of
  19031. \code{cast\_insert} is a program in the \LangCast{} language, which
  19032. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19033. %
  19034. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19035. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19036. inserted every time the type checker encounters two types that are
  19037. consistent but not equal. In the \code{inc} function, \code{x} is
  19038. cast to \INTTY{} and the result of the \code{+} is cast to
  19039. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19040. is cast from
  19041. \racket{\code{(Any -> Any)}}
  19042. \python{\code{Callable[[Any], Any]}}
  19043. to
  19044. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19045. %
  19046. In the next section we see how to interpret the \code{Cast} node.
  19047. \begin{figure}[btp]
  19048. \begin{tcolorbox}[colback=white]
  19049. {\if\edition\racketEd
  19050. \begin{lstlisting}
  19051. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19052. : (Vector Integer Integer)
  19053. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19054. (define (inc [x : Any]) : Any
  19055. (cast (+ (cast x Any Integer) 1) Integer Any))
  19056. (define (true) : Any (cast #t Boolean Any))
  19057. (define (maybe_inc [x : Any]) : Any
  19058. (if (eq? 0 (read)) (inc x) (true)))
  19059. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19060. (vector 0 41)) 0)
  19061. \end{lstlisting}
  19062. \fi}
  19063. {\if\edition\pythonEd\pythonColor
  19064. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19065. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19066. return f(v[0]), f(v[1])
  19067. def inc(x : Any) -> Any:
  19068. return Cast(Cast(x, Any, int) + 1, int, Any)
  19069. def true() -> Any:
  19070. return Cast(True, bool, Any)
  19071. def maybe_inc(x : Any) -> Any:
  19072. return inc(x) if input_int() == 0 else true()
  19073. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19074. (0, 41))
  19075. print(t[1])
  19076. \end{lstlisting}
  19077. \fi}
  19078. \vspace{-5pt}
  19079. \end{tcolorbox}
  19080. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19081. and \code{maybe\_inc} example.}
  19082. \label{fig:map-cast}
  19083. \end{figure}
  19084. {\if\edition\pythonEd\pythonColor
  19085. \begin{figure}[tbp]
  19086. \begin{tcolorbox}[colback=white]
  19087. \begin{lstlisting}
  19088. class TypeCheckLgrad(TypeCheckLlambda):
  19089. def type_check_exp(self, e, env) -> Type:
  19090. match e:
  19091. case Name(id):
  19092. return env[id]
  19093. case Constant(value) if isinstance(value, bool):
  19094. return BoolType()
  19095. case Constant(value) if isinstance(value, int):
  19096. return IntType()
  19097. case Call(Name('input_int'), []):
  19098. return IntType()
  19099. case BinOp(left, op, right):
  19100. left_type = self.type_check_exp(left, env)
  19101. self.check_consistent(left_type, IntType(), left)
  19102. right_type = self.type_check_exp(right, env)
  19103. self.check_consistent(right_type, IntType(), right)
  19104. return IntType()
  19105. case IfExp(test, body, orelse):
  19106. test_t = self.type_check_exp(test, env)
  19107. self.check_consistent(test_t, BoolType(), test)
  19108. body_t = self.type_check_exp(body, env)
  19109. orelse_t = self.type_check_exp(orelse, env)
  19110. self.check_consistent(body_t, orelse_t, e)
  19111. return self.join_types(body_t, orelse_t)
  19112. case Call(func, args):
  19113. func_t = self.type_check_exp(func, env)
  19114. args_t = [self.type_check_exp(arg, env) for arg in args]
  19115. match func_t:
  19116. case FunctionType(params_t, return_t) \
  19117. if len(params_t) == len(args_t):
  19118. for (arg_t, param_t) in zip(args_t, params_t):
  19119. self.check_consistent(param_t, arg_t, e)
  19120. return return_t
  19121. case AnyType():
  19122. return AnyType()
  19123. case _:
  19124. raise Exception('type_check_exp: in call, unexpected '
  19125. + repr(func_t))
  19126. ...
  19127. case _:
  19128. raise Exception('type_check_exp: unexpected ' + repr(e))
  19129. \end{lstlisting}
  19130. \end{tcolorbox}
  19131. \caption{Type checking expressions in the \LangGrad{} language.}
  19132. \label{fig:type-check-Lgradual-1}
  19133. \end{figure}
  19134. \begin{figure}[tbp]
  19135. \begin{tcolorbox}[colback=white]
  19136. \begin{lstlisting}
  19137. def check_exp(self, e, expected_ty, env):
  19138. match e:
  19139. case Lambda(params, body):
  19140. match expected_ty:
  19141. case FunctionType(params_t, return_t):
  19142. new_env = env.copy().update(zip(params, params_t))
  19143. e.has_type = expected_ty
  19144. body_ty = self.type_check_exp(body, new_env)
  19145. self.check_consistent(body_ty, return_t)
  19146. case AnyType():
  19147. new_env = env.copy().update((p, AnyType()) for p in params)
  19148. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19149. body_ty = self.type_check_exp(body, new_env)
  19150. case _:
  19151. raise Exception('lambda is not of type ' + str(expected_ty))
  19152. case _:
  19153. e_ty = self.type_check_exp(e, env)
  19154. self.check_consistent(e_ty, expected_ty, e)
  19155. \end{lstlisting}
  19156. \end{tcolorbox}
  19157. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19158. \label{fig:type-check-Lgradual-2}
  19159. \end{figure}
  19160. \begin{figure}[tbp]
  19161. \begin{tcolorbox}[colback=white]
  19162. \begin{lstlisting}
  19163. def type_check_stmt(self, s, env, return_type):
  19164. match s:
  19165. case Assign([Name(id)], value):
  19166. value_ty = self.type_check_exp(value, env)
  19167. if id in env:
  19168. self.check_consistent(env[id], value_ty, value)
  19169. else:
  19170. env[id] = value_ty
  19171. ...
  19172. case _:
  19173. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19174. def type_check_stmts(self, ss, env, return_type):
  19175. for s in ss:
  19176. self.type_check_stmt(s, env, return_type)
  19177. \end{lstlisting}
  19178. \end{tcolorbox}
  19179. \caption{Type checking statements in the \LangGrad{} language.}
  19180. \label{fig:type-check-Lgradual-3}
  19181. \end{figure}
  19182. \clearpage
  19183. \begin{figure}[tbp]
  19184. \begin{tcolorbox}[colback=white]
  19185. \begin{lstlisting}
  19186. def join_types(self, t1, t2):
  19187. match (t1, t2):
  19188. case (AnyType(), _):
  19189. return t2
  19190. case (_, AnyType()):
  19191. return t1
  19192. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19193. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19194. self.join_types(rt1,rt2))
  19195. case (TupleType(ts1), TupleType(ts2)):
  19196. return TupleType(list(map(self.join_types, ts1, ts2)))
  19197. case (_, _):
  19198. return t1
  19199. def check_consistent(self, t1, t2, e):
  19200. if not self.consistent(t1, t2):
  19201. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19202. + repr(t2) + ' in ' + repr(e))
  19203. \end{lstlisting}
  19204. \end{tcolorbox}
  19205. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19206. \label{fig:type-check-Lgradual-aux}
  19207. \end{figure}
  19208. \fi}
  19209. {\if\edition\racketEd
  19210. \begin{figure}[tbp]
  19211. \begin{tcolorbox}[colback=white]
  19212. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19213. (define/override (type-check-exp env)
  19214. (lambda (e)
  19215. (define recur (type-check-exp env))
  19216. (match e
  19217. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19218. (define-values (new-es ts)
  19219. (for/lists (exprs types) ([e es])
  19220. (recur e)))
  19221. (define t-ret (type-check-op op ts e))
  19222. (values (Prim op new-es) t-ret)]
  19223. [(Prim 'eq? (list e1 e2))
  19224. (define-values (e1^ t1) (recur e1))
  19225. (define-values (e2^ t2) (recur e2))
  19226. (check-consistent? t1 t2 e)
  19227. (define T (meet t1 t2))
  19228. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19229. [(Prim 'and (list e1 e2))
  19230. (recur (If e1 e2 (Bool #f)))]
  19231. [(Prim 'or (list e1 e2))
  19232. (define tmp (gensym 'tmp))
  19233. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19234. [(If e1 e2 e3)
  19235. (define-values (e1^ T1) (recur e1))
  19236. (define-values (e2^ T2) (recur e2))
  19237. (define-values (e3^ T3) (recur e3))
  19238. (check-consistent? T1 'Boolean e)
  19239. (check-consistent? T2 T3 e)
  19240. (define Tif (meet T2 T3))
  19241. (values (If e1^ e2^ e3^) Tif)]
  19242. [(SetBang x e1)
  19243. (define-values (e1^ T1) (recur e1))
  19244. (define varT (dict-ref env x))
  19245. (check-consistent? T1 varT e)
  19246. (values (SetBang x e1^) 'Void)]
  19247. [(WhileLoop e1 e2)
  19248. (define-values (e1^ T1) (recur e1))
  19249. (check-consistent? T1 'Boolean e)
  19250. (define-values (e2^ T2) ((type-check-exp env) e2))
  19251. (values (WhileLoop e1^ e2^) 'Void)]
  19252. [(Prim 'vector-length (list e1))
  19253. (define-values (e1^ t) (recur e1))
  19254. (match t
  19255. [`(Vector ,ts ...)
  19256. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19257. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19258. \end{lstlisting}
  19259. \end{tcolorbox}
  19260. \caption{Type checker for the \LangGrad{} language, part 1.}
  19261. \label{fig:type-check-Lgradual-1}
  19262. \end{figure}
  19263. \begin{figure}[tbp]
  19264. \begin{tcolorbox}[colback=white]
  19265. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19266. [(Prim 'vector-ref (list e1 e2))
  19267. (define-values (e1^ t1) (recur e1))
  19268. (define-values (e2^ t2) (recur e2))
  19269. (check-consistent? t2 'Integer e)
  19270. (match t1
  19271. [`(Vector ,ts ...)
  19272. (match e2^
  19273. [(Int i)
  19274. (unless (and (0 . <= . i) (i . < . (length ts)))
  19275. (error 'type-check "invalid index ~a in ~a" i e))
  19276. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19277. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19278. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19279. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19280. [(Prim 'vector-set! (list e1 e2 e3) )
  19281. (define-values (e1^ t1) (recur e1))
  19282. (define-values (e2^ t2) (recur e2))
  19283. (define-values (e3^ t3) (recur e3))
  19284. (check-consistent? t2 'Integer e)
  19285. (match t1
  19286. [`(Vector ,ts ...)
  19287. (match e2^
  19288. [(Int i)
  19289. (unless (and (0 . <= . i) (i . < . (length ts)))
  19290. (error 'type-check "invalid index ~a in ~a" i e))
  19291. (check-consistent? (list-ref ts i) t3 e)
  19292. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19293. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19294. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19295. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19296. [(Apply e1 e2s)
  19297. (define-values (e1^ T1) (recur e1))
  19298. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19299. (match T1
  19300. [`(,T1ps ... -> ,T1rt)
  19301. (for ([T2 T2s] [Tp T1ps])
  19302. (check-consistent? T2 Tp e))
  19303. (values (Apply e1^ e2s^) T1rt)]
  19304. [`Any (values (Apply e1^ e2s^) 'Any)]
  19305. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19306. [(Lambda params Tr e1)
  19307. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19308. (match p
  19309. [`[,x : ,T] (values x T)]
  19310. [(? symbol? x) (values x 'Any)])))
  19311. (define-values (e1^ T1)
  19312. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19313. (check-consistent? Tr T1 e)
  19314. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19315. `(,@Ts -> ,Tr))]
  19316. [else ((super type-check-exp env) e)]
  19317. )))
  19318. \end{lstlisting}
  19319. \end{tcolorbox}
  19320. \caption{Type checker for the \LangGrad{} language, part 2.}
  19321. \label{fig:type-check-Lgradual-2}
  19322. \end{figure}
  19323. \begin{figure}[tbp]
  19324. \begin{tcolorbox}[colback=white]
  19325. \begin{lstlisting}
  19326. (define/override (type-check-def env)
  19327. (lambda (e)
  19328. (match e
  19329. [(Def f params rt info body)
  19330. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19331. (match p
  19332. [`[,x : ,T] (values x T)]
  19333. [(? symbol? x) (values x 'Any)])))
  19334. (define new-env (append (map cons xs ps) env))
  19335. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19336. (check-consistent? ty^ rt e)
  19337. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19338. [else (error 'type-check "ill-formed function definition ~a" e)]
  19339. )))
  19340. (define/override (type-check-program e)
  19341. (match e
  19342. [(Program info body)
  19343. (define-values (body^ ty) ((type-check-exp '()) body))
  19344. (check-consistent? ty 'Integer e)
  19345. (ProgramDefsExp info '() body^)]
  19346. [(ProgramDefsExp info ds body)
  19347. (define new-env (for/list ([d ds])
  19348. (cons (Def-name d) (fun-def-type d))))
  19349. (define ds^ (for/list ([d ds])
  19350. ((type-check-def new-env) d)))
  19351. (define-values (body^ ty) ((type-check-exp new-env) body))
  19352. (check-consistent? ty 'Integer e)
  19353. (ProgramDefsExp info ds^ body^)]
  19354. [else (super type-check-program e)]))
  19355. \end{lstlisting}
  19356. \end{tcolorbox}
  19357. \caption{Type checker for the \LangGrad{} language, part 3.}
  19358. \label{fig:type-check-Lgradual-3}
  19359. \end{figure}
  19360. \begin{figure}[tbp]
  19361. \begin{tcolorbox}[colback=white]
  19362. \begin{lstlisting}
  19363. (define/public (join t1 t2)
  19364. (match* (t1 t2)
  19365. [('Integer 'Integer) 'Integer]
  19366. [('Boolean 'Boolean) 'Boolean]
  19367. [('Void 'Void) 'Void]
  19368. [('Any t2) t2]
  19369. [(t1 'Any) t1]
  19370. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19371. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19372. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19373. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19374. -> ,(join rt1 rt2))]))
  19375. (define/public (meet t1 t2)
  19376. (match* (t1 t2)
  19377. [('Integer 'Integer) 'Integer]
  19378. [('Boolean 'Boolean) 'Boolean]
  19379. [('Void 'Void) 'Void]
  19380. [('Any t2) 'Any]
  19381. [(t1 'Any) 'Any]
  19382. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19383. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19384. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19385. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19386. -> ,(meet rt1 rt2))]))
  19387. (define/public (check-consistent? t1 t2 e)
  19388. (unless (consistent? t1 t2)
  19389. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19390. (define explicit-prim-ops
  19391. (set-union
  19392. (type-predicates)
  19393. (set 'procedure-arity 'eq? 'not 'and 'or
  19394. 'vector 'vector-length 'vector-ref 'vector-set!
  19395. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19396. (define/override (fun-def-type d)
  19397. (match d
  19398. [(Def f params rt info body)
  19399. (define ps
  19400. (for/list ([p params])
  19401. (match p
  19402. [`[,x : ,T] T]
  19403. [(? symbol?) 'Any]
  19404. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19405. `(,@ps -> ,rt)]
  19406. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19407. \end{lstlisting}
  19408. \end{tcolorbox}
  19409. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19410. \label{fig:type-check-Lgradual-aux}
  19411. \end{figure}
  19412. \fi}
  19413. \section{Interpreting \LangCast{} }
  19414. \label{sec:interp-casts}
  19415. The runtime behavior of casts involving simple types such as
  19416. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19417. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19418. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19419. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19420. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19421. operator, by checking the value's tag and either retrieving
  19422. the underlying integer or signaling an error if the tag is not the
  19423. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19424. %
  19425. Things get more interesting with casts involving
  19426. \racket{function and tuple types}\python{function, tuple, and array types}.
  19427. Consider the cast of the function \code{maybe\_inc} from
  19428. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19429. to
  19430. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19431. shown in figure~\ref{fig:map-maybe_inc}.
  19432. When the \code{maybe\_inc} function flows through
  19433. this cast at runtime, we don't know whether it will return
  19434. an integer, because that depends on the input from the user.
  19435. The \LangCast{} interpreter therefore delays the checking
  19436. of the cast until the function is applied. To do so it
  19437. wraps \code{maybe\_inc} in a new function that casts its parameter
  19438. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19439. casts the return value from \CANYTY{} to \INTTY{}.
  19440. {\if\edition\pythonEd\pythonColor
  19441. %
  19442. There are further complications regarding casts on mutable data,
  19443. such as the \code{list} type introduced in
  19444. the challenge assignment of section~\ref{sec:arrays}.
  19445. %
  19446. \fi}
  19447. %
  19448. Consider the example presented in figure~\ref{fig:map-bang} that
  19449. defines a partially typed version of \code{map} whose parameter
  19450. \code{v} has type
  19451. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19452. and that updates \code{v} in place
  19453. instead of returning a new tuple. We name this function
  19454. \code{map\_inplace}. We apply \code{map\_inplace} to
  19455. \racket{a tuple}\python{an array} of integers, so the type checker
  19456. inserts a cast from
  19457. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19458. to
  19459. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19460. A naive way for the \LangCast{} interpreter to cast between
  19461. \racket{tuple}\python{array} types would be to build a new
  19462. \racket{tuple}\python{array} whose elements are the result
  19463. of casting each of the original elements to the target
  19464. type. However, this approach is not valid for mutable data structures.
  19465. In the example of figure~\ref{fig:map-bang},
  19466. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19467. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19468. the original one.
  19469. Instead the interpreter needs to create a new kind of value, a
  19470. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19471. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19472. and then applies a
  19473. cast to the resulting value. On a write, the proxy casts the argument
  19474. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19475. \racket{
  19476. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19477. \code{0} from \INTTY{} to \CANYTY{}.
  19478. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19479. from \CANYTY{} to \INTTY{}.
  19480. }
  19481. \python{
  19482. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19483. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19484. For the subscript on the left of the assignment,
  19485. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19486. }
  19487. Finally we consider casts between the \CANYTY{} type and higher-order types
  19488. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19489. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19490. have a type annotation, so it is given type \CANYTY{}. In the call to
  19491. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19492. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19493. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19494. \code{Inject}, but that doesn't work because
  19495. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19496. a flat type. Instead, we must first cast to
  19497. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19498. and then inject to \CANYTY{}.
  19499. \begin{figure}[tbp]
  19500. \begin{tcolorbox}[colback=white]
  19501. % gradual_test_11.rkt
  19502. {\if\edition\racketEd
  19503. \begin{lstlisting}
  19504. (define (map_inplace [f : (Any -> Any)]
  19505. [v : (Vector Any Any)]) : Void
  19506. (begin
  19507. (vector-set! v 0 (f (vector-ref v 0)))
  19508. (vector-set! v 1 (f (vector-ref v 1)))))
  19509. (define (inc x) (+ x 1))
  19510. (let ([v (vector 0 41)])
  19511. (begin (map_inplace inc v) (vector-ref v 1)))
  19512. \end{lstlisting}
  19513. \fi}
  19514. {\if\edition\pythonEd\pythonColor
  19515. \begin{lstlisting}
  19516. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19517. i = 0
  19518. while i != len(v):
  19519. v[i] = f(v[i])
  19520. i = i + 1
  19521. def inc(x : int) -> int:
  19522. return x + 1
  19523. v = [0, 41]
  19524. map_inplace(inc, v)
  19525. print(v[1])
  19526. \end{lstlisting}
  19527. \fi}
  19528. \end{tcolorbox}
  19529. \caption{An example involving casts on arrays.}
  19530. \label{fig:map-bang}
  19531. \end{figure}
  19532. \begin{figure}[btp]
  19533. \begin{tcolorbox}[colback=white]
  19534. {\if\edition\racketEd
  19535. \begin{lstlisting}
  19536. (define (map_inplace [f : (Any -> Any)] v) : Void
  19537. (begin
  19538. (vector-set! v 0 (f (vector-ref v 0)))
  19539. (vector-set! v 1 (f (vector-ref v 1)))))
  19540. (define (inc x) (+ x 1))
  19541. (let ([v (vector 0 41)])
  19542. (begin (map_inplace inc v) (vector-ref v 1)))
  19543. \end{lstlisting}
  19544. \fi}
  19545. {\if\edition\pythonEd\pythonColor
  19546. \begin{lstlisting}
  19547. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19548. i = 0
  19549. while i != len(v):
  19550. v[i] = f(v[i])
  19551. i = i + 1
  19552. def inc(x):
  19553. return x + 1
  19554. v = [0, 41]
  19555. map_inplace(inc, v)
  19556. print(v[1])
  19557. \end{lstlisting}
  19558. \fi}
  19559. \end{tcolorbox}
  19560. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19561. \label{fig:map-any}
  19562. \end{figure}
  19563. \begin{figure}[tbp]
  19564. \begin{tcolorbox}[colback=white]
  19565. {\if\edition\racketEd
  19566. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19567. (define/public (apply_cast v s t)
  19568. (match* (s t)
  19569. [(t1 t2) #:when (equal? t1 t2) v]
  19570. [('Any t2)
  19571. (match t2
  19572. [`(,ts ... -> ,rt)
  19573. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19574. (define v^ (apply-project v any->any))
  19575. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19576. [`(Vector ,ts ...)
  19577. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19578. (define v^ (apply-project v vec-any))
  19579. (apply_cast v^ vec-any `(Vector ,@ts))]
  19580. [else (apply-project v t2)])]
  19581. [(t1 'Any)
  19582. (match t1
  19583. [`(,ts ... -> ,rt)
  19584. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19585. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19586. (apply-inject v^ (any-tag any->any))]
  19587. [`(Vector ,ts ...)
  19588. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19589. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19590. (apply-inject v^ (any-tag vec-any))]
  19591. [else (apply-inject v (any-tag t1))])]
  19592. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19593. (define x (gensym 'x))
  19594. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19595. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19596. (define cast-writes
  19597. (for/list ([t1 ts1] [t2 ts2])
  19598. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19599. `(vector-proxy ,(vector v (apply vector cast-reads)
  19600. (apply vector cast-writes)))]
  19601. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19602. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19603. `(function ,xs ,(Cast
  19604. (Apply (Value v)
  19605. (for/list ([x xs][t1 ts1][t2 ts2])
  19606. (Cast (Var x) t2 t1)))
  19607. rt1 rt2) ())]
  19608. ))
  19609. \end{lstlisting}
  19610. \fi}
  19611. {\if\edition\pythonEd\pythonColor
  19612. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19613. def apply_cast(self, value, src, tgt):
  19614. match (src, tgt):
  19615. case (AnyType(), FunctionType(ps2, rt2)):
  19616. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19617. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19618. case (AnyType(), TupleType(ts2)):
  19619. anytup = TupleType([AnyType() for t1 in ts2])
  19620. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19621. case (AnyType(), ListType(t2)):
  19622. anylist = ListType([AnyType() for t1 in ts2])
  19623. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19624. case (AnyType(), AnyType()):
  19625. return value
  19626. case (AnyType(), _):
  19627. return self.apply_project(value, tgt)
  19628. case (FunctionType(ps1,rt1), AnyType()):
  19629. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19630. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19631. case (TupleType(ts1), AnyType()):
  19632. anytup = TupleType([AnyType() for t1 in ts1])
  19633. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19634. case (ListType(t1), AnyType()):
  19635. anylist = ListType(AnyType())
  19636. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19637. case (_, AnyType()):
  19638. return self.apply_inject(value, src)
  19639. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19640. params = [generate_name('x') for p in ps2]
  19641. args = [Cast(Name(x), t2, t1)
  19642. for (x,t1,t2) in zip(params, ps1, ps2)]
  19643. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19644. return Function('cast', params, [Return(body)], {})
  19645. case (TupleType(ts1), TupleType(ts2)):
  19646. x = generate_name('x')
  19647. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19648. for (t1,t2) in zip(ts1,ts2)]
  19649. return ProxiedTuple(value, reads)
  19650. case (ListType(t1), ListType(t2)):
  19651. x = generate_name('x')
  19652. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19653. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19654. return ProxiedList(value, read, write)
  19655. case (t1, t2) if t1 == t2:
  19656. return value
  19657. case (t1, t2):
  19658. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19659. def apply_inject(self, value, src):
  19660. return Tagged(value, self.type_to_tag(src))
  19661. def apply_project(self, value, tgt):
  19662. match value:
  19663. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19664. return val
  19665. case _:
  19666. raise Exception('apply_project, unexpected ' + repr(value))
  19667. \end{lstlisting}
  19668. \fi}
  19669. \end{tcolorbox}
  19670. \caption{The \code{apply\_cast} auxiliary method.}
  19671. \label{fig:apply_cast}
  19672. \end{figure}
  19673. The \LangCast{} interpreter uses an auxiliary function named
  19674. \code{apply\_cast} to cast a value from a source type to a target type,
  19675. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19676. the kinds of casts that we've discussed in this section.
  19677. %
  19678. The definition of the interpreter for \LangCast{} is shown in
  19679. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19680. dispatching to \code{apply\_cast}.
  19681. \racket{To handle the addition of tuple
  19682. proxies, we update the tuple primitives in \code{interp-op} using the
  19683. functions given in figure~\ref{fig:guarded-tuple}.}
  19684. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19685. \begin{figure}[tbp]
  19686. \begin{tcolorbox}[colback=white]
  19687. {\if\edition\racketEd
  19688. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19689. (define interp-Lcast-class
  19690. (class interp-Llambda-class
  19691. (super-new)
  19692. (inherit apply-fun apply-inject apply-project)
  19693. (define/override (interp-op op)
  19694. (match op
  19695. ['vector-length guarded-vector-length]
  19696. ['vector-ref guarded-vector-ref]
  19697. ['vector-set! guarded-vector-set!]
  19698. ['any-vector-ref (lambda (v i)
  19699. (match v [`(tagged ,v^ ,tg)
  19700. (guarded-vector-ref v^ i)]))]
  19701. ['any-vector-set! (lambda (v i a)
  19702. (match v [`(tagged ,v^ ,tg)
  19703. (guarded-vector-set! v^ i a)]))]
  19704. ['any-vector-length (lambda (v)
  19705. (match v [`(tagged ,v^ ,tg)
  19706. (guarded-vector-length v^)]))]
  19707. [else (super interp-op op)]
  19708. ))
  19709. (define/override ((interp-exp env) e)
  19710. (define (recur e) ((interp-exp env) e))
  19711. (match e
  19712. [(Value v) v]
  19713. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19714. [else ((super interp-exp env) e)]))
  19715. ))
  19716. (define (interp-Lcast p)
  19717. (send (new interp-Lcast-class) interp-program p))
  19718. \end{lstlisting}
  19719. \fi}
  19720. {\if\edition\pythonEd\pythonColor
  19721. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19722. class InterpLcast(InterpLany):
  19723. def interp_exp(self, e, env):
  19724. match e:
  19725. case Cast(value, src, tgt):
  19726. v = self.interp_exp(value, env)
  19727. return self.apply_cast(v, src, tgt)
  19728. case ValueExp(value):
  19729. return value
  19730. ...
  19731. case _:
  19732. return super().interp_exp(e, env)
  19733. \end{lstlisting}
  19734. \fi}
  19735. \end{tcolorbox}
  19736. \caption{The interpreter for \LangCast{}.}
  19737. \label{fig:interp-Lcast}
  19738. \end{figure}
  19739. {\if\edition\racketEd
  19740. \begin{figure}[tbp]
  19741. \begin{tcolorbox}[colback=white]
  19742. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19743. (define (guarded-vector-ref vec i)
  19744. (match vec
  19745. [`(vector-proxy ,proxy)
  19746. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19747. (define rd (vector-ref (vector-ref proxy 1) i))
  19748. (apply-fun rd (list val) 'guarded-vector-ref)]
  19749. [else (vector-ref vec i)]))
  19750. (define (guarded-vector-set! vec i arg)
  19751. (match vec
  19752. [`(vector-proxy ,proxy)
  19753. (define wr (vector-ref (vector-ref proxy 2) i))
  19754. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19755. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19756. [else (vector-set! vec i arg)]))
  19757. (define (guarded-vector-length vec)
  19758. (match vec
  19759. [`(vector-proxy ,proxy)
  19760. (guarded-vector-length (vector-ref proxy 0))]
  19761. [else (vector-length vec)]))
  19762. \end{lstlisting}
  19763. %% {\if\edition\pythonEd\pythonColor
  19764. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19765. %% UNDER CONSTRUCTION
  19766. %% \end{lstlisting}
  19767. %% \fi}
  19768. \end{tcolorbox}
  19769. \caption{The \code{guarded-vector} auxiliary functions.}
  19770. \label{fig:guarded-tuple}
  19771. \end{figure}
  19772. \fi}
  19773. {\if\edition\pythonEd\pythonColor
  19774. \section{Overload Resolution }
  19775. \label{sec:gradual-resolution}
  19776. Recall that when we added support for arrays in
  19777. section~\ref{sec:arrays}, the syntax for the array operations were the
  19778. same as for tuple operations (for example, accessing an element and
  19779. getting the length). So we performed overload resolution, with a pass
  19780. named \code{resolve}, to separate the array and tuple operations. In
  19781. particular, we introduced the primitives \code{array\_load},
  19782. \code{array\_store}, and \code{array\_len}.
  19783. For gradual typing, we further overload these operators to work on
  19784. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19785. updated with new cases for the \CANYTY{} type, translating the element
  19786. access and length operations to the primitives \code{any\_load},
  19787. \code{any\_store}, and \code{any\_len}.
  19788. \fi}
  19789. \section{Cast Insertion }
  19790. \label{sec:gradual-insert-casts}
  19791. In our discussion of type checking of \LangGrad{}, we mentioned how
  19792. the runtime aspect of type checking is carried out by the \code{Cast}
  19793. AST node, which is added to the program by a new pass named
  19794. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19795. language. We now discuss the details of this pass.
  19796. The \code{cast\_insert} pass is closely related to the type checker
  19797. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19798. In particular, the type checker allows implicit casts between
  19799. consistent types. The job of the \code{cast\_insert} pass is to make
  19800. those casts explicit. It does so by inserting
  19801. \code{Cast} nodes into the AST.
  19802. %
  19803. For the most part, the implicit casts occur in places where the type
  19804. checker checks two types for consistency. Consider the case for
  19805. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19806. checker requires that the type of the left operand is consistent with
  19807. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19808. \code{Cast} around the left operand, converting from its type to
  19809. \INTTY{}. The story is similar for the right operand. It is not always
  19810. necessary to insert a cast, for example, if the left operand already has type
  19811. \INTTY{} then there is no need for a \code{Cast}.
  19812. Some of the implicit casts are not as straightforward. One such case
  19813. arises with the
  19814. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19815. see that the type checker requires that the two branches have
  19816. consistent types and that type of the conditional expression is the
  19817. meet of the branches' types. In the target language \LangCast{}, both
  19818. branches will need to have the same type, and that type
  19819. will be the type of the conditional expression. Thus, each branch requires
  19820. a \code{Cast} to convert from its type to the meet of the branches' types.
  19821. The case for the function call exhibits another interesting situation. If
  19822. the function expression is of type \CANYTY{}, then it needs to be cast
  19823. to a function type so that it can be used in a function call in
  19824. \LangCast{}. Which function type should it be cast to? The parameter
  19825. and return types are unknown, so we can simply use \CANYTY{} for all
  19826. of them. Furthermore, in \LangCast{} the argument types will need to
  19827. exactly match the parameter types, so we must cast all the arguments
  19828. to type \CANYTY{} (if they are not already of that type).
  19829. {\if\edition\racketEd
  19830. %
  19831. Likewise, the cases for the tuple operators \code{vector-length},
  19832. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19833. where the tuple expression is of type \CANYTY{}. Instead of
  19834. handling these situations with casts, we recommend translating
  19835. the special-purpose variants of the tuple operators that handle
  19836. tuples of type \CANYTY{}: \code{any-vector-length},
  19837. \code{any-vector-ref}, and \code{any-vector-set!}.
  19838. %
  19839. \fi}
  19840. \section{Lower Casts }
  19841. \label{sec:lower_casts}
  19842. The next step in the journey toward x86 is the \code{lower\_casts}
  19843. pass that translates the casts in \LangCast{} to the lower-level
  19844. \code{Inject} and \code{Project} operators and new operators for
  19845. proxies, extending the \LangLam{} language to \LangProxy{}.
  19846. The \LangProxy{} language can also be described as an extension of
  19847. \LangAny{}, with the addition of proxies. We recommend creating an
  19848. auxiliary function named \code{lower\_cast} that takes an expression
  19849. (in \LangCast{}), a source type, and a target type and translates it
  19850. to an expression in \LangProxy{}.
  19851. The \code{lower\_cast} function can follow a code structure similar to
  19852. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19853. the interpreter for \LangCast{}, because it must handle the same cases
  19854. as \code{apply\_cast} and it needs to mimic the behavior of
  19855. \code{apply\_cast}. The most interesting cases concern
  19856. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19857. {\if\edition\racketEd
  19858. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19859. type to another tuple type is accomplished by creating a proxy that
  19860. intercepts the operations on the underlying tuple. Here we make the
  19861. creation of the proxy explicit with the \code{vector-proxy} AST
  19862. node. It takes three arguments: the first is an expression for the
  19863. tuple, the second is a tuple of functions for casting an element that is
  19864. being read from the tuple, and the third is a tuple of functions for
  19865. casting an element that is being written to the array. You can create
  19866. the functions for reading and writing using lambda expressions. Also,
  19867. as we show in the next section, we need to differentiate these tuples
  19868. of functions from the user-created ones, so we recommend using a new
  19869. AST node named \code{raw-vector} instead of \code{vector}.
  19870. %
  19871. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19872. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19873. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19874. \fi}
  19875. {\if\edition\pythonEd\pythonColor
  19876. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19877. type to another array type is accomplished by creating a proxy that
  19878. intercepts the operations on the underlying array. Here we make the
  19879. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19880. takes fives arguments: the first is an expression for the array, the
  19881. second is a function for casting an element that is being read from
  19882. the array, the third is a function for casting an element that is
  19883. being written to the array, the fourth is the type of the underlying
  19884. array, and the fifth is the type of the proxied array. You can create
  19885. the functions for reading and writing using lambda expressions.
  19886. A cast between two tuple types can be handled in a similar manner. We
  19887. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19888. immutable, so there is no need for a function to cast the value during
  19889. a write. Because there is a separate element type for each slot in
  19890. the tuple, we need more than one function for casting during a read:
  19891. we need a tuple of functions.
  19892. %
  19893. Also, as we show in the next section, we need to differentiate these
  19894. tuples from the user-created ones, so we recommend using a new AST
  19895. node named \code{RawTuple} instead of \code{Tuple} to create the
  19896. tuples of functions.
  19897. %
  19898. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19899. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19900. that involves casting an array of integers to an array of \CANYTY{}.
  19901. \fi}
  19902. \begin{figure}[tbp]
  19903. \begin{tcolorbox}[colback=white]
  19904. {\if\edition\racketEd
  19905. \begin{lstlisting}
  19906. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19907. (begin
  19908. (vector-set! v 0 (f (vector-ref v 0)))
  19909. (vector-set! v 1 (f (vector-ref v 1)))))
  19910. (define (inc [x : Any]) : Any
  19911. (inject (+ (project x Integer) 1) Integer))
  19912. (let ([v (vector 0 41)])
  19913. (begin
  19914. (map_inplace inc (vector-proxy v
  19915. (raw-vector (lambda: ([x9 : Integer]) : Any
  19916. (inject x9 Integer))
  19917. (lambda: ([x9 : Integer]) : Any
  19918. (inject x9 Integer)))
  19919. (raw-vector (lambda: ([x9 : Any]) : Integer
  19920. (project x9 Integer))
  19921. (lambda: ([x9 : Any]) : Integer
  19922. (project x9 Integer)))))
  19923. (vector-ref v 1)))
  19924. \end{lstlisting}
  19925. \fi}
  19926. {\if\edition\pythonEd\pythonColor
  19927. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19928. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19929. i = 0
  19930. while i != array_len(v):
  19931. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19932. i = (i + 1)
  19933. def inc(x : int) -> int:
  19934. return (x + 1)
  19935. def main() -> int:
  19936. v = [0, 41]
  19937. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19938. print(array_load(v, 1))
  19939. return 0
  19940. \end{lstlisting}
  19941. \fi}
  19942. \end{tcolorbox}
  19943. \caption{Output of \code{lower\_casts} on the example shown in
  19944. figure~\ref{fig:map-bang}.}
  19945. \label{fig:map-bang-lower-cast}
  19946. \end{figure}
  19947. A cast from one function type to another function type is accomplished
  19948. by generating a \code{lambda} whose parameter and return types match
  19949. the target function type. The body of the \code{lambda} should cast
  19950. the parameters from the target type to the source type. (Yes,
  19951. backward! Functions are contravariant\index{subject}{contravariant}
  19952. in the parameters.) Afterward, call the underlying function and then
  19953. cast the result from the source return type to the target return type.
  19954. Figure~\ref{fig:map-lower-cast} shows the output of the
  19955. \code{lower\_casts} pass on the \code{map} example given in
  19956. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19957. call to \code{map} is wrapped in a \code{lambda}.
  19958. \begin{figure}[tbp]
  19959. \begin{tcolorbox}[colback=white]
  19960. {\if\edition\racketEd
  19961. \begin{lstlisting}
  19962. (define (map [f : (Integer -> Integer)]
  19963. [v : (Vector Integer Integer)])
  19964. : (Vector Integer Integer)
  19965. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19966. (define (inc [x : Any]) : Any
  19967. (inject (+ (project x Integer) 1) Integer))
  19968. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19969. (project (inc (inject x9 Integer)) Integer))
  19970. (vector 0 41)) 1)
  19971. \end{lstlisting}
  19972. \fi}
  19973. {\if\edition\pythonEd\pythonColor
  19974. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19975. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19976. return (f(v[0]), f(v[1]),)
  19977. def inc(x : any) -> any:
  19978. return inject((project(x, int) + 1), int)
  19979. def main() -> int:
  19980. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19981. print(t[1])
  19982. return 0
  19983. \end{lstlisting}
  19984. \fi}
  19985. \end{tcolorbox}
  19986. \caption{Output of \code{lower\_casts} on the example shown in
  19987. figure~\ref{fig:gradual-map}.}
  19988. \label{fig:map-lower-cast}
  19989. \end{figure}
  19990. %\pagebreak
  19991. \section{Differentiate Proxies }
  19992. \label{sec:differentiate-proxies}
  19993. So far, the responsibility of differentiating tuples and tuple proxies
  19994. has been the job of the interpreter.
  19995. %
  19996. \racket{For example, the interpreter for \LangCast{} implements
  19997. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19998. figure~\ref{fig:guarded-tuple}.}
  19999. %
  20000. In the \code{differentiate\_proxies} pass we shift this responsibility
  20001. to the generated code.
  20002. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20003. we used the type \TUPLETYPENAME{} for both
  20004. real tuples and tuple proxies.
  20005. \python{Similarly, we use the type \code{list} for both arrays and
  20006. array proxies.}
  20007. In \LangPVec{} we return the
  20008. \TUPLETYPENAME{} type to its original
  20009. meaning, as the type of just tuples, and we introduce a new type,
  20010. \PTUPLETYNAME{}, whose values
  20011. can be either real tuples or tuple
  20012. proxies.
  20013. %
  20014. {\if\edition\pythonEd\pythonColor
  20015. Likewise, we return the
  20016. \ARRAYTYPENAME{} type to its original
  20017. meaning, as the type of arrays, and we introduce a new type,
  20018. \PARRAYTYNAME{}, whose values
  20019. can be either arrays or array proxies.
  20020. These new types come with a suite of new primitive operations.
  20021. \fi}
  20022. {\if\edition\racketEd
  20023. A tuple proxy is represented by a tuple containing three things: (1) the
  20024. underlying tuple, (2) a tuple of functions for casting elements that
  20025. are read from the tuple, and (3) a tuple of functions for casting
  20026. values to be written to the tuple. So, we define the following
  20027. abbreviation for the type of a tuple proxy:
  20028. \[
  20029. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20030. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20031. \]
  20032. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20033. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20034. %
  20035. Next we describe each of the new primitive operations.
  20036. \begin{description}
  20037. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20038. (\key{PVector} $T \ldots$)]\ \\
  20039. %
  20040. This operation brands a vector as a value of the \code{PVector} type.
  20041. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20042. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20043. %
  20044. This operation brands a vector proxy as value of the \code{PVector} type.
  20045. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20046. \BOOLTY{}] \ \\
  20047. %
  20048. This returns true if the value is a tuple proxy and false if it is a
  20049. real tuple.
  20050. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20051. (\key{Vector} $T \ldots$)]\ \\
  20052. %
  20053. Assuming that the input is a tuple, this operation returns the
  20054. tuple.
  20055. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20056. $\to$ \INTTY{}]\ \\
  20057. %
  20058. Given a tuple proxy, this operation returns the length of the tuple.
  20059. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20060. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20061. %
  20062. Given a tuple proxy, this operation returns the $i$th element of the
  20063. tuple.
  20064. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20065. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20066. Given a tuple proxy, this operation writes a value to the $i$th element
  20067. of the tuple.
  20068. \end{description}
  20069. \fi}
  20070. {\if\edition\pythonEd\pythonColor
  20071. %
  20072. A tuple proxy is represented by a tuple containing (1) the underlying
  20073. tuple and (2) a tuple of functions for casting elements that are read
  20074. from the tuple. The \LangPVec{} language includes the following AST
  20075. classes and primitive functions.
  20076. \begin{description}
  20077. \item[\code{InjectTuple}] \ \\
  20078. %
  20079. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20080. \item[\code{InjectTupleProxy}]\ \\
  20081. %
  20082. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20083. \item[\code{is\_tuple\_proxy}]\ \\
  20084. %
  20085. This primitive returns true if the value is a tuple proxy and false
  20086. if it is a tuple.
  20087. \item[\code{project\_tuple}]\ \\
  20088. %
  20089. Converts a tuple that is branded as \PTUPLETYNAME{}
  20090. back to a tuple.
  20091. \item[\code{proxy\_tuple\_len}]\ \\
  20092. %
  20093. Given a tuple proxy, returns the length of the underlying tuple.
  20094. \item[\code{proxy\_tuple\_load}]\ \\
  20095. %
  20096. Given a tuple proxy, returns the $i$th element of the underlying
  20097. tuple.
  20098. \end{description}
  20099. An array proxy is represented by a tuple containing (1) the underlying
  20100. array, (2) a function for casting elements that are read from the
  20101. array, and (3) a function for casting elements that are written to the
  20102. array. The \LangPVec{} language includes the following AST classes
  20103. and primitive functions.
  20104. \begin{description}
  20105. \item[\code{InjectList}]\ \\
  20106. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20107. \item[\code{InjectListProxy}]\ \\
  20108. %
  20109. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20110. \item[\code{is\_array\_proxy}]\ \\
  20111. %
  20112. Returns true if the value is an array proxy and false if it is an
  20113. array.
  20114. \item[\code{project\_array}]\ \\
  20115. %
  20116. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20117. array.
  20118. \item[\code{proxy\_array\_len}]\ \\
  20119. %
  20120. Given an array proxy, returns the length of the underlying array.
  20121. \item[\code{proxy\_array\_load}]\ \\
  20122. %
  20123. Given an array proxy, returns the $i$th element of the underlying
  20124. array.
  20125. \item[\code{proxy\_array\_store}]\ \\
  20126. %
  20127. Given an array proxy, writes a value to the $i$th element of the
  20128. underlying array.
  20129. \end{description}
  20130. \fi}
  20131. Now we discuss the translation that differentiates tuples and arrays
  20132. from proxies. First, every type annotation in the program is
  20133. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20134. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20135. places. For example, we wrap every tuple creation with an
  20136. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20137. %
  20138. {\if\edition\racketEd
  20139. \begin{minipage}{0.96\textwidth}
  20140. \begin{lstlisting}
  20141. (vector |$e_1 \ldots e_n$|)
  20142. |$\Rightarrow$|
  20143. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20144. \end{lstlisting}
  20145. \end{minipage}
  20146. \fi}
  20147. {\if\edition\pythonEd\pythonColor
  20148. \begin{lstlisting}
  20149. Tuple(|$e_1, \ldots, e_n$|)
  20150. |$\Rightarrow$|
  20151. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20152. \end{lstlisting}
  20153. \fi}
  20154. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20155. AST node that we introduced in the previous
  20156. section does not get injected.
  20157. {\if\edition\racketEd
  20158. \begin{lstlisting}
  20159. (raw-vector |$e_1 \ldots e_n$|)
  20160. |$\Rightarrow$|
  20161. (vector |$e'_1 \ldots e'_n$|)
  20162. \end{lstlisting}
  20163. \fi}
  20164. {\if\edition\pythonEd\pythonColor
  20165. \begin{lstlisting}
  20166. RawTuple(|$e_1, \ldots, e_n$|)
  20167. |$\Rightarrow$|
  20168. Tuple(|$e'_1, \ldots, e'_n$|)
  20169. \end{lstlisting}
  20170. \fi}
  20171. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20172. translates as follows:
  20173. %
  20174. {\if\edition\racketEd
  20175. \begin{lstlisting}
  20176. (vector-proxy |$e_1~e_2~e_3$|)
  20177. |$\Rightarrow$|
  20178. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20179. \end{lstlisting}
  20180. \fi}
  20181. {\if\edition\pythonEd\pythonColor
  20182. \begin{lstlisting}
  20183. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20184. |$\Rightarrow$|
  20185. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20186. \end{lstlisting}
  20187. \fi}
  20188. We translate the element access operations into conditional
  20189. expressions that check whether the value is a proxy and then dispatch
  20190. to either the appropriate proxy tuple operation or the regular tuple
  20191. operation.
  20192. {\if\edition\racketEd
  20193. \begin{lstlisting}
  20194. (vector-ref |$e_1$| |$i$|)
  20195. |$\Rightarrow$|
  20196. (let ([|$v~e_1$|])
  20197. (if (proxy? |$v$|)
  20198. (proxy-vector-ref |$v$| |$i$|)
  20199. (vector-ref (project-vector |$v$|) |$i$|)
  20200. \end{lstlisting}
  20201. \fi}
  20202. %
  20203. Note that in the branch for a tuple, we must apply
  20204. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20205. from the tuple.
  20206. The translation of array operations is similar to the ones for tuples.
  20207. \section{Reveal Casts }
  20208. \label{sec:reveal-casts-gradual}
  20209. {\if\edition\racketEd
  20210. Recall that the \code{reveal\_casts} pass
  20211. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20212. \code{Inject} and \code{Project} into lower-level operations.
  20213. %
  20214. In particular, \code{Project} turns into a conditional expression that
  20215. inspects the tag and retrieves the underlying value. Here we need to
  20216. augment the translation of \code{Project} to handle the situation in which
  20217. the target type is \code{PVector}. Instead of using
  20218. \code{vector-length} we need to use \code{proxy-vector-length}.
  20219. \begin{lstlisting}
  20220. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20221. |$\Rightarrow$|
  20222. (let |$\itm{tmp}$| |$e'$|
  20223. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20224. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20225. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20226. (exit)))
  20227. \end{lstlisting}
  20228. \fi}
  20229. %
  20230. {\if\edition\pythonEd\pythonColor
  20231. Recall that the $\itm{tagof}$ function determines the bits used to
  20232. identify values of different types, and it is used in the \code{reveal\_casts}
  20233. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20234. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20235. decimal), just like the tuple and array types.
  20236. \fi}
  20237. %
  20238. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20239. \pagebreak
  20240. \section{Closure Conversion }
  20241. \label{sec:closure-conversion-gradual}
  20242. The auxiliary function that translates type annotations needs to be
  20243. updated to handle the \PTUPLETYNAME{}
  20244. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20245. %
  20246. Otherwise, the only other changes are adding cases that copy the new
  20247. AST nodes.
  20248. \section{Select Instructions }
  20249. \label{sec:select-instructions-gradual}
  20250. \index{subject}{select instructions}
  20251. Recall that the \code{select\_instructions} pass is responsible for
  20252. lowering the primitive operations into x86 instructions. So, we need
  20253. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20254. to x86. To do so, the first question we need to answer is how to
  20255. differentiate between tuple and tuple proxies\python{, and likewise for
  20256. arrays and array proxies}. We need just one bit to accomplish this;
  20257. we use the bit in position $63$ of the 64-bit tag at the front of
  20258. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20259. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20260. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20261. it that way.
  20262. {\if\edition\racketEd
  20263. \begin{lstlisting}
  20264. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20265. |$\Rightarrow$|
  20266. movq |$e'_1$|, |$\itm{lhs'}$|
  20267. \end{lstlisting}
  20268. \fi}
  20269. {\if\edition\pythonEd\pythonColor
  20270. \begin{lstlisting}
  20271. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20272. |$\Rightarrow$|
  20273. movq |$e'_1$|, |$\itm{lhs'}$|
  20274. \end{lstlisting}
  20275. \fi}
  20276. \python{The translation for \code{InjectList} is also a move instruction.}
  20277. \noindent On the other hand,
  20278. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20279. $63$ to $1$.
  20280. %
  20281. {\if\edition\racketEd
  20282. \begin{lstlisting}
  20283. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20284. |$\Rightarrow$|
  20285. movq |$e'_1$|, %r11
  20286. movq |$(1 << 63)$|, %rax
  20287. orq 0(%r11), %rax
  20288. movq %rax, 0(%r11)
  20289. movq %r11, |$\itm{lhs'}$|
  20290. \end{lstlisting}
  20291. \fi}
  20292. {\if\edition\pythonEd\pythonColor
  20293. \begin{lstlisting}
  20294. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20295. |$\Rightarrow$|
  20296. movq |$e'_1$|, %r11
  20297. movq |$(1 << 63)$|, %rax
  20298. orq 0(%r11), %rax
  20299. movq %rax, 0(%r11)
  20300. movq %r11, |$\itm{lhs'}$|
  20301. \end{lstlisting}
  20302. \fi}
  20303. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20304. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20305. The \racket{\code{proxy?} operation consumes}%
  20306. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20307. consume}
  20308. the information so carefully stashed away by the injections. It
  20309. isolates bit $63$ to tell whether the value is a proxy.
  20310. %
  20311. {\if\edition\racketEd
  20312. \begin{lstlisting}
  20313. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20314. |$\Rightarrow$|
  20315. movq |$e_1'$|, %r11
  20316. movq 0(%r11), %rax
  20317. sarq $63, %rax
  20318. andq $1, %rax
  20319. movq %rax, |$\itm{lhs'}$|
  20320. \end{lstlisting}
  20321. \fi}%
  20322. %
  20323. {\if\edition\pythonEd\pythonColor
  20324. \begin{lstlisting}
  20325. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20326. |$\Rightarrow$|
  20327. movq |$e_1'$|, %r11
  20328. movq 0(%r11), %rax
  20329. sarq $63, %rax
  20330. andq $1, %rax
  20331. movq %rax, |$\itm{lhs'}$|
  20332. \end{lstlisting}
  20333. \fi}%
  20334. %
  20335. The \racket{\code{project-vector} operation is}
  20336. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20337. straightforward to translate, so we leave that to the reader.
  20338. Regarding the element access operations for tuples\python{ and arrays}, the
  20339. runtime provides procedures that implement them (they are recursive
  20340. functions!), so here we simply need to translate these tuple
  20341. operations into the appropriate function call. For example, here is
  20342. the translation for
  20343. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20344. {\if\edition\racketEd
  20345. \begin{minipage}{0.96\textwidth}
  20346. \begin{lstlisting}
  20347. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20348. |$\Rightarrow$|
  20349. movq |$e_1'$|, %rdi
  20350. movq |$e_2'$|, %rsi
  20351. callq proxy_vector_ref
  20352. movq %rax, |$\itm{lhs'}$|
  20353. \end{lstlisting}
  20354. \end{minipage}
  20355. \fi}
  20356. {\if\edition\pythonEd\pythonColor
  20357. \begin{lstlisting}
  20358. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20359. |$\Rightarrow$|
  20360. movq |$e_1'$|, %rdi
  20361. movq |$e_2'$|, %rsi
  20362. callq proxy_vector_ref
  20363. movq %rax, |$\itm{lhs'}$|
  20364. \end{lstlisting}
  20365. \fi}
  20366. {\if\edition\pythonEd\pythonColor
  20367. % TODO: revisit the names vecof for python -Jeremy
  20368. We translate
  20369. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20370. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20371. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20372. \fi}
  20373. We have another batch of operations to deal with: those for the
  20374. \CANYTY{} type. Recall that we generate an
  20375. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20376. there is a element access on something of type \CANYTY{}, and
  20377. similarly for
  20378. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20379. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20380. section~\ref{sec:select-Lany} we selected instructions for these
  20381. operations on the basis of the idea that the underlying value was a tuple or
  20382. array. But in the current setting, the underlying value is of type
  20383. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20384. functions to deal with this:
  20385. \code{proxy\_vector\_ref},
  20386. \code{proxy\_vector\_set}, and
  20387. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20388. to determine whether the value is a proxy, and then
  20389. dispatches to the the appropriate code.
  20390. %
  20391. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20392. can be translated as follows.
  20393. We begin by projecting the underlying value out of the tagged value and
  20394. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20395. {\if\edition\racketEd
  20396. \begin{lstlisting}
  20397. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20398. |$\Rightarrow$|
  20399. movq |$\neg 111$|, %rdi
  20400. andq |$e_1'$|, %rdi
  20401. movq |$e_2'$|, %rsi
  20402. callq proxy_vector_ref
  20403. movq %rax, |$\itm{lhs'}$|
  20404. \end{lstlisting}
  20405. \fi}
  20406. {\if\edition\pythonEd\pythonColor
  20407. \begin{lstlisting}
  20408. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20409. |$\Rightarrow$|
  20410. movq |$\neg 111$|, %rdi
  20411. andq |$e_1'$|, %rdi
  20412. movq |$e_2'$|, %rsi
  20413. callq proxy_vector_ref
  20414. movq %rax, |$\itm{lhs'}$|
  20415. \end{lstlisting}
  20416. \fi}
  20417. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20418. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20419. are translated in a similar way. Alternatively, you could generate
  20420. instructions to open-code
  20421. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20422. and \code{proxy\_vector\_length} functions.
  20423. \begin{exercise}\normalfont\normalsize
  20424. Implement a compiler for the gradually typed \LangGrad{} language by
  20425. extending and adapting your compiler for \LangLam{}. Create ten new
  20426. partially typed test programs. In addition to testing with these
  20427. new programs, test your compiler on all the tests for \LangLam{}
  20428. and for \LangDyn{}.
  20429. %
  20430. \racket{Sometimes you may get a type-checking error on the
  20431. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20432. the \CANYTY{} type around each subexpression that has caused a type
  20433. error. Although \LangDyn{} does not have explicit casts, you can
  20434. induce one by wrapping the subexpression \code{e} with a call to
  20435. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20436. %
  20437. \python{Sometimes you may get a type-checking error on the
  20438. \LangDyn{} programs, but you can adapt them by inserting a
  20439. temporary variable of type \CANYTY{} that is initialized with the
  20440. troublesome expression.}
  20441. \end{exercise}
  20442. \begin{figure}[t]
  20443. \begin{tcolorbox}[colback=white]
  20444. {\if\edition\racketEd
  20445. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20446. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20447. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20448. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20449. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20450. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20451. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20452. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20453. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20454. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20455. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20456. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20457. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20458. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20459. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20460. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20461. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20462. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20463. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20464. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20465. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20466. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20467. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20468. \path[->,bend left=15] (Lgradual) edge [above] node
  20469. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20470. \path[->,bend left=15] (Lgradual2) edge [above] node
  20471. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20472. \path[->,bend left=15] (Lgradual3) edge [above] node
  20473. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20474. \path[->,bend left=15] (Lgradual4) edge [left] node
  20475. {\ttfamily\footnotesize shrink} (Lgradualr);
  20476. \path[->,bend left=15] (Lgradualr) edge [above] node
  20477. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20478. \path[->,bend right=15] (Lgradualp) edge [above] node
  20479. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20480. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20481. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20482. \path[->,bend right=15] (Llambdapp) edge [above] node
  20483. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20484. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20485. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20486. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20487. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20488. \path[->,bend left=15] (F1-2) edge [above] node
  20489. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20490. \path[->,bend left=15] (F1-3) edge [left] node
  20491. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20492. \path[->,bend left=15] (F1-4) edge [below] node
  20493. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20494. \path[->,bend right=15] (F1-5) edge [above] node
  20495. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20496. \path[->,bend right=15] (F1-6) edge [above] node
  20497. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20498. \path[->,bend right=15] (C3-2) edge [right] node
  20499. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20500. \path[->,bend right=15] (x86-2) edge [right] node
  20501. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20502. \path[->,bend right=15] (x86-2-1) edge [below] node
  20503. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20504. \path[->,bend right=15] (x86-2-2) edge [right] node
  20505. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20506. \path[->,bend left=15] (x86-3) edge [above] node
  20507. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20508. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20509. \end{tikzpicture}
  20510. \fi}
  20511. {\if\edition\pythonEd\pythonColor
  20512. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20513. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20514. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20515. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20516. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20517. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20518. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20519. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20520. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20521. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20522. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20523. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20524. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20525. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20526. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20527. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20528. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20529. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20530. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20531. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20532. \path[->,bend left=15] (Lgradual) edge [above] node
  20533. {\ttfamily\footnotesize shrink} (Lgradual2);
  20534. \path[->,bend left=15] (Lgradual2) edge [above] node
  20535. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20536. \path[->,bend left=15] (Lgradual3) edge [above] node
  20537. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20538. \path[->,bend left=15] (Lgradual4) edge [left] node
  20539. {\ttfamily\footnotesize resolve} (Lgradualr);
  20540. \path[->,bend left=15] (Lgradualr) edge [below] node
  20541. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20542. \path[->,bend right=15] (Lgradualp) edge [above] node
  20543. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20544. \path[->,bend right=15] (Llambdapp) edge [above] node
  20545. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20546. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20547. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20548. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20549. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20550. \path[->,bend left=15] (F1-1) edge [above] node
  20551. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20552. \path[->,bend left=15] (F1-2) edge [above] node
  20553. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20554. \path[->,bend left=15] (F1-3) edge [right] node
  20555. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20556. \path[->,bend right=15] (F1-5) edge [above] node
  20557. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20558. \path[->,bend right=15] (F1-6) edge [above] node
  20559. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20560. \path[->,bend right=15] (C3-2) edge [right] node
  20561. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20562. \path[->,bend right=15] (x86-2) edge [below] node
  20563. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20564. \path[->,bend right=15] (x86-3) edge [below] node
  20565. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20566. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20567. \end{tikzpicture}
  20568. \fi}
  20569. \end{tcolorbox}
  20570. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20571. \label{fig:Lgradual-passes}
  20572. \end{figure}
  20573. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20574. needed for the compilation of \LangGrad{}.
  20575. \section{Further Reading}
  20576. This chapter just scratches the surface of gradual typing. The basic
  20577. approach described here is missing two key ingredients that one would
  20578. want in an implementation of gradual typing: blame
  20579. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20580. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20581. problem addressed by blame tracking is that when a cast on a
  20582. higher-order value fails, it often does so at a point in the program
  20583. that is far removed from the original cast. Blame tracking is a
  20584. technique for propagating extra information through casts and proxies
  20585. so that when a cast fails, the error message can point back to the
  20586. original location of the cast in the source program.
  20587. The problem addressed by space-efficient casts also relates to
  20588. higher-order casts. It turns out that in partially typed programs, a
  20589. function or tuple can flow through a great many casts at runtime. With
  20590. the approach described in this chapter, each cast adds another
  20591. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20592. considerable space, but it also makes the function calls and tuple
  20593. operations slow. For example, a partially typed version of quicksort
  20594. could, in the worst case, build a chain of proxies of length $O(n)$
  20595. around the tuple, changing the overall time complexity of the
  20596. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20597. solution to this problem by representing casts using the coercion
  20598. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20599. long chains of proxies by compressing them into a concise normal
  20600. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20601. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20602. the Grift compiler:
  20603. \begin{center}
  20604. \url{https://github.com/Gradual-Typing/Grift}
  20605. \end{center}
  20606. There are also interesting interactions between gradual typing and
  20607. other language features, such as generics, information-flow types, and
  20608. type inference, to name a few. We recommend to the reader the
  20609. online gradual typing bibliography for more material:
  20610. \begin{center}
  20611. \url{http://samth.github.io/gradual-typing-bib/}
  20612. \end{center}
  20613. % TODO: challenge problem:
  20614. % type analysis and type specialization?
  20615. % coercions?
  20616. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20617. \chapter{Generics}
  20618. \label{ch:Lpoly}
  20619. \setcounter{footnote}{0}
  20620. This chapter studies the compilation of
  20621. generics\index{subject}{generics} (aka parametric
  20622. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20623. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20624. enable programmers to make code more reusable by parameterizing
  20625. functions and data structures with respect to the types on which they
  20626. operate. For example, figure~\ref{fig:map-poly} revisits the
  20627. \code{map} example and this time gives it a more fitting type. This
  20628. \code{map} function is parameterized with respect to the element type
  20629. of the tuple. The type of \code{map} is the following generic type
  20630. specified by the \code{All} type with parameter \code{T}:
  20631. {\if\edition\racketEd
  20632. \begin{lstlisting}
  20633. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20634. \end{lstlisting}
  20635. \fi}
  20636. {\if\edition\pythonEd\pythonColor
  20637. \begin{lstlisting}
  20638. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20639. \end{lstlisting}
  20640. \fi}
  20641. %
  20642. The idea is that \code{map} can be used at \emph{all} choices of a
  20643. type for parameter \code{T}. In the example shown in
  20644. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20645. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20646. \code{T}, but we could have just as well applied \code{map} to a tuple
  20647. of Booleans.
  20648. %
  20649. A \emph{monomorphic} function is simply one that is not generic.
  20650. %
  20651. We use the term \emph{instantiation} for the process (within the
  20652. language implementation) of turning a generic function into a
  20653. monomorphic one, where the type parameters have been replaced by
  20654. types.
  20655. {\if\edition\pythonEd\pythonColor
  20656. %
  20657. In Python, when writing a generic function such as \code{map}, one
  20658. does not explicitly write its generic type (using \code{All}).
  20659. Instead, that the function is generic is implied by the use of type
  20660. variables (such as \code{T}) in the type annotations of its
  20661. parameters.
  20662. %
  20663. \fi}
  20664. \begin{figure}[tbp]
  20665. % poly_test_2.rkt
  20666. \begin{tcolorbox}[colback=white]
  20667. {\if\edition\racketEd
  20668. \begin{lstlisting}
  20669. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20670. (define (map f v)
  20671. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20672. (define (inc [x : Integer]) : Integer (+ x 1))
  20673. (vector-ref (map inc (vector 0 41)) 1)
  20674. \end{lstlisting}
  20675. \fi}
  20676. {\if\edition\pythonEd\pythonColor
  20677. \begin{lstlisting}
  20678. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20679. return (f(tup[0]), f(tup[1]))
  20680. def add1(x : int) -> int:
  20681. return x + 1
  20682. t = map(add1, (0, 41))
  20683. print(t[1])
  20684. \end{lstlisting}
  20685. \fi}
  20686. \end{tcolorbox}
  20687. \caption{A generic version of the \code{map} function.}
  20688. \label{fig:map-poly}
  20689. \end{figure}
  20690. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20691. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20692. shows the definition of the abstract syntax.
  20693. %
  20694. {\if\edition\racketEd
  20695. We add a second form for function definitions in which a type
  20696. declaration comes before the \code{define}. In the abstract syntax,
  20697. the return type in the \code{Def} is \CANYTY{}, but that should be
  20698. ignored in favor of the return type in the type declaration. (The
  20699. \CANYTY{} comes from using the same parser as discussed in
  20700. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20701. enables the use of an \code{All} type for a function, thereby making
  20702. it generic.
  20703. \fi}
  20704. %
  20705. The grammar for types is extended to include the type of a generic
  20706. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20707. abstract syntax)}.
  20708. \newcommand{\LpolyGrammarRacket}{
  20709. \begin{array}{lcl}
  20710. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20711. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20712. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20713. \end{array}
  20714. }
  20715. \newcommand{\LpolyASTRacket}{
  20716. \begin{array}{lcl}
  20717. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20718. \Def &::=& \DECL{\Var}{\Type} \\
  20719. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20720. \end{array}
  20721. }
  20722. \newcommand{\LpolyGrammarPython}{
  20723. \begin{array}{lcl}
  20724. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20725. \end{array}
  20726. }
  20727. \newcommand{\LpolyASTPython}{
  20728. \begin{array}{lcl}
  20729. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20730. \MID \key{GenericVar}\LP\Var\RP
  20731. \end{array}
  20732. }
  20733. \begin{figure}[tp]
  20734. \centering
  20735. \begin{tcolorbox}[colback=white]
  20736. \footnotesize
  20737. {\if\edition\racketEd
  20738. \[
  20739. \begin{array}{l}
  20740. \gray{\LintGrammarRacket{}} \\ \hline
  20741. \gray{\LvarGrammarRacket{}} \\ \hline
  20742. \gray{\LifGrammarRacket{}} \\ \hline
  20743. \gray{\LwhileGrammarRacket} \\ \hline
  20744. \gray{\LtupGrammarRacket} \\ \hline
  20745. \gray{\LfunGrammarRacket} \\ \hline
  20746. \gray{\LlambdaGrammarRacket} \\ \hline
  20747. \LpolyGrammarRacket \\
  20748. \begin{array}{lcl}
  20749. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20750. \end{array}
  20751. \end{array}
  20752. \]
  20753. \fi}
  20754. {\if\edition\pythonEd\pythonColor
  20755. \[
  20756. \begin{array}{l}
  20757. \gray{\LintGrammarPython{}} \\ \hline
  20758. \gray{\LvarGrammarPython{}} \\ \hline
  20759. \gray{\LifGrammarPython{}} \\ \hline
  20760. \gray{\LwhileGrammarPython} \\ \hline
  20761. \gray{\LtupGrammarPython} \\ \hline
  20762. \gray{\LfunGrammarPython} \\ \hline
  20763. \gray{\LlambdaGrammarPython} \\\hline
  20764. \LpolyGrammarPython \\
  20765. \begin{array}{lcl}
  20766. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20767. \end{array}
  20768. \end{array}
  20769. \]
  20770. \fi}
  20771. \end{tcolorbox}
  20772. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20773. (figure~\ref{fig:Llam-concrete-syntax}).}
  20774. \label{fig:Lpoly-concrete-syntax}
  20775. \end{figure}
  20776. \begin{figure}[tp]
  20777. \centering
  20778. \begin{tcolorbox}[colback=white]
  20779. \footnotesize
  20780. {\if\edition\racketEd
  20781. \[
  20782. \begin{array}{l}
  20783. \gray{\LintOpAST} \\ \hline
  20784. \gray{\LvarASTRacket{}} \\ \hline
  20785. \gray{\LifASTRacket{}} \\ \hline
  20786. \gray{\LwhileASTRacket{}} \\ \hline
  20787. \gray{\LtupASTRacket{}} \\ \hline
  20788. \gray{\LfunASTRacket} \\ \hline
  20789. \gray{\LlambdaASTRacket} \\ \hline
  20790. \LpolyASTRacket \\
  20791. \begin{array}{lcl}
  20792. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20793. \end{array}
  20794. \end{array}
  20795. \]
  20796. \fi}
  20797. {\if\edition\pythonEd\pythonColor
  20798. \[
  20799. \begin{array}{l}
  20800. \gray{\LintASTPython} \\ \hline
  20801. \gray{\LvarASTPython{}} \\ \hline
  20802. \gray{\LifASTPython{}} \\ \hline
  20803. \gray{\LwhileASTPython{}} \\ \hline
  20804. \gray{\LtupASTPython{}} \\ \hline
  20805. \gray{\LfunASTPython} \\ \hline
  20806. \gray{\LlambdaASTPython} \\ \hline
  20807. \LpolyASTPython \\
  20808. \begin{array}{lcl}
  20809. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20810. \end{array}
  20811. \end{array}
  20812. \]
  20813. \fi}
  20814. \end{tcolorbox}
  20815. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20816. (figure~\ref{fig:Llam-syntax}).}
  20817. \label{fig:Lpoly-syntax}
  20818. \end{figure}
  20819. By including the \code{All} type in the $\Type$ nonterminal of the
  20820. grammar we choose to make generics first class, which has interesting
  20821. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20822. not include syntax for the \code{All} type. It is inferred for functions whose
  20823. type annotations contain type variables.} Many languages with generics, such as
  20824. C++~\citep{stroustrup88:_param_types} and Standard
  20825. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20826. may be helpful to see an example of first-class generics in action. In
  20827. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20828. whose parameter is a generic function. Indeed, because the grammar for
  20829. $\Type$ includes the \code{All} type, a generic function may also be
  20830. returned from a function or stored inside a tuple. The body of
  20831. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20832. and also to an integer, which would not be possible if \code{f} were
  20833. not generic.
  20834. \begin{figure}[tbp]
  20835. \begin{tcolorbox}[colback=white]
  20836. {\if\edition\racketEd
  20837. \begin{lstlisting}
  20838. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20839. (define (apply_twice f)
  20840. (if (f #t) (f 42) (f 777)))
  20841. (: id (All (T) (T -> T)))
  20842. (define (id x) x)
  20843. (apply_twice id)
  20844. \end{lstlisting}
  20845. \fi}
  20846. {\if\edition\pythonEd\pythonColor
  20847. \begin{lstlisting}
  20848. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20849. if f(True):
  20850. return f(42)
  20851. else:
  20852. return f(777)
  20853. def id(x: T) -> T:
  20854. return x
  20855. print(apply_twice(id))
  20856. \end{lstlisting}
  20857. \fi}
  20858. \end{tcolorbox}
  20859. \caption{An example illustrating first-class generics.}
  20860. \label{fig:apply-twice}
  20861. \end{figure}
  20862. The type checker for \LangPoly{} shown in
  20863. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20864. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20865. {\if\edition\pythonEd\pythonColor
  20866. %
  20867. Regarding function definitions, if the type annotations on its
  20868. parameters contain generic variables, then the function is generic and
  20869. therefore its type is an \code{All} type wrapped around a function
  20870. type. Otherwise the function is monomorphic and its type is simply
  20871. a function type.
  20872. %
  20873. \fi}
  20874. The type checking of a function application is extended to handle the
  20875. case in which the operator expression is a generic function. In that case
  20876. the type arguments are deduced by matching the types of the parameters
  20877. with the types of the arguments.
  20878. %
  20879. The \code{match\_types} auxiliary function
  20880. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20881. recursively descending through a parameter type \code{param\_ty} and
  20882. the corresponding argument type \code{arg\_ty}, making sure that they
  20883. are equal except when there is a type parameter in the parameter
  20884. type. Upon encountering a type parameter for the first time, the
  20885. algorithm deduces an association of the type parameter to the
  20886. corresponding part of the argument type. If it is not the first time
  20887. that the type parameter has been encountered, the algorithm looks up
  20888. its deduced type and makes sure that it is equal to the corresponding
  20889. part of the argument type. The return type of the application is the
  20890. return type of the generic function with the type parameters
  20891. replaced by the deduced type arguments, using the
  20892. \code{substitute\_type} auxiliary function, which is also listed in
  20893. figure~\ref{fig:type-check-Lpoly-aux}.
  20894. The type checker extends type equality to handle the \code{All} type.
  20895. This is not quite as simple as for other types, such as function and
  20896. tuple types, because two \code{All} types can be syntactically
  20897. different even though they are equivalent. For example,
  20898. \begin{center}
  20899. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20900. \end{center}
  20901. is equivalent to
  20902. \begin{center}
  20903. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20904. \end{center}
  20905. Two generic types are equal if they differ only in
  20906. the choice of the names of the type parameters. The definition of type
  20907. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20908. parameters in one type to match the type parameters of the other type.
  20909. {\if\edition\racketEd
  20910. %
  20911. The type checker also ensures that only defined type variables appear
  20912. in type annotations. The \code{check\_well\_formed} function for which
  20913. the definition is shown in figure~\ref{fig:well-formed-types}
  20914. recursively inspects a type, making sure that each type variable has
  20915. been defined.
  20916. %
  20917. \fi}
  20918. \begin{figure}[tbp]
  20919. \begin{tcolorbox}[colback=white]
  20920. {\if\edition\racketEd
  20921. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20922. (define type-check-poly-class
  20923. (class type-check-Llambda-class
  20924. (super-new)
  20925. (inherit check-type-equal?)
  20926. (define/override (type-check-apply env e1 es)
  20927. (define-values (e^ ty) ((type-check-exp env) e1))
  20928. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20929. ((type-check-exp env) e)))
  20930. (match ty
  20931. [`(,ty^* ... -> ,rt)
  20932. (for ([arg-ty ty*] [param-ty ty^*])
  20933. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20934. (values e^ es^ rt)]
  20935. [`(All ,xs (,tys ... -> ,rt))
  20936. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20937. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20938. (match_types env^^ param-ty arg-ty)))
  20939. (define targs
  20940. (for/list ([x xs])
  20941. (match (dict-ref env^^ x (lambda () #f))
  20942. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20943. x (Apply e1 es))]
  20944. [ty ty])))
  20945. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20946. [else (error 'type-check "expected a function, not ~a" ty)]))
  20947. (define/override ((type-check-exp env) e)
  20948. (match e
  20949. [(Lambda `([,xs : ,Ts] ...) rT body)
  20950. (for ([T Ts]) ((check_well_formed env) T))
  20951. ((check_well_formed env) rT)
  20952. ((super type-check-exp env) e)]
  20953. [(HasType e1 ty)
  20954. ((check_well_formed env) ty)
  20955. ((super type-check-exp env) e)]
  20956. [else ((super type-check-exp env) e)]))
  20957. (define/override ((type-check-def env) d)
  20958. (verbose 'type-check "poly/def" d)
  20959. (match d
  20960. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20961. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20962. (for ([p ps]) ((check_well_formed ts-env) p))
  20963. ((check_well_formed ts-env) rt)
  20964. (define new-env (append ts-env (map cons xs ps) env))
  20965. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20966. (check-type-equal? ty^ rt body)
  20967. (Generic ts (Def f p:t* rt info body^))]
  20968. [else ((super type-check-def env) d)]))
  20969. (define/override (type-check-program p)
  20970. (match p
  20971. [(Program info body)
  20972. (type-check-program (ProgramDefsExp info '() body))]
  20973. [(ProgramDefsExp info ds body)
  20974. (define ds^ (combine-decls-defs ds))
  20975. (define new-env (for/list ([d ds^])
  20976. (cons (def-name d) (fun-def-type d))))
  20977. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20978. (define-values (body^ ty) ((type-check-exp new-env) body))
  20979. (check-type-equal? ty 'Integer body)
  20980. (ProgramDefsExp info ds^^ body^)]))
  20981. ))
  20982. \end{lstlisting}
  20983. \fi}
  20984. {\if\edition\pythonEd\pythonColor
  20985. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20986. def type_check_exp(self, e, env):
  20987. match e:
  20988. case Call(Name(f), args) if f in builtin_functions:
  20989. return super().type_check_exp(e, env)
  20990. case Call(func, args):
  20991. func_t = self.type_check_exp(func, env)
  20992. func.has_type = func_t
  20993. match func_t:
  20994. case AllType(ps, FunctionType(p_tys, rt)):
  20995. for arg in args:
  20996. arg.has_type = self.type_check_exp(arg, env)
  20997. arg_tys = [arg.has_type for arg in args]
  20998. deduced = {}
  20999. for (p, a) in zip(p_tys, arg_tys):
  21000. self.match_types(p, a, deduced, e)
  21001. return self.substitute_type(rt, deduced)
  21002. case _:
  21003. return super().type_check_exp(e, env)
  21004. case _:
  21005. return super().type_check_exp(e, env)
  21006. def type_check(self, p):
  21007. match p:
  21008. case Module(body):
  21009. env = {}
  21010. for s in body:
  21011. match s:
  21012. case FunctionDef(name, params, bod, dl, returns, comment):
  21013. params_t = [t for (x,t) in params]
  21014. ty_params = set()
  21015. for t in params_t:
  21016. ty_params |$\mid$|= self.generic_variables(t)
  21017. ty = FunctionType(params_t, returns)
  21018. if len(ty_params) > 0:
  21019. ty = AllType(list(ty_params), ty)
  21020. env[name] = ty
  21021. self.check_stmts(body, IntType(), env)
  21022. case _:
  21023. raise Exception('type_check: unexpected ' + repr(p))
  21024. \end{lstlisting}
  21025. \fi}
  21026. \end{tcolorbox}
  21027. \caption{Type checker for the \LangPoly{} language.}
  21028. \label{fig:type-check-Lpoly}
  21029. \end{figure}
  21030. \begin{figure}[tbp]
  21031. \begin{tcolorbox}[colback=white]
  21032. {\if\edition\racketEd
  21033. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21034. (define/override (type-equal? t1 t2)
  21035. (match* (t1 t2)
  21036. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21037. (define env (map cons xs ys))
  21038. (type-equal? (substitute_type env T1) T2)]
  21039. [(other wise)
  21040. (super type-equal? t1 t2)]))
  21041. (define/public (match_types env pt at)
  21042. (match* (pt at)
  21043. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21044. [('Void 'Void) env] [('Any 'Any) env]
  21045. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21046. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21047. (match_types env^ pt1 at1))]
  21048. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21049. (define env^ (match_types env prt art))
  21050. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21051. (match_types env^^ pt1 at1))]
  21052. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21053. (define env^ (append (map cons pxs axs) env))
  21054. (match_types env^ pt1 at1)]
  21055. [((? symbol? x) at)
  21056. (match (dict-ref env x (lambda () #f))
  21057. [#f (error 'type-check "undefined type variable ~a" x)]
  21058. ['Type (cons (cons x at) env)]
  21059. [t^ (check-type-equal? at t^ 'matching) env])]
  21060. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21061. (define/public (substitute_type env pt)
  21062. (match pt
  21063. ['Integer 'Integer] ['Boolean 'Boolean]
  21064. ['Void 'Void] ['Any 'Any]
  21065. [`(Vector ,ts ...)
  21066. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21067. [`(,ts ... -> ,rt)
  21068. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21069. [`(All ,xs ,t)
  21070. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21071. [(? symbol? x) (dict-ref env x)]
  21072. [else (error 'type-check "expected a type not ~a" pt)]))
  21073. (define/public (combine-decls-defs ds)
  21074. (match ds
  21075. ['() '()]
  21076. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21077. (unless (equal? name f)
  21078. (error 'type-check "name mismatch, ~a != ~a" name f))
  21079. (match type
  21080. [`(All ,xs (,ps ... -> ,rt))
  21081. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21082. (cons (Generic xs (Def name params^ rt info body))
  21083. (combine-decls-defs ds^))]
  21084. [`(,ps ... -> ,rt)
  21085. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21086. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21087. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21088. [`(,(Def f params rt info body) . ,ds^)
  21089. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21090. \end{lstlisting}
  21091. \fi}
  21092. {\if\edition\pythonEd\pythonColor
  21093. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21094. def match_types(self, param_ty, arg_ty, deduced, e):
  21095. match (param_ty, arg_ty):
  21096. case (GenericVar(id), _):
  21097. if id in deduced:
  21098. self.check_type_equal(arg_ty, deduced[id], e)
  21099. else:
  21100. deduced[id] = arg_ty
  21101. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21102. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21103. new_arg_ty = self.substitute_type(arg_ty, rename)
  21104. self.match_types(ty, new_arg_ty, deduced, e)
  21105. case (TupleType(ps), TupleType(ts)):
  21106. for (p, a) in zip(ps, ts):
  21107. self.match_types(p, a, deduced, e)
  21108. case (ListType(p), ListType(a)):
  21109. self.match_types(p, a, deduced, e)
  21110. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21111. for (pp, ap) in zip(pps, aps):
  21112. self.match_types(pp, ap, deduced, e)
  21113. self.match_types(prt, art, deduced, e)
  21114. case (IntType(), IntType()):
  21115. pass
  21116. case (BoolType(), BoolType()):
  21117. pass
  21118. case _:
  21119. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21120. def substitute_type(self, ty, var_map):
  21121. match ty:
  21122. case GenericVar(id):
  21123. return var_map[id]
  21124. case AllType(ps, ty):
  21125. new_map = copy.deepcopy(var_map)
  21126. for p in ps:
  21127. new_map[p] = GenericVar(p)
  21128. return AllType(ps, self.substitute_type(ty, new_map))
  21129. case TupleType(ts):
  21130. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21131. case ListType(ty):
  21132. return ListType(self.substitute_type(ty, var_map))
  21133. case FunctionType(pts, rt):
  21134. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21135. self.substitute_type(rt, var_map))
  21136. case IntType():
  21137. return IntType()
  21138. case BoolType():
  21139. return BoolType()
  21140. case _:
  21141. raise Exception('substitute_type: unexpected ' + repr(ty))
  21142. def check_type_equal(self, t1, t2, e):
  21143. match (t1, t2):
  21144. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21145. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21146. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21147. case (_, _):
  21148. return super().check_type_equal(t1, t2, e)
  21149. \end{lstlisting}
  21150. \fi}
  21151. \end{tcolorbox}
  21152. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21153. \label{fig:type-check-Lpoly-aux}
  21154. \end{figure}
  21155. {\if\edition\racketEd
  21156. \begin{figure}[tbp]
  21157. \begin{tcolorbox}[colback=white]
  21158. \begin{lstlisting}
  21159. (define/public ((check_well_formed env) ty)
  21160. (match ty
  21161. ['Integer (void)]
  21162. ['Boolean (void)]
  21163. ['Void (void)]
  21164. [(? symbol? a)
  21165. (match (dict-ref env a (lambda () #f))
  21166. ['Type (void)]
  21167. [else (error 'type-check "undefined type variable ~a" a)])]
  21168. [`(Vector ,ts ...)
  21169. (for ([t ts]) ((check_well_formed env) t))]
  21170. [`(,ts ... -> ,t)
  21171. (for ([t ts]) ((check_well_formed env) t))
  21172. ((check_well_formed env) t)]
  21173. [`(All ,xs ,t)
  21174. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21175. ((check_well_formed env^) t)]
  21176. [else (error 'type-check "unrecognized type ~a" ty)]))
  21177. \end{lstlisting}
  21178. \end{tcolorbox}
  21179. \caption{Well-formed types.}
  21180. \label{fig:well-formed-types}
  21181. \end{figure}
  21182. \fi}
  21183. % TODO: interpreter for R'_10
  21184. \clearpage
  21185. \section{Compiling Generics}
  21186. \label{sec:compiling-poly}
  21187. Broadly speaking, there are four approaches to compiling generics, as
  21188. follows:
  21189. \begin{description}
  21190. \item[Monomorphization] generates a different version of a generic
  21191. function for each set of type arguments with which it is used,
  21192. producing type-specialized code. This approach results in the most
  21193. efficient code but requires whole-program compilation (no separate
  21194. compilation) and may increase code size. Unfortunately,
  21195. monomorphization is incompatible with first-class generics because
  21196. it is not always possible to determine which generic functions are
  21197. used with which type arguments during compilation. (It can be done
  21198. at runtime with just-in-time compilation.) Monomorphization is
  21199. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21200. generic functions in NESL~\citep{Blelloch:1993aa} and
  21201. ML~\citep{Weeks:2006aa}.
  21202. \item[Uniform representation] generates one version of each generic
  21203. function and requires all values to have a common \emph{boxed} format,
  21204. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21205. generic and monomorphic code is compiled similarly to code in a
  21206. dynamically typed language (like \LangDyn{}), in which primitive
  21207. operators require their arguments to be projected from \CANYTY{} and
  21208. their results to be injected into \CANYTY{}. (In object-oriented
  21209. languages, the projection is accomplished via virtual method
  21210. dispatch.) The uniform representation approach is compatible with
  21211. separate compilation and with first-class generics. However, it
  21212. produces the least efficient code because it introduces overhead in
  21213. the entire program. This approach is used in
  21214. Java~\citep{Bracha:1998fk},
  21215. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21216. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21217. \item[Mixed representation] generates one version of each generic
  21218. function, using a boxed representation for type variables. However,
  21219. monomorphic code is compiled as usual (as in \LangLam{}), and
  21220. conversions are performed at the boundaries between monomorphic code
  21221. and polymorphic code (for example, when a generic function is instantiated
  21222. and called). This approach is compatible with separate compilation
  21223. and first-class generics and maintains efficiency in monomorphic
  21224. code. The trade-off is increased overhead at the boundary between
  21225. monomorphic and generic code. This approach is used in
  21226. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21227. Java 5 with the addition of autoboxing.
  21228. \item[Type passing] uses the unboxed representation in both
  21229. monomorphic and generic code. Each generic function is compiled to a
  21230. single function with extra parameters that describe the type
  21231. arguments. The type information is used by the generated code to
  21232. determine how to access the unboxed values at runtime. This approach is
  21233. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21234. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21235. compilation and first-class generics and maintains the
  21236. efficiency for monomorphic code. There is runtime overhead in
  21237. polymorphic code from dispatching on type information.
  21238. \end{description}
  21239. In this chapter we use the mixed representation approach, partly
  21240. because of its favorable attributes and partly because it is
  21241. straightforward to implement using the tools that we have already
  21242. built to support gradual typing. The work of compiling generic
  21243. functions is performed in two passes, \code{resolve} and
  21244. \code{erase\_types}, that we discuss next. The output of
  21245. \code{erase\_types} is \LangCast{}
  21246. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21247. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21248. \section{Resolve Instantiation}
  21249. \label{sec:generic-resolve}
  21250. Recall that the type checker for \LangPoly{} deduces the type
  21251. arguments at call sites to a generic function. The purpose of the
  21252. \code{resolve} pass is to turn this implicit instantiation into an
  21253. explicit one, by adding \code{inst} nodes to the syntax of the
  21254. intermediate language. An \code{inst} node records the mapping of
  21255. type parameters to type arguments. The semantics of the \code{inst}
  21256. node is to instantiate the result of its first argument, a generic
  21257. function, to produce a monomorphic function. However, because the
  21258. interpreter never analyzes type annotations, instantiation can be a
  21259. no-op and simply return the generic function.
  21260. %
  21261. The output language of the \code{resolve} pass is \LangInst{},
  21262. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21263. {\if\edition\racketEd
  21264. The \code{resolve} pass combines the type declaration and polymorphic
  21265. function into a single definition, using the \code{Poly} form, to make
  21266. polymorphic functions more convenient to process in the next pass of the
  21267. compiler.
  21268. \fi}
  21269. \newcommand{\LinstASTRacket}{
  21270. \begin{array}{lcl}
  21271. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21272. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21273. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21274. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21275. \end{array}
  21276. }
  21277. \newcommand{\LinstASTPython}{
  21278. \begin{array}{lcl}
  21279. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21280. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21281. \end{array}
  21282. }
  21283. \begin{figure}[tp]
  21284. \centering
  21285. \begin{tcolorbox}[colback=white]
  21286. \small
  21287. {\if\edition\racketEd
  21288. \[
  21289. \begin{array}{l}
  21290. \gray{\LintOpAST} \\ \hline
  21291. \gray{\LvarASTRacket{}} \\ \hline
  21292. \gray{\LifASTRacket{}} \\ \hline
  21293. \gray{\LwhileASTRacket{}} \\ \hline
  21294. \gray{\LtupASTRacket{}} \\ \hline
  21295. \gray{\LfunASTRacket} \\ \hline
  21296. \gray{\LlambdaASTRacket} \\ \hline
  21297. \LinstASTRacket \\
  21298. \begin{array}{lcl}
  21299. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21300. \end{array}
  21301. \end{array}
  21302. \]
  21303. \fi}
  21304. {\if\edition\pythonEd\pythonColor
  21305. \[
  21306. \begin{array}{l}
  21307. \gray{\LintASTPython} \\ \hline
  21308. \gray{\LvarASTPython{}} \\ \hline
  21309. \gray{\LifASTPython{}} \\ \hline
  21310. \gray{\LwhileASTPython{}} \\ \hline
  21311. \gray{\LtupASTPython{}} \\ \hline
  21312. \gray{\LfunASTPython} \\ \hline
  21313. \gray{\LlambdaASTPython} \\ \hline
  21314. \LinstASTPython \\
  21315. \begin{array}{lcl}
  21316. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21317. \end{array}
  21318. \end{array}
  21319. \]
  21320. \fi}
  21321. \end{tcolorbox}
  21322. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21323. (figure~\ref{fig:Llam-syntax}).}
  21324. \label{fig:Lpoly-prime-syntax}
  21325. \end{figure}
  21326. The output of the \code{resolve} pass on the generic \code{map}
  21327. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21328. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21329. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21330. \begin{figure}[tbp]
  21331. % poly_test_2.rkt
  21332. \begin{tcolorbox}[colback=white]
  21333. {\if\edition\racketEd
  21334. \begin{lstlisting}
  21335. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21336. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21337. (define (inc [x : Integer]) : Integer (+ x 1))
  21338. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21339. (Integer))
  21340. inc (vector 0 41)) 1)
  21341. \end{lstlisting}
  21342. \fi}
  21343. {\if\edition\pythonEd\pythonColor
  21344. \begin{lstlisting}
  21345. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21346. return (f(tup[0]), f(tup[1]))
  21347. def add1(x : int) -> int:
  21348. return x + 1
  21349. t = inst(map, {T: int})(add1, (0, 41))
  21350. print(t[1])
  21351. \end{lstlisting}
  21352. \fi}
  21353. \end{tcolorbox}
  21354. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21355. \label{fig:map-resolve}
  21356. \end{figure}
  21357. \section{Erase Generic Types}
  21358. \label{sec:erase_types}
  21359. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21360. represent type variables. For example, figure~\ref{fig:map-erase}
  21361. shows the output of the \code{erase\_types} pass on the generic
  21362. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21363. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21364. \code{All} types are removed from the type of \code{map}.
  21365. \begin{figure}[tbp]
  21366. \begin{tcolorbox}[colback=white]
  21367. {\if\edition\racketEd
  21368. \begin{lstlisting}
  21369. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21370. : (Vector Any Any)
  21371. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21372. (define (inc [x : Integer]) : Integer (+ x 1))
  21373. (vector-ref ((cast map
  21374. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21375. ((Integer -> Integer) (Vector Integer Integer)
  21376. -> (Vector Integer Integer)))
  21377. inc (vector 0 41)) 1)
  21378. \end{lstlisting}
  21379. \fi}
  21380. {\if\edition\pythonEd\pythonColor
  21381. \begin{lstlisting}
  21382. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21383. return (f(tup[0]), f(tup[1]))
  21384. def add1(x : int) -> int:
  21385. return (x + 1)
  21386. def main() -> int:
  21387. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21388. print(t[1])
  21389. return 0
  21390. \end{lstlisting}
  21391. {\small
  21392. where\\
  21393. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21394. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21395. }
  21396. \fi}
  21397. \end{tcolorbox}
  21398. \caption{The generic \code{map} example after type erasure.}
  21399. \label{fig:map-erase}
  21400. \end{figure}
  21401. This process of type erasure creates a challenge at points of
  21402. instantiation. For example, consider the instantiation of
  21403. \code{map} shown in figure~\ref{fig:map-resolve}.
  21404. The type of \code{map} is
  21405. %
  21406. {\if\edition\racketEd
  21407. \begin{lstlisting}
  21408. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21409. \end{lstlisting}
  21410. \fi}
  21411. {\if\edition\pythonEd\pythonColor
  21412. \begin{lstlisting}
  21413. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21414. \end{lstlisting}
  21415. \fi}
  21416. %
  21417. \noindent and it is instantiated to
  21418. %
  21419. {\if\edition\racketEd
  21420. \begin{lstlisting}
  21421. ((Integer -> Integer) (Vector Integer Integer)
  21422. -> (Vector Integer Integer))
  21423. \end{lstlisting}
  21424. \fi}
  21425. {\if\edition\pythonEd\pythonColor
  21426. \begin{lstlisting}
  21427. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21428. \end{lstlisting}
  21429. \fi}
  21430. %
  21431. \noindent After erasure, the type of \code{map} is
  21432. %
  21433. {\if\edition\racketEd
  21434. \begin{lstlisting}
  21435. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21436. \end{lstlisting}
  21437. \fi}
  21438. {\if\edition\pythonEd\pythonColor
  21439. \begin{lstlisting}
  21440. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21441. \end{lstlisting}
  21442. \fi}
  21443. %
  21444. \noindent but we need to convert it to the instantiated type. This is
  21445. easy to do in the language \LangCast{} with a single \code{cast}. In
  21446. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21447. \code{map} has been compiled to a \code{cast} from the type of
  21448. \code{map} to the instantiated type. The source and the target type of
  21449. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21450. is the case because both the source and target are obtained from the
  21451. same generic type of \code{map}, replacing the type parameters with
  21452. \CANYTY{} in the former and with the deduced type arguments in the
  21453. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21454. To implement the \code{erase\_types} pass, we first recommend defining
  21455. a recursive function that translates types, named
  21456. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21457. follows.
  21458. %
  21459. {\if\edition\racketEd
  21460. \begin{lstlisting}
  21461. |$T$|
  21462. |$\Rightarrow$|
  21463. Any
  21464. \end{lstlisting}
  21465. \fi}
  21466. {\if\edition\pythonEd\pythonColor
  21467. \begin{lstlisting}
  21468. GenericVar(|$T$|)
  21469. |$\Rightarrow$|
  21470. Any
  21471. \end{lstlisting}
  21472. \fi}
  21473. %
  21474. \noindent The \code{erase\_type} function also removes the generic
  21475. \code{All} types.
  21476. %
  21477. {\if\edition\racketEd
  21478. \begin{lstlisting}
  21479. (All |$xs$| |$T_1$|)
  21480. |$\Rightarrow$|
  21481. |$T'_1$|
  21482. \end{lstlisting}
  21483. \fi}
  21484. {\if\edition\pythonEd\pythonColor
  21485. \begin{lstlisting}
  21486. AllType(|$xs$|, |$T_1$|)
  21487. |$\Rightarrow$|
  21488. |$T'_1$|
  21489. \end{lstlisting}
  21490. \fi}
  21491. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21492. $T_1$.
  21493. %
  21494. In this compiler pass, apply the \code{erase\_type} function to all
  21495. the type annotations in the program.
  21496. Regarding the translation of expressions, the case for \code{Inst} is
  21497. the interesting one. We translate it into a \code{Cast}, as shown
  21498. next.
  21499. The type of the subexpression $e$ is a generic type of the form
  21500. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21501. The source type of the cast is the erasure of $T$, the type $T_s$.
  21502. %
  21503. {\if\edition\racketEd
  21504. %
  21505. The target type $T_t$ is the result of substituting the argument types
  21506. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21507. erasure.
  21508. %
  21509. \begin{lstlisting}
  21510. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21511. |$\Rightarrow$|
  21512. (Cast |$e'$| |$T_s$| |$T_t$|)
  21513. \end{lstlisting}
  21514. %
  21515. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21516. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21517. \fi}
  21518. {\if\edition\pythonEd\pythonColor
  21519. %
  21520. The target type $T_t$ is the result of substituting the deduced
  21521. argument types $d$ in $T$ and then performing type erasure.
  21522. %
  21523. \begin{lstlisting}
  21524. Inst(|$e$|, |$d$|)
  21525. |$\Rightarrow$|
  21526. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21527. \end{lstlisting}
  21528. %
  21529. where
  21530. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21531. \fi}
  21532. Finally, each generic function is translated to a regular
  21533. function in which type erasure has been applied to all the type
  21534. annotations and the body.
  21535. %% \begin{lstlisting}
  21536. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21537. %% |$\Rightarrow$|
  21538. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21539. %% \end{lstlisting}
  21540. \begin{exercise}\normalfont\normalsize
  21541. Implement a compiler for the polymorphic language \LangPoly{} by
  21542. extending and adapting your compiler for \LangGrad{}. Create six new
  21543. test programs that use polymorphic functions. Some of them should
  21544. make use of first-class generics.
  21545. \end{exercise}
  21546. \begin{figure}[tbp]
  21547. \begin{tcolorbox}[colback=white]
  21548. {\if\edition\racketEd
  21549. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21550. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21551. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21552. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21553. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21554. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21555. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21556. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21557. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21558. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21559. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21560. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21561. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21562. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21563. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21564. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21565. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21566. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21567. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21568. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21569. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21570. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21571. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21572. \path[->,bend left=15] (Lpoly) edge [above] node
  21573. {\ttfamily\footnotesize resolve} (Lpolyp);
  21574. \path[->,bend left=15] (Lpolyp) edge [above] node
  21575. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21576. \path[->,bend left=15] (Lgradualp) edge [above] node
  21577. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21578. \path[->,bend left=15] (Llambdapp) edge [left] node
  21579. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21580. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21581. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21582. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21583. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21584. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21585. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21586. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21587. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21588. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21589. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21590. \path[->,bend left=15] (F1-1) edge [above] node
  21591. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21592. \path[->,bend left=15] (F1-2) edge [above] node
  21593. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21594. \path[->,bend left=15] (F1-3) edge [left] node
  21595. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21596. \path[->,bend left=15] (F1-4) edge [below] node
  21597. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21598. \path[->,bend right=15] (F1-5) edge [above] node
  21599. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21600. \path[->,bend right=15] (F1-6) edge [above] node
  21601. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21602. \path[->,bend right=15] (C3-2) edge [right] node
  21603. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21604. \path[->,bend right=15] (x86-2) edge [right] node
  21605. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21606. \path[->,bend right=15] (x86-2-1) edge [below] node
  21607. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21608. \path[->,bend right=15] (x86-2-2) edge [right] node
  21609. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21610. \path[->,bend left=15] (x86-3) edge [above] node
  21611. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21612. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21613. \end{tikzpicture}
  21614. \fi}
  21615. {\if\edition\pythonEd\pythonColor
  21616. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21617. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21618. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21619. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21620. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21621. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21622. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21623. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21624. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21625. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21626. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21627. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21628. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21629. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21630. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21631. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21632. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21633. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21634. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21635. \path[->,bend left=15] (Lgradual) edge [above] node
  21636. {\ttfamily\footnotesize shrink} (Lgradual2);
  21637. \path[->,bend left=15] (Lgradual2) edge [above] node
  21638. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21639. \path[->,bend left=15] (Lgradual3) edge [above] node
  21640. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21641. \path[->,bend left=15] (Lgradual4) edge [left] node
  21642. {\ttfamily\footnotesize resolve} (Lgradualr);
  21643. \path[->,bend left=15] (Lgradualr) edge [below] node
  21644. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21645. \path[->,bend right=15] (Llambdapp) edge [above] node
  21646. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21647. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21648. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21649. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21650. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21651. \path[->,bend right=15] (F1-1) edge [below] node
  21652. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21653. \path[->,bend right=15] (F1-2) edge [below] node
  21654. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21655. \path[->,bend left=15] (F1-3) edge [above] node
  21656. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21657. \path[->,bend left=15] (F1-5) edge [left] node
  21658. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21659. \path[->,bend left=5] (F1-6) edge [below] node
  21660. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21661. \path[->,bend right=15] (C3-2) edge [right] node
  21662. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21663. \path[->,bend right=15] (x86-2) edge [below] node
  21664. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21665. \path[->,bend right=15] (x86-3) edge [below] node
  21666. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21667. \path[->,bend left=15] (x86-4) edge [above] node
  21668. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21669. \end{tikzpicture}
  21670. \fi}
  21671. \end{tcolorbox}
  21672. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21673. \label{fig:Lpoly-passes}
  21674. \end{figure}
  21675. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21676. needed to compile \LangPoly{}.
  21677. % TODO: challenge problem: specialization of instantiations
  21678. % Further Reading
  21679. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21680. \clearpage
  21681. \appendix
  21682. \chapter{Appendix}
  21683. \setcounter{footnote}{0}
  21684. {\if\edition\racketEd
  21685. \section{Interpreters}
  21686. \label{appendix:interp}
  21687. \index{subject}{interpreter}
  21688. We provide interpreters for each of the source languages \LangInt{},
  21689. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21690. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21691. intermediate languages \LangCVar{} and \LangCIf{} are in
  21692. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21693. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21694. \key{interp.rkt} file.
  21695. \section{Utility Functions}
  21696. \label{appendix:utilities}
  21697. The utility functions described in this section are in the
  21698. \key{utilities.rkt} file of the support code.
  21699. \paragraph{\code{interp-tests}}
  21700. This function runs the compiler passes and the interpreters on each of
  21701. the specified tests to check whether each pass is correct. The
  21702. \key{interp-tests} function has the following parameters:
  21703. \begin{description}
  21704. \item[name (a string)] A name to identify the compiler.
  21705. \item[typechecker] A function of exactly one argument that either
  21706. raises an error using the \code{error} function when it encounters a
  21707. type error, or returns \code{\#f} when it encounters a type
  21708. error. If there is no type error, the type checker returns the
  21709. program.
  21710. \item[passes] A list with one entry per pass. An entry is a list
  21711. consisting of four things:
  21712. \begin{enumerate}
  21713. \item a string giving the name of the pass;
  21714. \item the function that implements the pass (a translator from AST
  21715. to AST);
  21716. \item a function that implements the interpreter (a function from
  21717. AST to result value) for the output language; and,
  21718. \item a type checker for the output language. Type checkers for
  21719. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21720. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21721. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21722. type checker entry is optional. The support code does not provide
  21723. type checkers for the x86 languages.
  21724. \end{enumerate}
  21725. \item[source-interp] An interpreter for the source language. The
  21726. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21727. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21728. \item[tests] A list of test numbers that specifies which tests to
  21729. run (explained next).
  21730. \end{description}
  21731. %
  21732. The \key{interp-tests} function assumes that the subdirectory
  21733. \key{tests} has a collection of Racket programs whose names all start
  21734. with the family name, followed by an underscore and then the test
  21735. number, and ending with the file extension \key{.rkt}. Also, for each test
  21736. program that calls \code{read} one or more times, there is a file with
  21737. the same name except that the file extension is \key{.in}, which
  21738. provides the input for the Racket program. If the test program is
  21739. expected to fail type checking, then there should be an empty file of
  21740. the same name with extension \key{.tyerr}.
  21741. \paragraph{\code{compiler-tests}}
  21742. This function runs the compiler passes to generate x86 (a \key{.s}
  21743. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21744. It runs the machine code and checks that the output is $42$. The
  21745. parameters to the \code{compiler-tests} function are similar to those
  21746. of the \code{interp-tests} function, and they consist of
  21747. \begin{itemize}
  21748. \item a compiler name (a string),
  21749. \item a type checker,
  21750. \item description of the passes,
  21751. \item name of a test-family, and
  21752. \item a list of test numbers.
  21753. \end{itemize}
  21754. \paragraph{\code{compile-file}}
  21755. This function takes a description of the compiler passes (see the
  21756. comment for \key{interp-tests}) and returns a function that, given a
  21757. program file name (a string ending in \key{.rkt}), applies all the
  21758. passes and writes the output to a file whose name is the same as the
  21759. program file name with extension \key{.rkt} replaced by \key{.s}.
  21760. \paragraph{\code{read-program}}
  21761. This function takes a file path and parses that file (it must be a
  21762. Racket program) into an abstract syntax tree.
  21763. \paragraph{\code{parse-program}}
  21764. This function takes an S-expression representation of an abstract
  21765. syntax tree and converts it into the struct-based representation.
  21766. \paragraph{\code{assert}}
  21767. This function takes two parameters, a string (\code{msg}) and Boolean
  21768. (\code{bool}), and displays the message \key{msg} if the Boolean
  21769. \key{bool} is false.
  21770. \paragraph{\code{lookup}}
  21771. % remove discussion of lookup? -Jeremy
  21772. This function takes a key and an alist and returns the first value that is
  21773. associated with the given key, if there is one. If not, an error is
  21774. triggered. The alist may contain both immutable pairs (built with
  21775. \key{cons}) and mutable pairs (built with \key{mcons}).
  21776. %The \key{map2} function ...
  21777. \fi} %\racketEd
  21778. \section{x86 Instruction Set Quick Reference}
  21779. \label{sec:x86-quick-reference}
  21780. \index{subject}{x86}
  21781. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21782. do. We write $A \to B$ to mean that the value of $A$ is written into
  21783. location $B$. Address offsets are given in bytes. The instruction
  21784. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21785. registers (such as \code{\%rax}), or memory references (such as
  21786. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21787. reference per instruction. Other operands must be immediates or
  21788. registers.
  21789. \begin{table}[tbp]
  21790. \captionabove{Quick reference for the x86 instructions used in this book.}
  21791. \label{tab:x86-instr}
  21792. \centering
  21793. \begin{tabular}{l|l}
  21794. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21795. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21796. \texttt{negq} $A$ & $- A \to A$ \\
  21797. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21798. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21799. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21800. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21801. \texttt{retq} & Pops the return address and jumps to it. \\
  21802. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21803. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21804. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21805. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21806. be an immediate). \\
  21807. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21808. matches the condition code of the instruction; otherwise go to the
  21809. next instructions. The condition codes are \key{e} for \emph{equal},
  21810. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21811. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21812. \texttt{jl} $L$ & \\
  21813. \texttt{jle} $L$ & \\
  21814. \texttt{jg} $L$ & \\
  21815. \texttt{jge} $L$ & \\
  21816. \texttt{jmp} $L$ & Jump to label $L$. \\
  21817. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21818. \texttt{movzbq} $A$, $B$ &
  21819. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21820. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21821. and the extra bytes of $B$ are set to zero.} \\
  21822. & \\
  21823. & \\
  21824. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21825. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21826. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21827. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21828. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21829. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21830. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21831. description of the condition codes. $A$ must be a single byte register
  21832. (e.g., \texttt{al} or \texttt{cl}).} \\
  21833. \texttt{setl} $A$ & \\
  21834. \texttt{setle} $A$ & \\
  21835. \texttt{setg} $A$ & \\
  21836. \texttt{setge} $A$ &
  21837. \end{tabular}
  21838. \end{table}
  21839. \backmatter
  21840. \addtocontents{toc}{\vspace{11pt}}
  21841. \cleardoublepage % needed for right page number in TOC for References
  21842. %% \nocite{*} is a way to get all the entries in the .bib file to
  21843. %% print in the bibliography:
  21844. \nocite{*}\let\bibname\refname
  21845. \addcontentsline{toc}{fmbm}{\refname}
  21846. \printbibliography
  21847. %\printindex{authors}{Author Index}
  21848. \printindex{subject}{Index}
  21849. \end{document}
  21850. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21851. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21852. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21853. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21854. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21855. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21856. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21857. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21858. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21859. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21860. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21861. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21862. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21863. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21864. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21865. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21866. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21867. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21868. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21869. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21870. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21871. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21872. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21873. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21874. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21875. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21876. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21877. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21878. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21879. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21880. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21881. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21882. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21883. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21884. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21885. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21886. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21887. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21888. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21889. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21890. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21891. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21892. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21893. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21894. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21895. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21896. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21897. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21898. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21899. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21900. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21901. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21902. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21903. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21904. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21905. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21906. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21907. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21908. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21909. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21910. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21911. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21912. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21913. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21914. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21915. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21916. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21917. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21918. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21919. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21920. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21921. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21922. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21923. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21924. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21925. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21926. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21927. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21928. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21929. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21930. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21931. % LocalWords: pseudocode underapproximation underapproximations LALR
  21932. % LocalWords: semilattices overapproximate incrementing Earley docs
  21933. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21934. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21935. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21936. % LocalWords: LC partialevaluation pythonEd TOC TrappedError