book.tex 831 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{0}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. \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: Siek, Jeremy, author. \\
  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 '- (list (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}}(3)= \{\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, behavior that is
  7259. inherited from the interpreter for \LangInt{}
  7260. (figure~\ref{fig:interp-Lint-class}).
  7261. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7262. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7263. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7264. \code{and}, \code{or}, and \code{not} behave according to propositional
  7265. logic. In addition, the \code{and} and \code{or} operations perform
  7266. \emph{short-circuit evaluation}.
  7267. %
  7268. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7269. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7270. %
  7271. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7272. evaluated if $e_1$ evaluates to \TRUE{}.
  7273. \racket{With the increase in the number of primitive operations, the
  7274. interpreter would become repetitive without some care. We refactor
  7275. the case for \code{Prim}, moving the code that differs with each
  7276. operation into the \code{interp\_op} method shown in
  7277. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7278. \code{or} operations separately because of their short-circuiting
  7279. behavior.}
  7280. \begin{figure}[tbp]
  7281. \begin{tcolorbox}[colback=white]
  7282. {\if\edition\racketEd
  7283. \begin{lstlisting}
  7284. (define interp-Lif-class
  7285. (class interp-Lvar-class
  7286. (super-new)
  7287. (define/public (interp_op op) ...)
  7288. (define/override ((interp_exp env) e)
  7289. (define recur (interp_exp env))
  7290. (match e
  7291. [(Bool b) b]
  7292. [(If cnd thn els)
  7293. (match (recur cnd)
  7294. [#t (recur thn)]
  7295. [#f (recur els)])]
  7296. [(Prim 'and (list e1 e2))
  7297. (match (recur e1)
  7298. [#t (match (recur e2) [#t #t] [#f #f])]
  7299. [#f #f])]
  7300. [(Prim 'or (list e1 e2))
  7301. (define v1 (recur e1))
  7302. (match v1
  7303. [#t #t]
  7304. [#f (match (recur e2) [#t #t] [#f #f])])]
  7305. [(Prim op args)
  7306. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7307. [else ((super interp_exp env) e)]))
  7308. ))
  7309. (define (interp_Lif p)
  7310. (send (new interp-Lif-class) interp_program p))
  7311. \end{lstlisting}
  7312. \fi}
  7313. {\if\edition\pythonEd\pythonColor
  7314. \begin{lstlisting}
  7315. class InterpLif(InterpLvar):
  7316. def interp_exp(self, e, env):
  7317. match e:
  7318. case IfExp(test, body, orelse):
  7319. if self.interp_exp(test, env):
  7320. return self.interp_exp(body, env)
  7321. else:
  7322. return self.interp_exp(orelse, env)
  7323. case UnaryOp(Not(), v):
  7324. return not self.interp_exp(v, env)
  7325. case BoolOp(And(), values):
  7326. if self.interp_exp(values[0], env):
  7327. return self.interp_exp(values[1], env)
  7328. else:
  7329. return False
  7330. case BoolOp(Or(), values):
  7331. if self.interp_exp(values[0], env):
  7332. return True
  7333. else:
  7334. return self.interp_exp(values[1], env)
  7335. case Compare(left, [cmp], [right]):
  7336. l = self.interp_exp(left, env)
  7337. r = self.interp_exp(right, env)
  7338. return self.interp_cmp(cmp)(l, r)
  7339. case _:
  7340. return super().interp_exp(e, env)
  7341. def interp_stmt(self, s, env, cont):
  7342. match s:
  7343. case If(test, body, orelse):
  7344. match self.interp_exp(test, env):
  7345. case True:
  7346. return self.interp_stmts(body + cont, env)
  7347. case False:
  7348. return self.interp_stmts(orelse + cont, env)
  7349. case _:
  7350. return super().interp_stmt(s, env, cont)
  7351. ...
  7352. \end{lstlisting}
  7353. \fi}
  7354. \end{tcolorbox}
  7355. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7356. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7357. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7358. \label{fig:interp-Lif}
  7359. \end{figure}
  7360. {\if\edition\racketEd
  7361. \begin{figure}[tbp]
  7362. \begin{tcolorbox}[colback=white]
  7363. \begin{lstlisting}
  7364. (define/public (interp_op op)
  7365. (match op
  7366. ['+ fx+]
  7367. ['- fx-]
  7368. ['read read-fixnum]
  7369. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7370. ['eq? (lambda (v1 v2)
  7371. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7372. (and (boolean? v1) (boolean? v2))
  7373. (and (vector? v1) (vector? v2)))
  7374. (eq? v1 v2)]))]
  7375. ['< (lambda (v1 v2)
  7376. (cond [(and (fixnum? v1) (fixnum? v2))
  7377. (< v1 v2)]))]
  7378. ['<= (lambda (v1 v2)
  7379. (cond [(and (fixnum? v1) (fixnum? v2))
  7380. (<= v1 v2)]))]
  7381. ['> (lambda (v1 v2)
  7382. (cond [(and (fixnum? v1) (fixnum? v2))
  7383. (> v1 v2)]))]
  7384. ['>= (lambda (v1 v2)
  7385. (cond [(and (fixnum? v1) (fixnum? v2))
  7386. (>= v1 v2)]))]
  7387. [else (error 'interp_op "unknown operator")]))
  7388. \end{lstlisting}
  7389. \end{tcolorbox}
  7390. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7391. \label{fig:interp-op-Lif}
  7392. \end{figure}
  7393. \fi}
  7394. {\if\edition\pythonEd\pythonColor
  7395. \begin{figure}
  7396. \begin{tcolorbox}[colback=white]
  7397. \begin{lstlisting}
  7398. class InterpLif(InterpLvar):
  7399. ...
  7400. def interp_cmp(self, cmp):
  7401. match cmp:
  7402. case Lt():
  7403. return lambda x, y: x < y
  7404. case LtE():
  7405. return lambda x, y: x <= y
  7406. case Gt():
  7407. return lambda x, y: x > y
  7408. case GtE():
  7409. return lambda x, y: x >= y
  7410. case Eq():
  7411. return lambda x, y: x == y
  7412. case NotEq():
  7413. return lambda x, y: x != y
  7414. \end{lstlisting}
  7415. \end{tcolorbox}
  7416. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7417. \label{fig:interp-cmp-Lif}
  7418. \end{figure}
  7419. \fi}
  7420. \section{Type Checking \LangIf{} Programs}
  7421. \label{sec:type-check-Lif}
  7422. It is helpful to think about type checking\index{subject}{type
  7423. checking} in two complementary ways. A type checker predicts the
  7424. type of value that will be produced by each expression in the program.
  7425. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7426. type checker should predict that {\if\edition\racketEd
  7427. \begin{lstlisting}
  7428. (+ 10 (- (+ 12 20)))
  7429. \end{lstlisting}
  7430. \fi}
  7431. {\if\edition\pythonEd\pythonColor
  7432. \begin{lstlisting}
  7433. 10 + -(12 + 20)
  7434. \end{lstlisting}
  7435. \fi}
  7436. \noindent produces a value of type \INTTY{}, whereas
  7437. {\if\edition\racketEd
  7438. \begin{lstlisting}
  7439. (and (not #f) #t)
  7440. \end{lstlisting}
  7441. \fi}
  7442. {\if\edition\pythonEd\pythonColor
  7443. \begin{lstlisting}
  7444. (not False) and True
  7445. \end{lstlisting}
  7446. \fi}
  7447. \noindent produces a value of type \BOOLTY{}.
  7448. A second way to think about type checking is that it enforces a set of
  7449. rules about which operators can be applied to which kinds of
  7450. values. For example, our type checker for \LangIf{} signals an error
  7451. for the following expression:
  7452. %
  7453. {\if\edition\racketEd
  7454. \begin{lstlisting}
  7455. (not (+ 10 (- (+ 12 20))))
  7456. \end{lstlisting}
  7457. \fi}
  7458. {\if\edition\pythonEd\pythonColor
  7459. \begin{lstlisting}
  7460. not (10 + -(12 + 20))
  7461. \end{lstlisting}
  7462. \fi}
  7463. \noindent The subexpression
  7464. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7465. \python{\code{(10 + -(12 + 20))}}
  7466. has type \INTTY{}, but the type checker enforces the rule that the
  7467. argument of \code{not} must be an expression of type \BOOLTY{}.
  7468. We implement type checking using classes and methods because they
  7469. provide the open recursion needed to reuse code as we extend the type
  7470. checker in subsequent chapters, analogous to the use of classes and methods
  7471. for the interpreters (section~\ref{sec:extensible-interp}).
  7472. We separate the type checker for the \LangVar{} subset into its own
  7473. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7474. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7475. from the type checker for \LangVar{}. These type checkers are in the
  7476. files
  7477. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7478. and
  7479. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7480. of the support code.
  7481. %
  7482. Each type checker is a structurally recursive function over the AST.
  7483. Given an input expression \code{e}, the type checker either signals an
  7484. error or returns \racket{an expression and its type.}\python{its type.}
  7485. %
  7486. \racket{It returns an expression because there are situations in which
  7487. we want to change or update the expression.}
  7488. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7489. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7490. constant is \INTTY{}. To handle variables, the type checker uses the
  7491. environment \code{env} to map variables to types.
  7492. %
  7493. \racket{Consider the case for \key{let}. We type check the
  7494. initializing expression to obtain its type \key{T} and then
  7495. associate type \code{T} with the variable \code{x} in the
  7496. environment used to type check the body of the \key{let}. Thus,
  7497. when the type checker encounters a use of variable \code{x}, it can
  7498. find its type in the environment.}
  7499. %
  7500. \python{Consider the case for assignment. We type check the
  7501. initializing expression to obtain its type \key{t}. If the variable
  7502. \code{id} is already in the environment because there was a
  7503. prior assignment, we check that this initializer has the same type
  7504. as the prior one. If this is the first assignment to the variable,
  7505. we associate type \code{t} with the variable \code{id} in the
  7506. environment. Thus, when the type checker encounters a use of
  7507. variable \code{x}, it can find its type in the environment.}
  7508. %
  7509. \racket{Regarding primitive operators, we recursively analyze the
  7510. arguments and then invoke \code{type\_check\_op} to check whether
  7511. the argument types are allowed.}
  7512. %
  7513. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7514. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7515. \racket{Several auxiliary methods are used in the type checker. The
  7516. method \code{operator-types} defines a dictionary that maps the
  7517. operator names to their parameter and return types. The
  7518. \code{type-equal?} method determines whether two types are equal,
  7519. which for now simply dispatches to \code{equal?} (deep
  7520. equality). The \code{check-type-equal?} method triggers an error if
  7521. the two types are not equal. The \code{type-check-op} method looks
  7522. up the operator in the \code{operator-types} dictionary and then
  7523. checks whether the argument types are equal to the parameter types.
  7524. The result is the return type of the operator.}
  7525. %
  7526. \python{The auxiliary method \code{check\_type\_equal} triggers
  7527. an error if the two types are not equal.}
  7528. \begin{figure}[tbp]
  7529. \begin{tcolorbox}[colback=white]
  7530. {\if\edition\racketEd
  7531. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7532. (define type-check-Lvar-class
  7533. (class object%
  7534. (super-new)
  7535. (define/public (operator-types)
  7536. '((+ . ((Integer Integer) . Integer))
  7537. (- . ((Integer Integer) . Integer))
  7538. (read . (() . Integer))))
  7539. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7540. (define/public (check-type-equal? t1 t2 e)
  7541. (unless (type-equal? t1 t2)
  7542. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7543. (define/public (type-check-op op arg-types e)
  7544. (match (dict-ref (operator-types) op)
  7545. [`(,param-types . ,return-type)
  7546. (for ([at arg-types] [pt param-types])
  7547. (check-type-equal? at pt e))
  7548. return-type]
  7549. [else (error 'type-check-op "unrecognized ~a" op)]))
  7550. (define/public (type-check-exp env)
  7551. (lambda (e)
  7552. (match e
  7553. [(Int n) (values (Int n) 'Integer)]
  7554. [(Var x) (values (Var x) (dict-ref env x))]
  7555. [(Let x e body)
  7556. (define-values (e^ Te) ((type-check-exp env) e))
  7557. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7558. (values (Let x e^ b) Tb)]
  7559. [(Prim op es)
  7560. (define-values (new-es ts)
  7561. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7562. (values (Prim op new-es) (type-check-op op ts e))]
  7563. [else (error 'type-check-exp "couldn't match" e)])))
  7564. (define/public (type-check-program e)
  7565. (match e
  7566. [(Program info body)
  7567. (define-values (body^ Tb) ((type-check-exp '()) body))
  7568. (check-type-equal? Tb 'Integer body)
  7569. (Program info body^)]
  7570. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7571. ))
  7572. (define (type-check-Lvar p)
  7573. (send (new type-check-Lvar-class) type-check-program p))
  7574. \end{lstlisting}
  7575. \fi}
  7576. {\if\edition\pythonEd\pythonColor
  7577. \begin{lstlisting}[escapechar=`]
  7578. class TypeCheckLvar:
  7579. def check_type_equal(self, t1, t2, e):
  7580. if t1 != t2:
  7581. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7582. raise Exception(msg)
  7583. def type_check_exp(self, e, env):
  7584. match e:
  7585. case BinOp(left, (Add() | Sub()), right):
  7586. l = self.type_check_exp(left, env)
  7587. check_type_equal(l, int, left)
  7588. r = self.type_check_exp(right, env)
  7589. check_type_equal(r, int, right)
  7590. return int
  7591. case UnaryOp(USub(), v):
  7592. t = self.type_check_exp(v, env)
  7593. check_type_equal(t, int, v)
  7594. return int
  7595. case Name(id):
  7596. return env[id]
  7597. case Constant(value) if isinstance(value, int):
  7598. return int
  7599. case Call(Name('input_int'), []):
  7600. return int
  7601. def type_check_stmts(self, ss, env):
  7602. if len(ss) == 0:
  7603. return
  7604. match ss[0]:
  7605. case Assign([Name(id)], value):
  7606. t = self.type_check_exp(value, env)
  7607. if id in env:
  7608. check_type_equal(env[id], t, value)
  7609. else:
  7610. env[id] = t
  7611. return self.type_check_stmts(ss[1:], env)
  7612. case Expr(Call(Name('print'), [arg])):
  7613. t = self.type_check_exp(arg, env)
  7614. check_type_equal(t, int, arg)
  7615. return self.type_check_stmts(ss[1:], env)
  7616. case Expr(value):
  7617. self.type_check_exp(value, env)
  7618. return self.type_check_stmts(ss[1:], env)
  7619. def type_check_P(self, p):
  7620. match p:
  7621. case Module(body):
  7622. self.type_check_stmts(body, {})
  7623. \end{lstlisting}
  7624. \fi}
  7625. \end{tcolorbox}
  7626. \caption{Type checker for the \LangVar{} language.}
  7627. \label{fig:type-check-Lvar}
  7628. \end{figure}
  7629. \begin{figure}[tbp]
  7630. \begin{tcolorbox}[colback=white]
  7631. {\if\edition\racketEd
  7632. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7633. (define type-check-Lif-class
  7634. (class type-check-Lvar-class
  7635. (super-new)
  7636. (inherit check-type-equal?)
  7637. (define/override (operator-types)
  7638. (append '((and . ((Boolean Boolean) . Boolean))
  7639. (or . ((Boolean Boolean) . Boolean))
  7640. (< . ((Integer Integer) . Boolean))
  7641. (<= . ((Integer Integer) . Boolean))
  7642. (> . ((Integer Integer) . Boolean))
  7643. (>= . ((Integer Integer) . Boolean))
  7644. (not . ((Boolean) . Boolean)))
  7645. (super operator-types)))
  7646. (define/override (type-check-exp env)
  7647. (lambda (e)
  7648. (match e
  7649. [(Bool b) (values (Bool b) 'Boolean)]
  7650. [(Prim 'eq? (list e1 e2))
  7651. (define-values (e1^ T1) ((type-check-exp env) e1))
  7652. (define-values (e2^ T2) ((type-check-exp env) e2))
  7653. (check-type-equal? T1 T2 e)
  7654. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7655. [(If cnd thn els)
  7656. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7657. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7658. (define-values (els^ Te) ((type-check-exp env) els))
  7659. (check-type-equal? Tc 'Boolean e)
  7660. (check-type-equal? Tt Te e)
  7661. (values (If cnd^ thn^ els^) Te)]
  7662. [else ((super type-check-exp env) e)])))
  7663. ))
  7664. (define (type-check-Lif p)
  7665. (send (new type-check-Lif-class) type-check-program p))
  7666. \end{lstlisting}
  7667. \fi}
  7668. {\if\edition\pythonEd\pythonColor
  7669. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7670. class TypeCheckLif(TypeCheckLvar):
  7671. def type_check_exp(self, e, env):
  7672. match e:
  7673. case Constant(value) if isinstance(value, bool):
  7674. return bool
  7675. case BinOp(left, Sub(), right):
  7676. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7677. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7678. return int
  7679. case UnaryOp(Not(), v):
  7680. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7681. return bool
  7682. case BoolOp(op, values):
  7683. left = values[0] ; right = values[1]
  7684. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7685. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7686. return bool
  7687. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7688. or isinstance(cmp, NotEq):
  7689. l = self.type_check_exp(left, env)
  7690. r = self.type_check_exp(right, env)
  7691. check_type_equal(l, r, e)
  7692. return bool
  7693. case Compare(left, [cmp], [right]):
  7694. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7695. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7696. return bool
  7697. case IfExp(test, body, orelse):
  7698. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7699. b = self.type_check_exp(body, env)
  7700. o = self.type_check_exp(orelse, env)
  7701. check_type_equal(b, o, e)
  7702. return b
  7703. case _:
  7704. return super().type_check_exp(e, env)
  7705. def type_check_stmts(self, ss, env):
  7706. if len(ss) == 0:
  7707. return
  7708. match ss[0]:
  7709. case If(test, body, orelse):
  7710. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7711. b = self.type_check_stmts(body, env)
  7712. o = self.type_check_stmts(orelse, env)
  7713. check_type_equal(b, o, ss[0])
  7714. return self.type_check_stmts(ss[1:], env)
  7715. case _:
  7716. return super().type_check_stmts(ss, env)
  7717. \end{lstlisting}
  7718. \fi}
  7719. \end{tcolorbox}
  7720. \caption{Type checker for the \LangIf{} language.}
  7721. \label{fig:type-check-Lif}
  7722. \end{figure}
  7723. The definition of the type checker for \LangIf{} is shown in
  7724. figure~\ref{fig:type-check-Lif}.
  7725. %
  7726. The type of a Boolean constant is \BOOLTY{}.
  7727. %
  7728. \racket{The \code{operator-types} function adds dictionary entries for
  7729. the new operators.}
  7730. %
  7731. \python{The logical \code{not} operator requires its argument to be a
  7732. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7733. and logical \code{or} operators.}
  7734. %
  7735. The equality operator requires the two arguments to have the same type,
  7736. and therefore we handle it separately from the other operators.
  7737. %
  7738. \python{The other comparisons (less-than, etc.) require their
  7739. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7740. %
  7741. The condition of an \code{if} must
  7742. be of \BOOLTY{} type, and the two branches must have the same type.
  7743. \begin{exercise}\normalfont\normalsize
  7744. Create ten new test programs in \LangIf{}. Half the programs should
  7745. have a type error.
  7746. \racket{For those programs, create an empty file with the
  7747. same base name and with file extension \code{.tyerr}. For example, if
  7748. the test \code{cond\_test\_14.rkt}
  7749. is expected to error, then create
  7750. an empty file named \code{cond\_test\_14.tyerr}.
  7751. This indicates to \code{interp-tests} and
  7752. \code{compiler-tests} that a type error is expected.}
  7753. %
  7754. The other half of the test programs should not have type errors.
  7755. %
  7756. \racket{In the \code{run-tests.rkt} script, change the second argument
  7757. of \code{interp-tests} and \code{compiler-tests} to
  7758. \code{type-check-Lif}, which causes the type checker to run prior to
  7759. the compiler passes. Temporarily change the \code{passes} to an
  7760. empty list and run the script, thereby checking that the new test
  7761. programs either type check or do not, as intended.}
  7762. %
  7763. Run the test script to check that these test programs type check as
  7764. expected.
  7765. \end{exercise}
  7766. \clearpage
  7767. \section{The \LangCIf{} Intermediate Language}
  7768. \label{sec:Cif}
  7769. {\if\edition\racketEd
  7770. %
  7771. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7772. comparison operators to the \Exp{} nonterminal and the literals
  7773. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7774. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7775. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7776. comparison operation and the branches are \code{goto} statements,
  7777. making it straightforward to compile \code{if} statements to x86. The
  7778. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7779. expressions. A \code{goto} statement transfers control to the $\Tail$
  7780. expression corresponding to its label.
  7781. %
  7782. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7783. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7784. defines its abstract syntax.
  7785. %
  7786. \fi}
  7787. %
  7788. {\if\edition\pythonEd\pythonColor
  7789. %
  7790. The output of \key{explicate\_control} is a language similar to the
  7791. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7792. \code{goto} statements, so we name it \LangCIf{}.
  7793. %
  7794. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7795. the arguments of operators are restricted to atomic expressions. The
  7796. \LangCIf{} language does not include \code{if} expressions, but it does
  7797. include a restricted form of \code{if} statement. The condition must be
  7798. a comparison, and the two branches may contain only \code{goto}
  7799. statements. These restrictions make it easier to translate \code{if}
  7800. statements to x86. The \LangCIf{} language also adds a \code{return}
  7801. statement to finish the program with a specified value.
  7802. %
  7803. The \key{CProgram} construct contains a dictionary mapping labels to
  7804. lists of statements that end with a \emph{tail} statement, which is
  7805. either a \code{return} statement, a \code{goto}, or an
  7806. \code{if} statement.
  7807. %
  7808. A \code{goto} transfers control to the sequence of statements
  7809. associated with its label.
  7810. %
  7811. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7812. and figure~\ref{fig:c1-syntax} shows its
  7813. abstract syntax.
  7814. %
  7815. \fi}
  7816. %
  7817. \newcommand{\CifGrammarRacket}{
  7818. \begin{array}{lcl}
  7819. \Atm &::=& \itm{bool} \\
  7820. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7821. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7822. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7823. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7824. \end{array}
  7825. }
  7826. \newcommand{\CifASTRacket}{
  7827. \begin{array}{lcl}
  7828. \Atm &::=& \BOOL{\itm{bool}} \\
  7829. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7830. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7831. \Tail &::= & \GOTO{\itm{label}} \\
  7832. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7833. \end{array}
  7834. }
  7835. \newcommand{\CifGrammarPython}{
  7836. \begin{array}{lcl}
  7837. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7838. \Exp &::= & \Atm \MID \CREAD{}
  7839. \MID \CUNIOP{\key{-}}{\Atm}
  7840. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7841. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7842. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7843. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7844. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7845. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7846. \end{array}
  7847. }
  7848. \newcommand{\CifASTPython}{
  7849. \begin{array}{lcl}
  7850. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7851. \Exp &::= & \Atm \MID \READ{}
  7852. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7853. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7854. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7855. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7856. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7857. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7858. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7859. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7860. \end{array}
  7861. }
  7862. \begin{figure}[tbp]
  7863. \begin{tcolorbox}[colback=white]
  7864. \small
  7865. {\if\edition\racketEd
  7866. \[
  7867. \begin{array}{l}
  7868. \gray{\CvarGrammarRacket} \\ \hline
  7869. \CifGrammarRacket \\
  7870. \begin{array}{lcl}
  7871. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7872. \end{array}
  7873. \end{array}
  7874. \]
  7875. \fi}
  7876. {\if\edition\pythonEd\pythonColor
  7877. \[
  7878. \begin{array}{l}
  7879. \CifGrammarPython \\
  7880. \begin{array}{lcl}
  7881. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7882. \end{array}
  7883. \end{array}
  7884. \]
  7885. \fi}
  7886. \end{tcolorbox}
  7887. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7888. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7889. \label{fig:c1-concrete-syntax}
  7890. \end{figure}
  7891. \begin{figure}[tp]
  7892. \begin{tcolorbox}[colback=white]
  7893. \small
  7894. {\if\edition\racketEd
  7895. \[
  7896. \begin{array}{l}
  7897. \gray{\CvarASTRacket} \\ \hline
  7898. \CifASTRacket \\
  7899. \begin{array}{lcl}
  7900. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7901. \end{array}
  7902. \end{array}
  7903. \]
  7904. \fi}
  7905. {\if\edition\pythonEd\pythonColor
  7906. \[
  7907. \begin{array}{l}
  7908. \CifASTPython \\
  7909. \begin{array}{lcl}
  7910. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7911. \end{array}
  7912. \end{array}
  7913. \]
  7914. \fi}
  7915. \end{tcolorbox}
  7916. \racket{
  7917. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7918. }
  7919. \index{subject}{Goto@\texttt{Goto}}
  7920. \index{subject}{Return@\texttt{Return}}
  7921. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7922. (figure~\ref{fig:c0-syntax})}.}
  7923. \label{fig:c1-syntax}
  7924. \end{figure}
  7925. \section{The \LangXIf{} Language}
  7926. \label{sec:x86-if}
  7927. \index{subject}{x86}
  7928. To implement Booleans, the new logical operations, the
  7929. comparison operations, and the \key{if} expression\python{ and
  7930. statement}, we delve further into the x86
  7931. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7932. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7933. subset of x86, which includes instructions for logical operations,
  7934. comparisons, and \racket{conditional} jumps.
  7935. %
  7936. \python{The abstract syntax for an \LangXIf{} program contains a
  7937. dictionary mapping labels to sequences of instructions, each of
  7938. which we refer to as a \emph{basic block}\index{subject}{basic
  7939. block}.}
  7940. As x86 does not provide direct support for Booleans, we take the usual
  7941. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7942. \code{False} as $0$.
  7943. Furthermore, x86 does not provide an instruction that directly
  7944. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7945. However, the \code{xorq} instruction can be used to encode \code{not}.
  7946. The \key{xorq} instruction takes two arguments, performs a pairwise
  7947. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7948. and writes the results into its second argument. Recall the following
  7949. truth table for exclusive-or:
  7950. \begin{center}
  7951. \begin{tabular}{l|cc}
  7952. & 0 & 1 \\ \hline
  7953. 0 & 0 & 1 \\
  7954. 1 & 1 & 0
  7955. \end{tabular}
  7956. \end{center}
  7957. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7958. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7959. for the bit $1$, the result is the opposite of the second bit. Thus,
  7960. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7961. the first argument, as follows, where $\Arg$ is the translation of
  7962. $\Atm$ to x86:
  7963. \[
  7964. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7965. \qquad\Rightarrow\qquad
  7966. \begin{array}{l}
  7967. \key{movq}~ \Arg\key{,} \Var\\
  7968. \key{xorq}~ \key{\$1,} \Var
  7969. \end{array}
  7970. \]
  7971. \newcommand{\GrammarXIf}{
  7972. \begin{array}{lcl}
  7973. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7974. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7975. \Arg &::=& \key{\%}\itm{bytereg}\\
  7976. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7977. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7978. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7979. \MID \key{set}cc~\Arg
  7980. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7981. &\MID& \key{j}cc~\itm{label} \\
  7982. \end{array}
  7983. }
  7984. \begin{figure}[tp]
  7985. \begin{tcolorbox}[colback=white]
  7986. \[
  7987. \begin{array}{l}
  7988. \gray{\GrammarXInt} \\ \hline
  7989. \GrammarXIf \\
  7990. \begin{array}{lcl}
  7991. \LangXIfM{} &::= & \key{.globl main} \\
  7992. & & \key{main:} \; \Instr\ldots
  7993. \end{array}
  7994. \end{array}
  7995. \]
  7996. \end{tcolorbox}
  7997. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7998. \label{fig:x86-1-concrete}
  7999. \end{figure}
  8000. \newcommand{\ASTXIfRacket}{
  8001. \begin{array}{lcl}
  8002. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8003. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8004. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8005. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8006. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8007. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8008. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8009. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8010. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8011. \end{array}
  8012. }
  8013. \newcommand{\ASTXIfPython}{
  8014. \begin{array}{lcl}
  8015. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8016. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8017. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8018. \MID \BYTEREG{\itm{bytereg}} \\
  8019. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8020. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8021. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8022. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8023. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8024. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8025. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8026. \end{array}
  8027. }
  8028. \begin{figure}[tp]
  8029. \begin{tcolorbox}[colback=white]
  8030. \small
  8031. {\if\edition\racketEd
  8032. \[\arraycolsep=3pt
  8033. \begin{array}{l}
  8034. \gray{\ASTXIntRacket} \\ \hline
  8035. \ASTXIfRacket \\
  8036. \begin{array}{lcl}
  8037. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8038. \end{array}
  8039. \end{array}
  8040. \]
  8041. \fi}
  8042. %
  8043. {\if\edition\pythonEd\pythonColor
  8044. \[
  8045. \begin{array}{l}
  8046. \gray{\ASTXIntPython} \\ \hline
  8047. \ASTXIfPython \\
  8048. \begin{array}{lcl}
  8049. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8050. \end{array}
  8051. \end{array}
  8052. \]
  8053. \fi}
  8054. \end{tcolorbox}
  8055. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8056. \label{fig:x86-1}
  8057. \end{figure}
  8058. Next we consider the x86 instructions that are relevant for compiling
  8059. the comparison operations. The \key{cmpq} instruction compares its two
  8060. arguments to determine whether one argument is less than, equal to, or
  8061. greater than the other argument. The \key{cmpq} instruction is unusual
  8062. regarding the order of its arguments and where the result is
  8063. placed. The argument order is backward: if you want to test whether
  8064. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8065. \key{cmpq} is placed in the special EFLAGS register. This register
  8066. cannot be accessed directly, but it can be queried by a number of
  8067. instructions, including the \key{set} instruction. The instruction
  8068. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8069. depending on whether the contents of the EFLAGS register matches the
  8070. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8071. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8072. The \key{set} instruction has a quirk in that its destination argument
  8073. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8074. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8075. register. Thankfully, the \key{movzbq} instruction can be used to
  8076. move from a single-byte register to a normal 64-bit register. The
  8077. abstract syntax for the \code{set} instruction differs from the
  8078. concrete syntax in that it separates the instruction name from the
  8079. condition code.
  8080. \python{The x86 instructions for jumping are relevant to the
  8081. compilation of \key{if} expressions.}
  8082. %
  8083. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8084. counter to the address of the instruction after the specified
  8085. label.}
  8086. %
  8087. \racket{The x86 instruction for conditional jump is relevant to the
  8088. compilation of \key{if} expressions.}
  8089. %
  8090. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8091. counter to point to the instruction after \itm{label}, depending on
  8092. whether the result in the EFLAGS register matches the condition code
  8093. \itm{cc}; otherwise, the jump instruction falls through to the next
  8094. instruction. Like the abstract syntax for \code{set}, the abstract
  8095. syntax for conditional jump separates the instruction name from the
  8096. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8097. corresponds to \code{jle foo}. Because the conditional jump instruction
  8098. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8099. a \key{cmpq} instruction to set the EFLAGS register.
  8100. \section{Shrink the \LangIf{} Language}
  8101. \label{sec:shrink-Lif}
  8102. The \code{shrink} pass translates some of the language features into
  8103. other features, thereby reducing the kinds of expressions in the
  8104. language. For example, the short-circuiting nature of the \code{and}
  8105. and \code{or} logical operators can be expressed using \code{if} as
  8106. follows.
  8107. \begin{align*}
  8108. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8109. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8110. \end{align*}
  8111. By performing these translations in the front end of the compiler,
  8112. subsequent passes of the compiler can be shorter.
  8113. On the other hand, translations sometimes reduce the efficiency of the
  8114. generated code by increasing the number of instructions. For example,
  8115. expressing subtraction in terms of addition and negation
  8116. \[
  8117. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8118. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8119. \]
  8120. produces code with two x86 instructions (\code{negq} and \code{addq})
  8121. instead of just one (\code{subq}). Thus, we do not recommend
  8122. translating subtraction into addition and negation.
  8123. \begin{exercise}\normalfont\normalsize
  8124. %
  8125. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8126. the language by translating them to \code{if} expressions in \LangIf{}.
  8127. %
  8128. Create four test programs that involve these operators.
  8129. %
  8130. {\if\edition\racketEd
  8131. In the \code{run-tests.rkt} script, add the following entry for
  8132. \code{shrink} to the list of passes (it should be the only pass at
  8133. this point).
  8134. \begin{lstlisting}
  8135. (list "shrink" shrink interp_Lif type-check-Lif)
  8136. \end{lstlisting}
  8137. This instructs \code{interp-tests} to run the interpreter
  8138. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8139. output of \code{shrink}.
  8140. \fi}
  8141. %
  8142. Run the script to test your compiler on all the test programs.
  8143. \end{exercise}
  8144. {\if\edition\racketEd
  8145. \section{Uniquify Variables}
  8146. \label{sec:uniquify-Lif}
  8147. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8148. \code{if} expressions.
  8149. \begin{exercise}\normalfont\normalsize
  8150. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8151. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8152. \begin{lstlisting}
  8153. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8154. \end{lstlisting}
  8155. Run the script to test your compiler.
  8156. \end{exercise}
  8157. \fi}
  8158. \section{Remove Complex Operands}
  8159. \label{sec:remove-complex-opera-Lif}
  8160. The output language of \code{remove\_complex\_operands} is
  8161. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8162. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8163. but the \code{if} expression is not. All three subexpressions of an
  8164. \code{if} are allowed to be complex expressions, but the operands of
  8165. the \code{not} operator and comparison operators must be atomic.
  8166. %
  8167. \python{We add a new language form, the \code{Begin} expression, to aid
  8168. in the translation of \code{if} expressions. When we recursively
  8169. process the two branches of the \code{if}, we generate temporary
  8170. variables and their initializing expressions. However, these
  8171. expressions may contain side effects and should be executed only
  8172. when the condition of the \code{if} is true (for the ``then''
  8173. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8174. provides a way to initialize the temporary variables within the two branches
  8175. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8176. form executes the statements $ss$ and then returns the result of
  8177. expression $e$.}
  8178. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8179. the new features in \LangIf{}. In recursively processing
  8180. subexpressions, recall that you should invoke \code{rco\_atom} when
  8181. the output needs to be an \Atm{} (as specified in the grammar for
  8182. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8183. \Exp{}. Regarding \code{if}, it is particularly important
  8184. \emph{not} to replace its condition with a temporary variable, because
  8185. that would interfere with the generation of high-quality output in the
  8186. upcoming \code{explicate\_control} pass.
  8187. \newcommand{\LifMonadASTRacket}{
  8188. \begin{array}{rcl}
  8189. \Atm &::=& \BOOL{\itm{bool}}\\
  8190. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8191. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8192. \MID \IF{\Exp}{\Exp}{\Exp}
  8193. \end{array}
  8194. }
  8195. \newcommand{\LifMonadASTPython}{
  8196. \begin{array}{rcl}
  8197. \Atm &::=& \BOOL{\itm{bool}}\\
  8198. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8199. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8200. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8201. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8202. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8203. \end{array}
  8204. }
  8205. \begin{figure}[tp]
  8206. \centering
  8207. \begin{tcolorbox}[colback=white]
  8208. {\if\edition\racketEd
  8209. \[
  8210. \begin{array}{l}
  8211. \gray{\LvarMonadASTRacket} \\ \hline
  8212. \LifMonadASTRacket \\
  8213. \begin{array}{rcl}
  8214. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8215. \end{array}
  8216. \end{array}
  8217. \]
  8218. \fi}
  8219. {\if\edition\pythonEd\pythonColor
  8220. \[
  8221. \begin{array}{l}
  8222. \gray{\LvarMonadASTPython} \\ \hline
  8223. \LifMonadASTPython \\
  8224. \begin{array}{rcl}
  8225. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8226. \end{array}
  8227. \end{array}
  8228. \]
  8229. \fi}
  8230. \end{tcolorbox}
  8231. \python{\index{subject}{Begin@\texttt{Begin}}}
  8232. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8233. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8234. \label{fig:Lif-anf-syntax}
  8235. \end{figure}
  8236. \begin{exercise}\normalfont\normalsize
  8237. %
  8238. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8239. and \code{rco\_exp} functions.
  8240. %
  8241. Create three new \LangIf{} programs that exercise the interesting
  8242. code in this pass.
  8243. %
  8244. {\if\edition\racketEd
  8245. In the \code{run-tests.rkt} script, add the following entry to the
  8246. list of \code{passes} and then run the script to test your compiler.
  8247. \begin{lstlisting}
  8248. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8249. \end{lstlisting}
  8250. \fi}
  8251. \end{exercise}
  8252. \section{Explicate Control}
  8253. \label{sec:explicate-control-Lif}
  8254. \racket{Recall that the purpose of \code{explicate\_control} is to
  8255. make the order of evaluation explicit in the syntax of the program.
  8256. With the addition of \key{if}, this becomes more interesting.}
  8257. %
  8258. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8259. %
  8260. The main challenge to overcome is that the condition of an \key{if}
  8261. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8262. condition must be a comparison.
  8263. As a motivating example, consider the following program that has an
  8264. \key{if} expression nested in the condition of another \key{if}:%
  8265. \python{\footnote{Programmers rarely write nested \code{if}
  8266. expressions, but they do write nested expressions involving
  8267. logical \code{and}, which, as we have seen, translates to
  8268. \code{if}.}}
  8269. % cond_test_41.rkt, if_lt_eq.py
  8270. \begin{center}
  8271. \begin{minipage}{0.96\textwidth}
  8272. {\if\edition\racketEd
  8273. \begin{lstlisting}
  8274. (let ([x (read)])
  8275. (let ([y (read)])
  8276. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8277. (+ y 2)
  8278. (+ y 10))))
  8279. \end{lstlisting}
  8280. \fi}
  8281. {\if\edition\pythonEd\pythonColor
  8282. \begin{lstlisting}
  8283. x = input_int()
  8284. y = input_int()
  8285. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8286. \end{lstlisting}
  8287. \fi}
  8288. \end{minipage}
  8289. \end{center}
  8290. %
  8291. The naive way to compile \key{if} and the comparison operations would
  8292. be to handle each of them in isolation, regardless of their context.
  8293. Each comparison would be translated into a \key{cmpq} instruction
  8294. followed by several instructions to move the result from the EFLAGS
  8295. register into a general purpose register or stack location. Each
  8296. \key{if} would be translated into a \key{cmpq} instruction followed by
  8297. a conditional jump. The generated code for the inner \key{if} in this
  8298. example would be as follows:
  8299. \begin{center}
  8300. \begin{minipage}{0.96\textwidth}
  8301. \begin{lstlisting}
  8302. cmpq $1, x
  8303. setl %al
  8304. movzbq %al, tmp
  8305. cmpq $1, tmp
  8306. je then_branch_1
  8307. jmp else_branch_1
  8308. \end{lstlisting}
  8309. \end{minipage}
  8310. \end{center}
  8311. Notice that the three instructions starting with \code{setl} are
  8312. redundant; the conditional jump could come immediately after the first
  8313. \code{cmpq}.
  8314. Our goal is to compile \key{if} expressions so that the relevant
  8315. comparison instruction appears directly before the conditional jump.
  8316. For example, we want to generate the following code for the inner
  8317. \code{if}:
  8318. \begin{center}
  8319. \begin{minipage}{0.96\textwidth}
  8320. \begin{lstlisting}
  8321. cmpq $1, x
  8322. jl then_branch_1
  8323. jmp else_branch_1
  8324. \end{lstlisting}
  8325. \end{minipage}
  8326. \end{center}
  8327. One way to achieve this goal is to reorganize the code at the level of
  8328. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8329. the following code:
  8330. \begin{center}
  8331. \begin{minipage}{0.96\textwidth}
  8332. {\if\edition\racketEd
  8333. \begin{lstlisting}
  8334. (let ([x (read)])
  8335. (let ([y (read)])
  8336. (if (< x 1)
  8337. (if (eq? x 0)
  8338. (+ y 2)
  8339. (+ y 10))
  8340. (if (eq? x 2)
  8341. (+ y 2)
  8342. (+ y 10)))))
  8343. \end{lstlisting}
  8344. \fi}
  8345. {\if\edition\pythonEd\pythonColor
  8346. \begin{lstlisting}
  8347. x = input_int()
  8348. y = input_int()
  8349. print(((y + 2) if x == 0 else (y + 10)) \
  8350. if (x < 1) \
  8351. else ((y + 2) if (x == 2) else (y + 10)))
  8352. \end{lstlisting}
  8353. \fi}
  8354. \end{minipage}
  8355. \end{center}
  8356. Unfortunately, this approach duplicates the two branches from the
  8357. outer \code{if}, and a compiler must never duplicate code! After all,
  8358. the two branches could be very large expressions.
  8359. How can we apply this transformation without duplicating code? In
  8360. other words, how can two different parts of a program refer to one
  8361. piece of code?
  8362. %
  8363. The answer is that we must move away from abstract syntax \emph{trees}
  8364. and instead use \emph{graphs}.
  8365. %
  8366. At the level of x86 assembly, this is straightforward because we can
  8367. label the code for each branch and insert jumps in all the places that
  8368. need to execute the branch. In this way, jump instructions are edges
  8369. in the graph and the basic blocks are the nodes.
  8370. %
  8371. Likewise, our language \LangCIf{} provides the ability to label a
  8372. sequence of statements and to jump to a label via \code{goto}.
  8373. As a preview of what \code{explicate\_control} will do,
  8374. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8375. \code{explicate\_control} on this example. Note how the condition of
  8376. every \code{if} is a comparison operation and that we have not
  8377. duplicated any code but instead have used labels and \code{goto} to
  8378. enable sharing of code.
  8379. \begin{figure}[tbp]
  8380. \begin{tcolorbox}[colback=white]
  8381. {\if\edition\racketEd
  8382. \begin{tabular}{lll}
  8383. \begin{minipage}{0.4\textwidth}
  8384. % cond_test_41.rkt
  8385. \begin{lstlisting}
  8386. (let ([x (read)])
  8387. (let ([y (read)])
  8388. (if (if (< x 1)
  8389. (eq? x 0)
  8390. (eq? x 2))
  8391. (+ y 2)
  8392. (+ y 10))))
  8393. \end{lstlisting}
  8394. \end{minipage}
  8395. &
  8396. $\Rightarrow$
  8397. &
  8398. \begin{minipage}{0.55\textwidth}
  8399. \begin{lstlisting}
  8400. start:
  8401. x = (read);
  8402. y = (read);
  8403. if (< x 1)
  8404. goto block_4;
  8405. else
  8406. goto block_5;
  8407. block_4:
  8408. if (eq? x 0)
  8409. goto block_2;
  8410. else
  8411. goto block_3;
  8412. block_5:
  8413. if (eq? x 2)
  8414. goto block_2;
  8415. else
  8416. goto block_3;
  8417. block_2:
  8418. return (+ y 2);
  8419. block_3:
  8420. return (+ y 10);
  8421. \end{lstlisting}
  8422. \end{minipage}
  8423. \end{tabular}
  8424. \fi}
  8425. {\if\edition\pythonEd\pythonColor
  8426. \begin{tabular}{lll}
  8427. \begin{minipage}{0.4\textwidth}
  8428. % tests/if/if_lt_eq.py
  8429. \begin{lstlisting}
  8430. x = input_int()
  8431. y = input_int()
  8432. print(y + 2 \
  8433. if (x == 0 \
  8434. if x < 1 \
  8435. else x == 2) \
  8436. else y + 10)
  8437. \end{lstlisting}
  8438. \end{minipage}
  8439. &
  8440. $\Rightarrow\qquad$
  8441. &
  8442. \begin{minipage}{0.55\textwidth}
  8443. \begin{lstlisting}
  8444. start:
  8445. x = input_int()
  8446. y = input_int()
  8447. if x < 1:
  8448. goto block_6
  8449. else:
  8450. goto block_7
  8451. block_6:
  8452. if x == 0:
  8453. goto block_4
  8454. else:
  8455. goto block_5
  8456. block_7:
  8457. if x == 2:
  8458. goto block_4
  8459. else:
  8460. goto block_5
  8461. block_4:
  8462. tmp.82 = (y + 2)
  8463. goto block_3
  8464. block_5:
  8465. tmp.82 = (y + 10)
  8466. goto block_3
  8467. block_3:
  8468. print(tmp.82)
  8469. return 0
  8470. \end{lstlisting}
  8471. \end{minipage}
  8472. \end{tabular}
  8473. \fi}
  8474. \end{tcolorbox}
  8475. \caption{Translation from \LangIf{} to \LangCIf{}
  8476. via the \code{explicate\_control}.}
  8477. \label{fig:explicate-control-s1-38}
  8478. \end{figure}
  8479. {\if\edition\racketEd
  8480. %
  8481. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8482. \code{explicate\_control} for \LangVar{} using two recursive
  8483. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8484. former function translates expressions in tail position, whereas the
  8485. latter function translates expressions on the right-hand side of a
  8486. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8487. have a new kind of position to deal with: the predicate position of
  8488. the \key{if}. We need another function, \code{explicate\_pred}, that
  8489. decides how to compile an \key{if} by analyzing its condition. So,
  8490. \code{explicate\_pred} takes an \LangIf{} expression and two
  8491. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8492. and outputs a tail. In the following paragraphs we discuss specific
  8493. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8494. \code{explicate\_pred} functions.
  8495. %
  8496. \fi}
  8497. %
  8498. {\if\edition\pythonEd\pythonColor
  8499. %
  8500. We recommend implementing \code{explicate\_control} using the
  8501. following four auxiliary functions.
  8502. \begin{description}
  8503. \item[\code{explicate\_effect}] generates code for expressions as
  8504. statements, so their result is ignored and only their side effects
  8505. matter.
  8506. \item[\code{explicate\_assign}] generates code for expressions
  8507. on the right-hand side of an assignment.
  8508. \item[\code{explicate\_pred}] generates code for an \code{if}
  8509. expression or statement by analyzing the condition expression.
  8510. \item[\code{explicate\_stmt}] generates code for statements.
  8511. \end{description}
  8512. These four functions should build the dictionary of basic blocks. The
  8513. following auxiliary function \code{create\_block} is used to create a
  8514. new basic block from a list of statements. If the list just contains a
  8515. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8516. \code{create\_block} creates a new basic block and returns a
  8517. \code{goto} to its label.
  8518. \begin{center}
  8519. \begin{minipage}{\textwidth}
  8520. \begin{lstlisting}
  8521. def create_block(stmts, basic_blocks):
  8522. match stmts:
  8523. case [Goto(l)]:
  8524. return stmts
  8525. case _:
  8526. label = label_name(generate_name('block'))
  8527. basic_blocks[label] = stmts
  8528. return [Goto(label)]
  8529. \end{lstlisting}
  8530. \end{minipage}
  8531. \end{center}
  8532. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8533. \code{explicate\_control} pass.
  8534. The \code{explicate\_effect} function has three parameters: (1) the
  8535. expression to be compiled; (2) the already-compiled code for this
  8536. expression's \emph{continuation}, that is, the list of statements that
  8537. should execute after this expression; and (3) the dictionary of
  8538. generated basic blocks. The \code{explicate\_effect} function returns
  8539. a list of \LangCIf{} statements and it may add to the dictionary of
  8540. basic blocks.
  8541. %
  8542. Let's consider a few of the cases for the expression to be compiled.
  8543. If the expression to be compiled is a constant, then it can be
  8544. discarded because it has no side effects. If it's a \CREAD{}, then it
  8545. has a side effect and should be preserved. So the expression should be
  8546. translated into a statement using the \code{Expr} AST class. If the
  8547. expression to be compiled is an \code{if} expression, we translate the
  8548. two branches using \code{explicate\_effect} and then translate the
  8549. condition expression using \code{explicate\_pred}, which generates
  8550. code for the entire \code{if}.
  8551. The \code{explicate\_assign} function has four parameters: (1) the
  8552. right-hand side of the assignment, (2) the left-hand side of the
  8553. assignment (the variable), (3) the continuation, and (4) the dictionary
  8554. of basic blocks. The \code{explicate\_assign} function returns a list
  8555. of \LangCIf{} statements, and it may add to the dictionary of basic
  8556. blocks.
  8557. When the right-hand side is an \code{if} expression, there is some
  8558. work to do. In particular, the two branches should be translated using
  8559. \code{explicate\_assign}, and the condition expression should be
  8560. translated using \code{explicate\_pred}. Otherwise we can simply
  8561. generate an assignment statement, with the given left- and right-hand
  8562. sides, concatenated with its continuation.
  8563. \begin{figure}[tbp]
  8564. \begin{tcolorbox}[colback=white]
  8565. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8566. def explicate_effect(e, cont, basic_blocks):
  8567. match e:
  8568. case IfExp(test, body, orelse):
  8569. ...
  8570. case Call(func, args):
  8571. ...
  8572. case Begin(body, result):
  8573. ...
  8574. case _:
  8575. ...
  8576. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8577. match rhs:
  8578. case IfExp(test, body, orelse):
  8579. ...
  8580. case Begin(body, result):
  8581. ...
  8582. case _:
  8583. return [Assign([lhs], rhs)] + cont
  8584. def explicate_pred(cnd, thn, els, basic_blocks):
  8585. match cnd:
  8586. case Compare(left, [op], [right]):
  8587. goto_thn = create_block(thn, basic_blocks)
  8588. goto_els = create_block(els, basic_blocks)
  8589. return [If(cnd, goto_thn, goto_els)]
  8590. case Constant(True):
  8591. return thn;
  8592. case Constant(False):
  8593. return els;
  8594. case UnaryOp(Not(), operand):
  8595. ...
  8596. case IfExp(test, body, orelse):
  8597. ...
  8598. case Begin(body, result):
  8599. ...
  8600. case _:
  8601. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8602. create_block(els, basic_blocks),
  8603. create_block(thn, basic_blocks))]
  8604. def explicate_stmt(s, cont, basic_blocks):
  8605. match s:
  8606. case Assign([lhs], rhs):
  8607. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8608. case Expr(value):
  8609. return explicate_effect(value, cont, basic_blocks)
  8610. case If(test, body, orelse):
  8611. ...
  8612. def explicate_control(p):
  8613. match p:
  8614. case Module(body):
  8615. new_body = [Return(Constant(0))]
  8616. basic_blocks = {}
  8617. for s in reversed(body):
  8618. new_body = explicate_stmt(s, new_body, basic_blocks)
  8619. basic_blocks[label_name('start')] = new_body
  8620. return CProgram(basic_blocks)
  8621. \end{lstlisting}
  8622. \end{tcolorbox}
  8623. \caption{Skeleton for the \code{explicate\_control} pass.}
  8624. \label{fig:explicate-control-Lif}
  8625. \end{figure}
  8626. \fi}
  8627. {\if\edition\racketEd
  8628. \subsection{Explicate Tail and Assign}
  8629. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8630. additional cases for Boolean constants and \key{if}. The cases for
  8631. \code{if} should recursively compile the two branches using either
  8632. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8633. cases should then invoke \code{explicate\_pred} on the condition
  8634. expression, passing in the generated code for the two branches. For
  8635. example, consider the following program with an \code{if} in tail
  8636. position.
  8637. % cond_test_6.rkt
  8638. \begin{lstlisting}
  8639. (let ([x (read)])
  8640. (if (eq? x 0) 42 777))
  8641. \end{lstlisting}
  8642. The two branches are recursively compiled to return statements. We
  8643. then delegate to \code{explicate\_pred}, passing the condition
  8644. \code{(eq? x 0)} and the two return statements. We return to this
  8645. example shortly when we discuss \code{explicate\_pred}.
  8646. Next let us consider a program with an \code{if} on the right-hand
  8647. side of a \code{let}.
  8648. \begin{lstlisting}
  8649. (let ([y (read)])
  8650. (let ([x (if (eq? y 0) 40 777)])
  8651. (+ x 2)))
  8652. \end{lstlisting}
  8653. Note that the body of the inner \code{let} will have already been
  8654. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8655. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8656. to recursively process both branches of the \code{if}, and we do not
  8657. want to duplicate code, so we generate the following block using an
  8658. auxiliary function named \code{create\_block}, discussed in the next
  8659. section.
  8660. \begin{lstlisting}
  8661. block_6:
  8662. return (+ x 2)
  8663. \end{lstlisting}
  8664. We then use \code{goto block\_6;} as the \code{cont} argument for
  8665. compiling the branches. So the two branches compile to
  8666. \begin{center}
  8667. \begin{minipage}{0.2\textwidth}
  8668. \begin{lstlisting}
  8669. x = 40;
  8670. goto block_6;
  8671. \end{lstlisting}
  8672. \end{minipage}
  8673. \hspace{0.5in} and \hspace{0.5in}
  8674. \begin{minipage}{0.2\textwidth}
  8675. \begin{lstlisting}
  8676. x = 777;
  8677. goto block_6;
  8678. \end{lstlisting}
  8679. \end{minipage}
  8680. \end{center}
  8681. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8682. \code{(eq? y 0)} and the previously presented code for the branches.
  8683. \subsection{Create Block}
  8684. We recommend implementing the \code{create\_block} auxiliary function
  8685. as follows, using a global variable \code{basic-blocks} to store a
  8686. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8687. that \code{create\_block} generates a new label and then associates
  8688. the given \code{tail} with the new label in the \code{basic-blocks}
  8689. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8690. new label. However, if the given \code{tail} is already a \code{Goto},
  8691. then there is no need to generate a new label and entry in
  8692. \code{basic-blocks}; we can simply return that \code{Goto}.
  8693. %
  8694. \begin{lstlisting}
  8695. (define (create_block tail)
  8696. (match tail
  8697. [(Goto label) (Goto label)]
  8698. [else
  8699. (let ([label (gensym 'block)])
  8700. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8701. (Goto label))]))
  8702. \end{lstlisting}
  8703. \fi}
  8704. {\if\edition\racketEd
  8705. \subsection{Explicate Predicate}
  8706. The skeleton for the \code{explicate\_pred} function is given in
  8707. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8708. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8709. the code generated by explicate for the \emph{then} branch; and (3)
  8710. \code{els}, the code generated by explicate for the \emph{else}
  8711. branch. The \code{explicate\_pred} function should match on
  8712. \code{cnd} with a case for every kind of expression that can have type
  8713. \BOOLTY{}.
  8714. \begin{figure}[tbp]
  8715. \begin{tcolorbox}[colback=white]
  8716. \begin{lstlisting}
  8717. (define (explicate_pred cnd thn els)
  8718. (match cnd
  8719. [(Var x) ___]
  8720. [(Let x rhs body) ___]
  8721. [(Prim 'not (list e)) ___]
  8722. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8723. (IfStmt (Prim op es) (create_block thn)
  8724. (create_block els))]
  8725. [(Bool b) (if b thn els)]
  8726. [(If cnd^ thn^ els^) ___]
  8727. [else (error "explicate_pred unhandled case" cnd)]))
  8728. \end{lstlisting}
  8729. \end{tcolorbox}
  8730. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8731. \label{fig:explicate-pred}
  8732. \end{figure}
  8733. \fi}
  8734. %
  8735. {\if\edition\pythonEd\pythonColor
  8736. The \code{explicate\_pred} function has four parameters: (1) the
  8737. condition expression, (2) the generated statements for the \emph{then}
  8738. branch, (3) the generated statements for the \emph{else} branch, and
  8739. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8740. function returns a list of statements, and it adds to the dictionary
  8741. of basic blocks.
  8742. \fi}
  8743. Consider the case for comparison operators. We translate the
  8744. comparison to an \code{if} statement whose branches are \code{goto}
  8745. statements created by applying \code{create\_block} to the \code{thn}
  8746. and \code{els} parameters. Let us illustrate this translation by
  8747. returning to the program with an \code{if} expression in tail
  8748. position, shown next. We invoke \code{explicate\_pred} on its
  8749. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8750. %
  8751. {\if\edition\racketEd
  8752. \begin{lstlisting}
  8753. (let ([x (read)])
  8754. (if (eq? x 0) 42 777))
  8755. \end{lstlisting}
  8756. \fi}
  8757. %
  8758. {\if\edition\pythonEd\pythonColor
  8759. \begin{lstlisting}
  8760. x = input_int()
  8761. 42 if x == 0 else 777
  8762. \end{lstlisting}
  8763. \fi}
  8764. %
  8765. \noindent The two branches \code{42} and \code{777} were already
  8766. compiled to \code{return} statements, from which we now create the
  8767. following blocks:
  8768. %
  8769. \begin{center}
  8770. \begin{minipage}{\textwidth}
  8771. \begin{lstlisting}
  8772. block_1:
  8773. return 42;
  8774. block_2:
  8775. return 777;
  8776. \end{lstlisting}
  8777. \end{minipage}
  8778. \end{center}
  8779. %
  8780. After that, \code{explicate\_pred} compiles the comparison
  8781. \racket{\code{(eq? x 0)}}
  8782. \python{\code{x == 0}}
  8783. to the following \code{if} statement:
  8784. %
  8785. {\if\edition\racketEd
  8786. \begin{center}
  8787. \begin{minipage}{\textwidth}
  8788. \begin{lstlisting}
  8789. if (eq? x 0)
  8790. goto block_1;
  8791. else
  8792. goto block_2;
  8793. \end{lstlisting}
  8794. \end{minipage}
  8795. \end{center}
  8796. \fi}
  8797. {\if\edition\pythonEd\pythonColor
  8798. \begin{center}
  8799. \begin{minipage}{\textwidth}
  8800. \begin{lstlisting}
  8801. if x == 0:
  8802. goto block_1;
  8803. else
  8804. goto block_2;
  8805. \end{lstlisting}
  8806. \end{minipage}
  8807. \end{center}
  8808. \fi}
  8809. Next consider the case for Boolean constants. We perform a kind of
  8810. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8811. either the \code{thn} or \code{els} parameter, depending on whether the
  8812. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8813. following program:
  8814. {\if\edition\racketEd
  8815. \begin{lstlisting}
  8816. (if #t 42 777)
  8817. \end{lstlisting}
  8818. \fi}
  8819. {\if\edition\pythonEd\pythonColor
  8820. \begin{lstlisting}
  8821. 42 if True else 777
  8822. \end{lstlisting}
  8823. \fi}
  8824. %
  8825. \noindent Again, the two branches \code{42} and \code{777} were
  8826. compiled to \code{return} statements, so \code{explicate\_pred}
  8827. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8828. code for the \emph{then} branch.
  8829. \begin{lstlisting}
  8830. return 42;
  8831. \end{lstlisting}
  8832. This case demonstrates that we sometimes discard the \code{thn} or
  8833. \code{els} blocks that are input to \code{explicate\_pred}.
  8834. The case for \key{if} expressions in \code{explicate\_pred} is
  8835. particularly illuminating because it deals with the challenges
  8836. discussed previously regarding nested \key{if} expressions
  8837. (figure~\ref{fig:explicate-control-s1-38}). The
  8838. \racket{\lstinline{thn^}}\python{\code{body}} and
  8839. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8840. \key{if} inherit their context from the current one, that is,
  8841. predicate context. So, you should recursively apply
  8842. \code{explicate\_pred} to the
  8843. \racket{\lstinline{thn^}}\python{\code{body}} and
  8844. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8845. those recursive calls, pass \code{thn} and \code{els} as the extra
  8846. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8847. inside each recursive call. As discussed previously, to avoid
  8848. duplicating code, we need to add them to the dictionary of basic
  8849. blocks so that we can instead refer to them by name and execute them
  8850. with a \key{goto}.
  8851. {\if\edition\pythonEd\pythonColor
  8852. %
  8853. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8854. three parameters: (1) the statement to be compiled, (2) the code for its
  8855. continuation, and (3) the dictionary of basic blocks. The
  8856. \code{explicate\_stmt} returns a list of statements, and it may add to
  8857. the dictionary of basic blocks. The cases for assignment and an
  8858. expression-statement are given in full in the skeleton code: they
  8859. simply dispatch to \code{explicate\_assign} and
  8860. \code{explicate\_effect}, respectively. The case for \code{if}
  8861. statements is not given; it is similar to the case for \code{if}
  8862. expressions.
  8863. The \code{explicate\_control} function itself is given in
  8864. figure~\ref{fig:explicate-control-Lif}. It applies
  8865. \code{explicate\_stmt} to each statement in the program, from back to
  8866. front. Thus, the result so far, stored in \code{new\_body}, can be
  8867. used as the continuation parameter in the next call to
  8868. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8869. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8870. the dictionary of basic blocks, labeling it the ``start'' block.
  8871. %
  8872. \fi}
  8873. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8874. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8875. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8876. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8877. %% results from the two recursive calls. We complete the case for
  8878. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8879. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8880. %% the result $B_5$.
  8881. %% \[
  8882. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8883. %% \quad\Rightarrow\quad
  8884. %% B_5
  8885. %% \]
  8886. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8887. %% inherit the current context, so they are in tail position. Thus, the
  8888. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8889. %% \code{explicate\_tail}.
  8890. %% %
  8891. %% We need to pass $B_0$ as the accumulator argument for both of these
  8892. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8893. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8894. %% to the control-flow graph and obtain a promised goto $G_0$.
  8895. %% %
  8896. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8897. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8898. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8899. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8900. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8901. %% \[
  8902. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8903. %% \]
  8904. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8905. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8906. %% should not be confused with the labels for the blocks that appear in
  8907. %% the generated code. We initially construct unlabeled blocks; we only
  8908. %% attach labels to blocks when we add them to the control-flow graph, as
  8909. %% we see in the next case.
  8910. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8911. %% function. The context of the \key{if} is an assignment to some
  8912. %% variable $x$ and then the control continues to some promised block
  8913. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8914. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8915. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8916. %% branches of the \key{if} inherit the current context, so they are in
  8917. %% assignment positions. Let $B_2$ be the result of applying
  8918. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8919. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8920. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8921. %% the result of applying \code{explicate\_pred} to the predicate
  8922. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8923. %% translates to the promise $B_4$.
  8924. %% \[
  8925. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8926. %% \]
  8927. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8928. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8929. \code{remove\_complex\_operands} pass and then the
  8930. \code{explicate\_control} pass on the example program. We walk through
  8931. the output program.
  8932. %
  8933. Following the order of evaluation in the output of
  8934. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8935. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8936. in the predicate of the inner \key{if}. In the output of
  8937. \code{explicate\_control}, in the
  8938. block labeled \code{start}, two assignment statements are followed by an
  8939. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8940. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8941. The blocks associated with those labels contain the
  8942. translations of the code
  8943. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8944. and
  8945. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8946. respectively. In particular, we start
  8947. \racket{\code{block\_4}}\python{\code{block\_6}}
  8948. with the comparison
  8949. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8950. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8951. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8952. which correspond to the two branches of the outer \key{if}, that is,
  8953. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8954. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8955. %
  8956. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8957. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8958. %
  8959. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8960. {\if\edition\racketEd
  8961. \subsection{Interactions between Explicate and Shrink}
  8962. The way in which the \code{shrink} pass transforms logical operations
  8963. such as \code{and} and \code{or} can impact the quality of code
  8964. generated by \code{explicate\_control}. For example, consider the
  8965. following program:
  8966. % cond_test_21.rkt, and_eq_input.py
  8967. \begin{lstlisting}
  8968. (if (and (eq? (read) 0) (eq? (read) 1))
  8969. 0
  8970. 42)
  8971. \end{lstlisting}
  8972. The \code{and} operation should transform into something that the
  8973. \code{explicate\_pred} function can analyze and descend through to
  8974. reach the underlying \code{eq?} conditions. Ideally, for this program
  8975. your \code{explicate\_control} pass should generate code similar to
  8976. the following:
  8977. \begin{center}
  8978. \begin{minipage}{\textwidth}
  8979. \begin{lstlisting}
  8980. start:
  8981. tmp1 = (read);
  8982. if (eq? tmp1 0) goto block40;
  8983. else goto block39;
  8984. block40:
  8985. tmp2 = (read);
  8986. if (eq? tmp2 1) goto block38;
  8987. else goto block39;
  8988. block38:
  8989. return 0;
  8990. block39:
  8991. return 42;
  8992. \end{lstlisting}
  8993. \end{minipage}
  8994. \end{center}
  8995. \fi}
  8996. \begin{exercise}\normalfont\normalsize
  8997. \racket{
  8998. Implement the pass \code{explicate\_control} by adding the cases for
  8999. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9000. \code{explicate\_assign} functions. Implement the auxiliary function
  9001. \code{explicate\_pred} for predicate contexts.}
  9002. \python{Implement \code{explicate\_control} pass with its
  9003. four auxiliary functions.}
  9004. %
  9005. Create test cases that exercise all the new cases in the code for
  9006. this pass.
  9007. %
  9008. {\if\edition\racketEd
  9009. Add the following entry to the list of \code{passes} in
  9010. \code{run-tests.rkt}:
  9011. \begin{lstlisting}
  9012. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9013. \end{lstlisting}
  9014. and then run \code{run-tests.rkt} to test your compiler.
  9015. \fi}
  9016. \end{exercise}
  9017. \section{Select Instructions}
  9018. \label{sec:select-Lif}
  9019. \index{subject}{select instructions}
  9020. The \code{select\_instructions} pass translates \LangCIf{} to
  9021. \LangXIfVar{}.
  9022. %
  9023. \racket{Recall that we implement this pass using three auxiliary
  9024. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9025. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9026. %
  9027. \racket{For $\Atm$, we have new cases for the Booleans.}
  9028. %
  9029. \python{We begin with the Boolean constants.}
  9030. As previously discussed, we encode them as integers.
  9031. \[
  9032. \TRUE{} \quad\Rightarrow\quad \key{1}
  9033. \qquad\qquad
  9034. \FALSE{} \quad\Rightarrow\quad \key{0}
  9035. \]
  9036. For translating statements, we discuss some of the cases. The
  9037. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9038. discussed at the beginning of this section. Given an assignment, if
  9039. the left-hand-side variable is the same as the argument of \code{not},
  9040. then just the \code{xorq} instruction suffices.
  9041. \[
  9042. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9043. \quad\Rightarrow\quad
  9044. \key{xorq}~\key{\$}1\key{,}~\Var
  9045. \]
  9046. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9047. semantics of x86. In the following translation, let $\Arg$ be the
  9048. result of translating $\Atm$ to x86.
  9049. \[
  9050. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9051. \quad\Rightarrow\quad
  9052. \begin{array}{l}
  9053. \key{movq}~\Arg\key{,}~\Var\\
  9054. \key{xorq}~\key{\$}1\key{,}~\Var
  9055. \end{array}
  9056. \]
  9057. Next consider the cases for equality comparisons. Translating this
  9058. operation to x86 is slightly involved due to the unusual nature of the
  9059. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9060. We recommend translating an assignment with an equality on the
  9061. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9062. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9063. \begin{tabular}{lll}
  9064. \begin{minipage}{0.4\textwidth}
  9065. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9066. \end{minipage}
  9067. &
  9068. $\Rightarrow$
  9069. &
  9070. \begin{minipage}{0.4\textwidth}
  9071. \begin{lstlisting}
  9072. cmpq |$\Arg_2$|, |$\Arg_1$|
  9073. sete %al
  9074. movzbq %al, |$\Var$|
  9075. \end{lstlisting}
  9076. \end{minipage}
  9077. \end{tabular} \\
  9078. The translations for the other comparison operators are similar to
  9079. this but use different condition codes for the \code{set} instruction.
  9080. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9081. \key{goto} and \key{if} statements. Both are straightforward to
  9082. translate to x86.}
  9083. %
  9084. A \key{goto} statement becomes a jump instruction.
  9085. \[
  9086. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9087. \]
  9088. %
  9089. An \key{if} statement becomes a compare instruction followed by a
  9090. conditional jump (for the \emph{then} branch), and the fall-through is to
  9091. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9092. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9093. \begin{tabular}{lll}
  9094. \begin{minipage}{0.4\textwidth}
  9095. \begin{lstlisting}
  9096. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9097. goto |$\ell_1$||$\racket{\key{;}}$|
  9098. else|$\python{\key{:}}$|
  9099. goto |$\ell_2$||$\racket{\key{;}}$|
  9100. \end{lstlisting}
  9101. \end{minipage}
  9102. &
  9103. $\Rightarrow$
  9104. &
  9105. \begin{minipage}{0.4\textwidth}
  9106. \begin{lstlisting}
  9107. cmpq |$\Arg_2$|, |$\Arg_1$|
  9108. je |$\ell_1$|
  9109. jmp |$\ell_2$|
  9110. \end{lstlisting}
  9111. \end{minipage}
  9112. \end{tabular} \\
  9113. Again, the translations for the other comparison operators are similar to this
  9114. but use different condition codes for the conditional jump instruction.
  9115. \python{Regarding the \key{return} statement, we recommend treating it
  9116. as an assignment to the \key{rax} register followed by a jump to the
  9117. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9118. \begin{exercise}\normalfont\normalsize
  9119. Expand your \code{select\_instructions} pass to handle the new
  9120. features of the \LangCIf{} language.
  9121. %
  9122. {\if\edition\racketEd
  9123. Add the following entry to the list of \code{passes} in
  9124. \code{run-tests.rkt}
  9125. \begin{lstlisting}
  9126. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9127. \end{lstlisting}
  9128. \fi}
  9129. %
  9130. Run the script to test your compiler on all the test programs.
  9131. \end{exercise}
  9132. \section{Register Allocation}
  9133. \label{sec:register-allocation-Lif}
  9134. \index{subject}{register allocation}
  9135. The changes required for compiling \LangIf{} affect liveness analysis,
  9136. building the interference graph, and assigning homes, but the graph
  9137. coloring algorithm itself does not change.
  9138. \subsection{Liveness Analysis}
  9139. \label{sec:liveness-analysis-Lif}
  9140. \index{subject}{liveness analysis}
  9141. Recall that for \LangVar{} we implemented liveness analysis for a
  9142. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9143. the addition of \key{if} expressions to \LangIf{},
  9144. \code{explicate\_control} produces many basic blocks.
  9145. %% We recommend that you create a new auxiliary function named
  9146. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9147. %% control-flow graph.
  9148. The first question is, in what order should we process the basic blocks?
  9149. Recall that to perform liveness analysis on a basic block we need to
  9150. know the live-after set for the last instruction in the block. If a
  9151. basic block has no successors (i.e., contains no jumps to other
  9152. blocks), then it has an empty live-after set and we can immediately
  9153. apply liveness analysis to it. If a basic block has some successors,
  9154. then we need to complete liveness analysis on those blocks
  9155. first. These ordering constraints are the reverse of a
  9156. \emph{topological order}\index{subject}{topological order} on a graph
  9157. representation of the program. In particular, the \emph{control flow
  9158. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9159. of a program has a node for each basic block and an edge for each jump
  9160. from one block to another. It is straightforward to generate a CFG
  9161. from the dictionary of basic blocks. One then transposes the CFG and
  9162. applies the topological sort algorithm.
  9163. %
  9164. %
  9165. \racket{We recommend using the \code{tsort} and \code{transpose}
  9166. functions of the Racket \code{graph} package to accomplish this.}
  9167. %
  9168. \python{We provide implementations of \code{topological\_sort} and
  9169. \code{transpose} in the file \code{graph.py} of the support code.}
  9170. %
  9171. As an aside, a topological ordering is only guaranteed to exist if the
  9172. graph does not contain any cycles. This is the case for the
  9173. control-flow graphs that we generate from \LangIf{} programs.
  9174. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9175. and learn how to handle cycles in the control-flow graph.
  9176. \racket{You need to construct a directed graph to represent the
  9177. control-flow graph. Do not use the \code{directed-graph} of the
  9178. \code{graph} package because that allows at most one edge
  9179. between each pair of vertices, whereas a control-flow graph may have
  9180. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9181. file in the support code implements a graph representation that
  9182. allows multiple edges between a pair of vertices.}
  9183. {\if\edition\racketEd
  9184. The next question is how to analyze jump instructions. Recall that in
  9185. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9186. \code{label->live} that maps each label to the set of live locations
  9187. at the beginning of its block. We use \code{label->live} to determine
  9188. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9189. that we have many basic blocks, \code{label->live} needs to be updated
  9190. as we process the blocks. In particular, after performing liveness
  9191. analysis on a block, we take the live-before set of its first
  9192. instruction and associate that with the block's label in the
  9193. \code{label->live} alist.
  9194. \fi}
  9195. %
  9196. {\if\edition\pythonEd\pythonColor
  9197. %
  9198. The next question is how to analyze jump instructions. The locations
  9199. that are live before a \code{jmp} should be the locations in
  9200. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9201. maintaining a dictionary named \code{live\_before\_block} that maps each
  9202. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9203. block. After performing liveness analysis on each block, we take the
  9204. live-before set of its first instruction and associate that with the
  9205. block's label in the \code{live\_before\_block} dictionary.
  9206. %
  9207. \fi}
  9208. In \LangXIfVar{} we also have the conditional jump
  9209. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9210. this instruction is particularly interesting because during
  9211. compilation, we do not know which way a conditional jump will go. Thus
  9212. we do not know whether to use the live-before set for the block
  9213. associated with the $\itm{label}$ or the live-before set for the
  9214. following instruction. So we use both, by taking the union of the
  9215. live-before sets from the following instruction and from the mapping
  9216. for $\itm{label}$ in
  9217. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9218. The auxiliary functions for computing the variables in an
  9219. instruction's argument and for computing the variables read-from ($R$)
  9220. or written-to ($W$) by an instruction need to be updated to handle the
  9221. new kinds of arguments and instructions in \LangXIfVar{}.
  9222. \begin{exercise}\normalfont\normalsize
  9223. {\if\edition\racketEd
  9224. %
  9225. Update the \code{uncover\_live} pass to apply liveness analysis to
  9226. every basic block in the program.
  9227. %
  9228. Add the following entry to the list of \code{passes} in the
  9229. \code{run-tests.rkt} script:
  9230. \begin{lstlisting}
  9231. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9232. \end{lstlisting}
  9233. \fi}
  9234. {\if\edition\pythonEd\pythonColor
  9235. %
  9236. Update the \code{uncover\_live} function to perform liveness analysis,
  9237. in reverse topological order, on all the basic blocks in the
  9238. program.
  9239. %
  9240. \fi}
  9241. % Check that the live-after sets that you generate for
  9242. % example X matches the following... -Jeremy
  9243. \end{exercise}
  9244. \subsection{Build the Interference Graph}
  9245. \label{sec:build-interference-Lif}
  9246. Many of the new instructions in \LangXIfVar{} can be handled in the
  9247. same way as the instructions in \LangXVar{}.
  9248. % Thus, if your code was
  9249. % already quite general, it will not need to be changed to handle the
  9250. % new instructions. If your code is not general enough, we recommend that
  9251. % you change your code to be more general. For example, you can factor
  9252. % out the computing of the the read and write sets for each kind of
  9253. % instruction into auxiliary functions.
  9254. %
  9255. Some instructions, such as the \key{movzbq} instruction, require special care,
  9256. similar to the \key{movq} instruction. Refer to rule number 1 in
  9257. section~\ref{sec:build-interference}.
  9258. \begin{exercise}\normalfont\normalsize
  9259. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9260. {\if\edition\racketEd
  9261. Add the following entries to the list of \code{passes} in the
  9262. \code{run-tests.rkt} script:
  9263. \begin{lstlisting}
  9264. (list "build_interference" build_interference interp-pseudo-x86-1)
  9265. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9266. \end{lstlisting}
  9267. \fi}
  9268. % Check that the interference graph that you generate for
  9269. % example X matches the following graph G... -Jeremy
  9270. \end{exercise}
  9271. \section{Patch Instructions}
  9272. The new instructions \key{cmpq} and \key{movzbq} have some special
  9273. restrictions that need to be handled in the \code{patch\_instructions}
  9274. pass.
  9275. %
  9276. The second argument of the \key{cmpq} instruction must not be an
  9277. immediate value (such as an integer). So, if you are comparing two
  9278. immediates, we recommend inserting a \key{movq} instruction to put the
  9279. second argument in \key{rax}. On the other hand, if you implemented
  9280. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9281. update it for \LangIf{} and then this situation would not arise.
  9282. %
  9283. As usual, \key{cmpq} may have at most one memory reference.
  9284. %
  9285. The second argument of the \key{movzbq} must be a register.
  9286. \begin{exercise}\normalfont\normalsize
  9287. %
  9288. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9289. %
  9290. {\if\edition\racketEd
  9291. Add the following entry to the list of \code{passes} in
  9292. \code{run-tests.rkt}, and then run this script to test your compiler.
  9293. \begin{lstlisting}
  9294. (list "patch_instructions" patch_instructions interp-x86-1)
  9295. \end{lstlisting}
  9296. \fi}
  9297. \end{exercise}
  9298. {\if\edition\pythonEd\pythonColor
  9299. \section{Generate Prelude and Conclusion}
  9300. \label{sec:prelude-conclusion-cond}
  9301. The generation of the \code{main} function with its prelude and
  9302. conclusion must change to accommodate how the program now consists of
  9303. one or more basic blocks. After the prelude in \code{main}, jump to
  9304. the \code{start} block. Place the conclusion in a basic block labeled
  9305. with \code{conclusion}.
  9306. \fi}
  9307. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9308. \LangIf{} translated to x86, showing the results of
  9309. \code{explicate\_control}, \code{select\_instructions}, and the final
  9310. x86 assembly.
  9311. \begin{figure}[tbp]
  9312. \begin{tcolorbox}[colback=white]
  9313. {\if\edition\racketEd
  9314. \begin{tabular}{lll}
  9315. \begin{minipage}{0.4\textwidth}
  9316. % cond_test_20.rkt, eq_input.py
  9317. \begin{lstlisting}
  9318. (if (eq? (read) 1) 42 0)
  9319. \end{lstlisting}
  9320. $\Downarrow$
  9321. \begin{lstlisting}
  9322. start:
  9323. tmp7951 = (read);
  9324. if (eq? tmp7951 1)
  9325. goto block7952;
  9326. else
  9327. goto block7953;
  9328. block7952:
  9329. return 42;
  9330. block7953:
  9331. return 0;
  9332. \end{lstlisting}
  9333. $\Downarrow$
  9334. \begin{lstlisting}
  9335. start:
  9336. callq read_int
  9337. movq %rax, tmp7951
  9338. cmpq $1, tmp7951
  9339. je block7952
  9340. jmp block7953
  9341. block7953:
  9342. movq $0, %rax
  9343. jmp conclusion
  9344. block7952:
  9345. movq $42, %rax
  9346. jmp conclusion
  9347. \end{lstlisting}
  9348. \end{minipage}
  9349. &
  9350. $\Rightarrow\qquad$
  9351. \begin{minipage}{0.4\textwidth}
  9352. \begin{lstlisting}
  9353. start:
  9354. callq read_int
  9355. movq %rax, %rcx
  9356. cmpq $1, %rcx
  9357. je block7952
  9358. jmp block7953
  9359. block7953:
  9360. movq $0, %rax
  9361. jmp conclusion
  9362. block7952:
  9363. movq $42, %rax
  9364. jmp conclusion
  9365. .globl main
  9366. main:
  9367. pushq %rbp
  9368. movq %rsp, %rbp
  9369. pushq %r13
  9370. pushq %r12
  9371. pushq %rbx
  9372. pushq %r14
  9373. subq $0, %rsp
  9374. jmp start
  9375. conclusion:
  9376. addq $0, %rsp
  9377. popq %r14
  9378. popq %rbx
  9379. popq %r12
  9380. popq %r13
  9381. popq %rbp
  9382. retq
  9383. \end{lstlisting}
  9384. \end{minipage}
  9385. \end{tabular}
  9386. \fi}
  9387. {\if\edition\pythonEd\pythonColor
  9388. \begin{tabular}{lll}
  9389. \begin{minipage}{0.4\textwidth}
  9390. % cond_test_20.rkt, eq_input.py
  9391. \begin{lstlisting}
  9392. print(42 if input_int() == 1 else 0)
  9393. \end{lstlisting}
  9394. $\Downarrow$
  9395. \begin{lstlisting}
  9396. start:
  9397. tmp_0 = input_int()
  9398. if tmp_0 == 1:
  9399. goto block_3
  9400. else:
  9401. goto block_4
  9402. block_3:
  9403. tmp_1 = 42
  9404. goto block_2
  9405. block_4:
  9406. tmp_1 = 0
  9407. goto block_2
  9408. block_2:
  9409. print(tmp_1)
  9410. return 0
  9411. \end{lstlisting}
  9412. $\Downarrow$
  9413. \begin{lstlisting}
  9414. start:
  9415. callq read_int
  9416. movq %rax, tmp_0
  9417. cmpq 1, tmp_0
  9418. je block_3
  9419. jmp block_4
  9420. block_3:
  9421. movq 42, tmp_1
  9422. jmp block_2
  9423. block_4:
  9424. movq 0, tmp_1
  9425. jmp block_2
  9426. block_2:
  9427. movq tmp_1, %rdi
  9428. callq print_int
  9429. movq 0, %rax
  9430. jmp conclusion
  9431. \end{lstlisting}
  9432. \end{minipage}
  9433. &
  9434. $\Rightarrow\qquad$
  9435. \begin{minipage}{0.4\textwidth}
  9436. \begin{lstlisting}
  9437. .globl main
  9438. main:
  9439. pushq %rbp
  9440. movq %rsp, %rbp
  9441. subq $0, %rsp
  9442. jmp start
  9443. start:
  9444. callq read_int
  9445. movq %rax, %rcx
  9446. cmpq $1, %rcx
  9447. je block_3
  9448. jmp block_4
  9449. block_3:
  9450. movq $42, %rcx
  9451. jmp block_2
  9452. block_4:
  9453. movq $0, %rcx
  9454. jmp block_2
  9455. block_2:
  9456. movq %rcx, %rdi
  9457. callq print_int
  9458. movq $0, %rax
  9459. jmp conclusion
  9460. conclusion:
  9461. addq $0, %rsp
  9462. popq %rbp
  9463. retq
  9464. \end{lstlisting}
  9465. \end{minipage}
  9466. \end{tabular}
  9467. \fi}
  9468. \end{tcolorbox}
  9469. \caption{Example compilation of an \key{if} expression to x86, showing
  9470. the results of \code{explicate\_control},
  9471. \code{select\_instructions}, and the final x86 assembly code. }
  9472. \label{fig:if-example-x86}
  9473. \end{figure}
  9474. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9475. compilation of \LangIf{}.
  9476. \begin{figure}[htbp]
  9477. \begin{tcolorbox}[colback=white]
  9478. {\if\edition\racketEd
  9479. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9480. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9481. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9482. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9483. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9484. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9485. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9486. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9487. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9488. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9489. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9490. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9491. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9492. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9493. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9494. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9495. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9496. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9497. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9498. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9499. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9500. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9501. \end{tikzpicture}
  9502. \fi}
  9503. {\if\edition\pythonEd\pythonColor
  9504. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9505. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9506. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9507. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9508. \node (C-1) at (0,0) {\large \LangCIf{}};
  9509. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9510. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9511. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9512. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9513. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9514. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9515. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9516. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9517. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9518. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9519. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9520. \end{tikzpicture}
  9521. \fi}
  9522. \end{tcolorbox}
  9523. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9524. \label{fig:Lif-passes}
  9525. \end{figure}
  9526. \section{Challenge: Optimize Blocks and Remove Jumps}
  9527. \label{sec:opt-jumps}
  9528. We discuss two challenges that involve optimizing the control-flow of
  9529. the program.
  9530. \subsection{Optimize Blocks}
  9531. The algorithm for \code{explicate\_control} that we discussed in
  9532. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9533. blocks. It creates a block whenever a continuation \emph{might} get
  9534. used more than once (for example, whenever the \code{cont} parameter
  9535. is passed into two or more recursive calls). However, some
  9536. continuation arguments may not be used at all. Consider the case for
  9537. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9538. the \code{els} continuation.
  9539. %
  9540. {\if\edition\racketEd
  9541. The following example program falls into this
  9542. case, and it creates two unused blocks.
  9543. \begin{center}
  9544. \begin{tabular}{lll}
  9545. \begin{minipage}{0.4\textwidth}
  9546. % cond_test_82.rkt
  9547. \begin{lstlisting}
  9548. (let ([y (if #t
  9549. (read)
  9550. (if (eq? (read) 0)
  9551. 777
  9552. (let ([x (read)])
  9553. (+ 1 x))))])
  9554. (+ y 2))
  9555. \end{lstlisting}
  9556. \end{minipage}
  9557. &
  9558. $\Rightarrow$
  9559. &
  9560. \begin{minipage}{0.4\textwidth}
  9561. \begin{lstlisting}
  9562. start:
  9563. y = (read);
  9564. goto block_5;
  9565. block_5:
  9566. return (+ y 2);
  9567. block_6:
  9568. y = 777;
  9569. goto block_5;
  9570. block_7:
  9571. x = (read);
  9572. y = (+ 1 x2);
  9573. goto block_5;
  9574. \end{lstlisting}
  9575. \end{minipage}
  9576. \end{tabular}
  9577. \end{center}
  9578. \fi}
  9579. {\if\edition\pythonEd
  9580. The following example program falls into this
  9581. case, and it creates the unused \code{block\_9}.
  9582. \begin{center}
  9583. \begin{minipage}{0.4\textwidth}
  9584. % if/if_true.py
  9585. \begin{lstlisting}
  9586. if True:
  9587. print(0)
  9588. else:
  9589. x = 1 if False else 2
  9590. print(x)
  9591. \end{lstlisting}
  9592. \end{minipage}
  9593. $\Rightarrow\qquad\qquad$
  9594. \begin{minipage}{0.4\textwidth}
  9595. \begin{lstlisting}
  9596. start:
  9597. print(0)
  9598. goto block_8
  9599. block_9:
  9600. print(x)
  9601. goto block_8
  9602. block_8:
  9603. return 0
  9604. \end{lstlisting}
  9605. \end{minipage}
  9606. \end{center}
  9607. \fi}
  9608. The question is, how can we decide whether to create a basic block?
  9609. \emph{Lazy evaluation}\index{subject}{lazy
  9610. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9611. delaying the creation of a basic block until the point in time at which
  9612. we know that it will be used.
  9613. %
  9614. {\if\edition\racketEd
  9615. %
  9616. Racket provides support for
  9617. lazy evaluation with the
  9618. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9619. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9620. \index{subject}{delay} creates a
  9621. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9622. expressions is postponed. When \key{(force}
  9623. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9624. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9625. result of $e_n$ is cached in the promise and returned. If \code{force}
  9626. is applied again to the same promise, then the cached result is
  9627. returned. If \code{force} is applied to an argument that is not a
  9628. promise, \code{force} simply returns the argument.
  9629. %
  9630. \fi}
  9631. %
  9632. {\if\edition\pythonEd\pythonColor
  9633. %
  9634. Although Python does not provide direct support for lazy evaluation,
  9635. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9636. by wrapping it inside a function with no parameters. We \emph{force}
  9637. its evaluation by calling the function. However, we might need to
  9638. force multiple times, so we store the result of calling the
  9639. function instead of recomputing it each time. The following
  9640. \code{Promise} class handles this memoization process.
  9641. \begin{minipage}{0.8\textwidth}
  9642. \begin{lstlisting}
  9643. @dataclass
  9644. class Promise:
  9645. fun : typing.Any
  9646. cache : list[stmt] = None
  9647. def force(self):
  9648. if self.cache is None:
  9649. self.cache = self.fun(); return self.cache
  9650. else:
  9651. return self.cache
  9652. \end{lstlisting}
  9653. \end{minipage}
  9654. \noindent However, in some cases of \code{explicate\_pred}, we return
  9655. a list of statements, and in other cases we return a function that
  9656. computes a list of statements. To uniformly deal with both regular
  9657. data and promises, we define the following \code{force} function that
  9658. checks whether its input is delayed (i.e., whether it is a
  9659. \code{Promise}) and then either (1) forces the promise or (2) returns
  9660. the input.
  9661. %
  9662. \begin{lstlisting}
  9663. def force(promise):
  9664. if isinstance(promise, Promise):
  9665. return promise.force()
  9666. else:
  9667. return promise
  9668. \end{lstlisting}
  9669. %
  9670. \fi}
  9671. We use promises for the input and output of the functions
  9672. \code{explicate\_pred}, \code{explicate\_assign},
  9673. %
  9674. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9675. %
  9676. So, instead of taking and returning \racket{$\Tail$
  9677. expressions}\python{lists of statements}, they take and return
  9678. promises. Furthermore, when we come to a situation in which a
  9679. continuation might be used more than once, as in the case for
  9680. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9681. that creates a basic block for each continuation (if there is not
  9682. already one) and then returns a \code{goto} statement to that basic
  9683. block. When we come to a situation in which we have a promise but need an
  9684. actual piece of code, for example, to create a larger piece of code with a
  9685. constructor such as \code{Seq}, then insert a call to \code{force}.
  9686. %
  9687. {\if\edition\racketEd
  9688. %
  9689. Also, we must modify the \code{create\_block} function to begin with
  9690. \code{delay} to create a promise. When forced, this promise forces the
  9691. original promise. If that returns a \code{Goto} (because the block was
  9692. already added to \code{basic-blocks}), then we return the
  9693. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9694. return a \code{Goto} to the new label.
  9695. \begin{center}
  9696. \begin{minipage}{\textwidth}
  9697. \begin{lstlisting}
  9698. (define (create_block tail)
  9699. (delay
  9700. (define t (force tail))
  9701. (match t
  9702. [(Goto label) (Goto label)]
  9703. [else
  9704. (let ([label (gensym 'block)])
  9705. (set! basic-blocks (cons (cons label t) basic-blocks))
  9706. (Goto label))])))
  9707. \end{lstlisting}
  9708. \end{minipage}
  9709. \end{center}
  9710. \fi}
  9711. {\if\edition\pythonEd\pythonColor
  9712. %
  9713. Here is the new version of the \code{create\_block} auxiliary function
  9714. that delays the creation of the new basic block.\\
  9715. \begin{minipage}{\textwidth}
  9716. \begin{lstlisting}
  9717. def create_block(promise, basic_blocks):
  9718. def delay():
  9719. stmts = force(promise)
  9720. match stmts:
  9721. case [Goto(l)]:
  9722. return [Goto(l)]
  9723. case _:
  9724. label = label_name(generate_name('block'))
  9725. basic_blocks[label] = stmts
  9726. return [Goto(label)]
  9727. return Promise(delay)
  9728. \end{lstlisting}
  9729. \end{minipage}
  9730. \fi}
  9731. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9732. improved \code{explicate\_control} on this example.
  9733. \racket{As you can see, the number of basic blocks has been reduced
  9734. from four blocks to two blocks.}%
  9735. \python{As you can see, the number of basic blocks has been reduced
  9736. from three blocks to two blocks.}
  9737. \begin{figure}[tbp]
  9738. \begin{tcolorbox}[colback=white]
  9739. {\if\edition\racketEd
  9740. \begin{tabular}{lll}
  9741. \begin{minipage}{0.45\textwidth}
  9742. % cond_test_82.rkt
  9743. \begin{lstlisting}
  9744. (let ([y (if #t
  9745. (read)
  9746. (if (eq? (read) 0)
  9747. 777
  9748. (let ([x (read)])
  9749. (+ 1 x))))])
  9750. (+ y 2))
  9751. \end{lstlisting}
  9752. \end{minipage}
  9753. &
  9754. $\quad\Rightarrow\quad$
  9755. &
  9756. \begin{minipage}{0.4\textwidth}
  9757. \begin{lstlisting}
  9758. start:
  9759. y = (read);
  9760. goto block_5;
  9761. block_5:
  9762. return (+ y 2);
  9763. \end{lstlisting}
  9764. \end{minipage}
  9765. \end{tabular}
  9766. \fi}
  9767. {\if\edition\pythonEd\pythonColor
  9768. \begin{tabular}{lll}
  9769. \begin{minipage}{0.4\textwidth}
  9770. % if/if_true.py
  9771. \begin{lstlisting}
  9772. if True:
  9773. print(0)
  9774. else:
  9775. x = 1 if False else 2
  9776. print(x)
  9777. \end{lstlisting}
  9778. \end{minipage}
  9779. &
  9780. $\Rightarrow$
  9781. &
  9782. \begin{minipage}{0.55\textwidth}
  9783. \begin{lstlisting}
  9784. start:
  9785. print(0)
  9786. goto block_4
  9787. block_4:
  9788. return 0
  9789. \end{lstlisting}
  9790. \end{minipage}
  9791. \end{tabular}
  9792. \fi}
  9793. \end{tcolorbox}
  9794. \caption{Translation from \LangIf{} to \LangCIf{}
  9795. via the improved \code{explicate\_control}.}
  9796. \label{fig:explicate-control-challenge}
  9797. \end{figure}
  9798. %% Recall that in the example output of \code{explicate\_control} in
  9799. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9800. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9801. %% block. The first goal of this challenge assignment is to remove those
  9802. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9803. %% \code{explicate\_control} on the left and shows the result of bypassing
  9804. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9805. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9806. %% \code{block55}. The optimized code on the right of
  9807. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9808. %% \code{then} branch jumping directly to \code{block55}. The story is
  9809. %% similar for the \code{else} branch, as well as for the two branches in
  9810. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9811. %% have been optimized in this way, there are no longer any jumps to
  9812. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9813. %% \begin{figure}[tbp]
  9814. %% \begin{tabular}{lll}
  9815. %% \begin{minipage}{0.4\textwidth}
  9816. %% \begin{lstlisting}
  9817. %% block62:
  9818. %% tmp54 = (read);
  9819. %% if (eq? tmp54 2) then
  9820. %% goto block59;
  9821. %% else
  9822. %% goto block60;
  9823. %% block61:
  9824. %% tmp53 = (read);
  9825. %% if (eq? tmp53 0) then
  9826. %% goto block57;
  9827. %% else
  9828. %% goto block58;
  9829. %% block60:
  9830. %% goto block56;
  9831. %% block59:
  9832. %% goto block55;
  9833. %% block58:
  9834. %% goto block56;
  9835. %% block57:
  9836. %% goto block55;
  9837. %% block56:
  9838. %% return (+ 700 77);
  9839. %% block55:
  9840. %% return (+ 10 32);
  9841. %% start:
  9842. %% tmp52 = (read);
  9843. %% if (eq? tmp52 1) then
  9844. %% goto block61;
  9845. %% else
  9846. %% goto block62;
  9847. %% \end{lstlisting}
  9848. %% \end{minipage}
  9849. %% &
  9850. %% $\Rightarrow$
  9851. %% &
  9852. %% \begin{minipage}{0.55\textwidth}
  9853. %% \begin{lstlisting}
  9854. %% block62:
  9855. %% tmp54 = (read);
  9856. %% if (eq? tmp54 2) then
  9857. %% goto block55;
  9858. %% else
  9859. %% goto block56;
  9860. %% block61:
  9861. %% tmp53 = (read);
  9862. %% if (eq? tmp53 0) then
  9863. %% goto block55;
  9864. %% else
  9865. %% goto block56;
  9866. %% block56:
  9867. %% return (+ 700 77);
  9868. %% block55:
  9869. %% return (+ 10 32);
  9870. %% start:
  9871. %% tmp52 = (read);
  9872. %% if (eq? tmp52 1) then
  9873. %% goto block61;
  9874. %% else
  9875. %% goto block62;
  9876. %% \end{lstlisting}
  9877. %% \end{minipage}
  9878. %% \end{tabular}
  9879. %% \caption{Optimize jumps by removing trivial blocks.}
  9880. %% \label{fig:optimize-jumps}
  9881. %% \end{figure}
  9882. %% The name of this pass is \code{optimize-jumps}. We recommend
  9883. %% implementing this pass in two phases. The first phrase builds a hash
  9884. %% table that maps labels to possibly improved labels. The second phase
  9885. %% changes the target of each \code{goto} to use the improved label. If
  9886. %% the label is for a trivial block, then the hash table should map the
  9887. %% label to the first non-trivial block that can be reached from this
  9888. %% label by jumping through trivial blocks. If the label is for a
  9889. %% non-trivial block, then the hash table should map the label to itself;
  9890. %% we do not want to change jumps to non-trivial blocks.
  9891. %% The first phase can be accomplished by constructing an empty hash
  9892. %% table, call it \code{short-cut}, and then iterating over the control
  9893. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9894. %% then update the hash table, mapping the block's source to the target
  9895. %% of the \code{goto}. Also, the hash table may already have mapped some
  9896. %% labels to the block's source, to you must iterate through the hash
  9897. %% table and update all of those so that they instead map to the target
  9898. %% of the \code{goto}.
  9899. %% For the second phase, we recommend iterating through the $\Tail$ of
  9900. %% each block in the program, updating the target of every \code{goto}
  9901. %% according to the mapping in \code{short-cut}.
  9902. \begin{exercise}\normalfont\normalsize
  9903. Implement the improvements to the \code{explicate\_control} pass.
  9904. Check that it removes trivial blocks in a few example programs. Then
  9905. check that your compiler still passes all your tests.
  9906. \end{exercise}
  9907. \subsection{Remove Jumps}
  9908. There is an opportunity for removing jumps that is apparent in the
  9909. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9910. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9911. and there are no other jumps to
  9912. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9913. In this situation we can avoid the runtime overhead of this jump by merging
  9914. \racket{\code{block\_5}}\python{\code{block\_4}}
  9915. into the preceding block, which in this case is the \code{start} block.
  9916. Figure~\ref{fig:remove-jumps} shows the output of
  9917. \code{allocate\_registers} on the left and the result of this
  9918. optimization on the right.
  9919. \begin{figure}[tbp]
  9920. \begin{tcolorbox}[colback=white]
  9921. {\if\edition\racketEd
  9922. \begin{tabular}{lll}
  9923. \begin{minipage}{0.5\textwidth}
  9924. % cond_test_82.rkt
  9925. \begin{lstlisting}
  9926. start:
  9927. callq read_int
  9928. movq %rax, %rcx
  9929. jmp block_5
  9930. block_5:
  9931. movq %rcx, %rax
  9932. addq $2, %rax
  9933. jmp conclusion
  9934. \end{lstlisting}
  9935. \end{minipage}
  9936. &
  9937. $\Rightarrow\qquad$
  9938. \begin{minipage}{0.4\textwidth}
  9939. \begin{lstlisting}
  9940. start:
  9941. callq read_int
  9942. movq %rax, %rcx
  9943. movq %rcx, %rax
  9944. addq $2, %rax
  9945. jmp conclusion
  9946. \end{lstlisting}
  9947. \end{minipage}
  9948. \end{tabular}
  9949. \fi}
  9950. {\if\edition\pythonEd\pythonColor
  9951. \begin{tabular}{lll}
  9952. \begin{minipage}{0.5\textwidth}
  9953. % cond_test_20.rkt
  9954. \begin{lstlisting}
  9955. start:
  9956. callq read_int
  9957. movq %rax, tmp_0
  9958. cmpq 1, tmp_0
  9959. je block_3
  9960. jmp block_4
  9961. block_3:
  9962. movq 42, tmp_1
  9963. jmp block_2
  9964. block_4:
  9965. movq 0, tmp_1
  9966. jmp block_2
  9967. block_2:
  9968. movq tmp_1, %rdi
  9969. callq print_int
  9970. movq 0, %rax
  9971. jmp conclusion
  9972. \end{lstlisting}
  9973. \end{minipage}
  9974. &
  9975. $\Rightarrow\qquad$
  9976. \begin{minipage}{0.4\textwidth}
  9977. \begin{lstlisting}
  9978. start:
  9979. callq read_int
  9980. movq %rax, tmp_0
  9981. cmpq 1, tmp_0
  9982. je block_3
  9983. movq 0, tmp_1
  9984. jmp block_2
  9985. block_3:
  9986. movq 42, tmp_1
  9987. jmp block_2
  9988. block_2:
  9989. movq tmp_1, %rdi
  9990. callq print_int
  9991. movq 0, %rax
  9992. jmp conclusion
  9993. \end{lstlisting}
  9994. \end{minipage}
  9995. \end{tabular}
  9996. \fi}
  9997. \end{tcolorbox}
  9998. \caption{Merging basic blocks by removing unnecessary jumps.}
  9999. \label{fig:remove-jumps}
  10000. \end{figure}
  10001. \begin{exercise}\normalfont\normalsize
  10002. %
  10003. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10004. into their preceding basic block, when there is only one preceding
  10005. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10006. %
  10007. {\if\edition\racketEd
  10008. In the \code{run-tests.rkt} script, add the following entry to the
  10009. list of \code{passes} between \code{allocate\_registers}
  10010. and \code{patch\_instructions}:
  10011. \begin{lstlisting}
  10012. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10013. \end{lstlisting}
  10014. \fi}
  10015. %
  10016. Run the script to test your compiler.
  10017. %
  10018. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10019. blocks on several test programs.
  10020. \end{exercise}
  10021. \section{Further Reading}
  10022. \label{sec:cond-further-reading}
  10023. The algorithm for \code{explicate\_control} is based on the
  10024. \code{expose-basic-blocks} pass in the course notes of
  10025. \citet{Dybvig:2010aa}.
  10026. %
  10027. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10028. \citet{Appel:2003fk}, and is related to translations into continuation
  10029. passing
  10030. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10031. %
  10032. The treatment of conditionals in the \code{explicate\_control} pass is
  10033. similar to short-cut Boolean
  10034. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10035. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10036. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10037. \chapter{Loops and Dataflow Analysis}
  10038. \label{ch:Lwhile}
  10039. \setcounter{footnote}{0}
  10040. % TODO: define R'_8
  10041. % TODO: multi-graph
  10042. {\if\edition\racketEd
  10043. %
  10044. In this chapter we study two features that are the hallmarks of
  10045. imperative programming languages: loops and assignments to local
  10046. variables. The following example demonstrates these new features by
  10047. computing the sum of the first five positive integers:
  10048. % similar to loop_test_1.rkt
  10049. \begin{lstlisting}
  10050. (let ([sum 0])
  10051. (let ([i 5])
  10052. (begin
  10053. (while (> i 0)
  10054. (begin
  10055. (set! sum (+ sum i))
  10056. (set! i (- i 1))))
  10057. sum)))
  10058. \end{lstlisting}
  10059. The \code{while} loop consists of a condition and a
  10060. body.\footnote{The \code{while} loop is not a built-in
  10061. feature of the Racket language, but Racket includes many looping
  10062. constructs and it is straightforward to define \code{while} as a
  10063. macro.} The body is evaluated repeatedly so long as the condition
  10064. remains true.
  10065. %
  10066. The \code{set!} consists of a variable and a right-hand side
  10067. expression. The \code{set!} updates value of the variable to the
  10068. value of the right-hand side.
  10069. %
  10070. The primary purpose of both the \code{while} loop and \code{set!} is
  10071. to cause side effects, so they do not give a meaningful result
  10072. value. Instead, their result is the \code{\#<void>} value. The
  10073. expression \code{(void)} is an explicit way to create the
  10074. \code{\#<void>} value, and it has type \code{Void}. The
  10075. \code{\#<void>} value can be passed around just like other values
  10076. inside an \LangLoop{} program, and it can be compared for equality with
  10077. another \code{\#<void>} value. However, there are no other operations
  10078. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10079. Racket defines the \code{void?} predicate that returns \code{\#t}
  10080. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10081. %
  10082. \footnote{Racket's \code{Void} type corresponds to what is often
  10083. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10084. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10085. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10086. %
  10087. With the addition of side effect-producing features such as
  10088. \code{while} loop and \code{set!}, it is helpful to include a language
  10089. feature for sequencing side effects: the \code{begin} expression. It
  10090. consists of one or more subexpressions that are evaluated
  10091. left to right.
  10092. %
  10093. \fi}
  10094. {\if\edition\pythonEd\pythonColor
  10095. %
  10096. In this chapter we study loops, one of the hallmarks of imperative
  10097. programming languages. The following example demonstrates the
  10098. \code{while} loop by computing the sum of the first five positive
  10099. integers.
  10100. \begin{lstlisting}
  10101. sum = 0
  10102. i = 5
  10103. while i > 0:
  10104. sum = sum + i
  10105. i = i - 1
  10106. print(sum)
  10107. \end{lstlisting}
  10108. The \code{while} loop consists of a condition and a body (a sequence
  10109. of statements). The body is evaluated repeatedly so long as the
  10110. condition remains true.
  10111. %
  10112. \fi}
  10113. \section{The \LangLoop{} Language}
  10114. \newcommand{\LwhileGrammarRacket}{
  10115. \begin{array}{lcl}
  10116. \Type &::=& \key{Void}\\
  10117. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10118. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10119. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10120. \end{array}
  10121. }
  10122. \newcommand{\LwhileASTRacket}{
  10123. \begin{array}{lcl}
  10124. \Type &::=& \key{Void}\\
  10125. \Exp &::=& \SETBANG{\Var}{\Exp}
  10126. \MID \BEGIN{\Exp^{*}}{\Exp}
  10127. \MID \WHILE{\Exp}{\Exp}
  10128. \MID \VOID{}
  10129. \end{array}
  10130. }
  10131. \newcommand{\LwhileGrammarPython}{
  10132. \begin{array}{rcl}
  10133. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10134. \end{array}
  10135. }
  10136. \newcommand{\LwhileASTPython}{
  10137. \begin{array}{lcl}
  10138. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10139. \end{array}
  10140. }
  10141. \begin{figure}[tp]
  10142. \centering
  10143. \begin{tcolorbox}[colback=white]
  10144. \small
  10145. {\if\edition\racketEd
  10146. \[
  10147. \begin{array}{l}
  10148. \gray{\LintGrammarRacket{}} \\ \hline
  10149. \gray{\LvarGrammarRacket{}} \\ \hline
  10150. \gray{\LifGrammarRacket{}} \\ \hline
  10151. \LwhileGrammarRacket \\
  10152. \begin{array}{lcl}
  10153. \LangLoopM{} &::=& \Exp
  10154. \end{array}
  10155. \end{array}
  10156. \]
  10157. \fi}
  10158. {\if\edition\pythonEd\pythonColor
  10159. \[
  10160. \begin{array}{l}
  10161. \gray{\LintGrammarPython} \\ \hline
  10162. \gray{\LvarGrammarPython} \\ \hline
  10163. \gray{\LifGrammarPython} \\ \hline
  10164. \LwhileGrammarPython \\
  10165. \begin{array}{rcl}
  10166. \LangLoopM{} &::=& \Stmt^{*}
  10167. \end{array}
  10168. \end{array}
  10169. \]
  10170. \fi}
  10171. \end{tcolorbox}
  10172. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10173. \label{fig:Lwhile-concrete-syntax}
  10174. \end{figure}
  10175. \begin{figure}[tp]
  10176. \centering
  10177. \begin{tcolorbox}[colback=white]
  10178. \small
  10179. {\if\edition\racketEd
  10180. \[
  10181. \begin{array}{l}
  10182. \gray{\LintOpAST} \\ \hline
  10183. \gray{\LvarASTRacket{}} \\ \hline
  10184. \gray{\LifASTRacket{}} \\ \hline
  10185. \LwhileASTRacket{} \\
  10186. \begin{array}{lcl}
  10187. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10188. \end{array}
  10189. \end{array}
  10190. \]
  10191. \fi}
  10192. {\if\edition\pythonEd\pythonColor
  10193. \[
  10194. \begin{array}{l}
  10195. \gray{\LintASTPython} \\ \hline
  10196. \gray{\LvarASTPython} \\ \hline
  10197. \gray{\LifASTPython} \\ \hline
  10198. \LwhileASTPython \\
  10199. \begin{array}{lcl}
  10200. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10201. \end{array}
  10202. \end{array}
  10203. \]
  10204. \fi}
  10205. \end{tcolorbox}
  10206. \python{
  10207. \index{subject}{While@\texttt{While}}
  10208. }
  10209. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10210. \label{fig:Lwhile-syntax}
  10211. \end{figure}
  10212. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10213. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10214. shows the definition of its abstract syntax.
  10215. %
  10216. The definitional interpreter for \LangLoop{} is shown in
  10217. figure~\ref{fig:interp-Lwhile}.
  10218. %
  10219. {\if\edition\racketEd
  10220. %
  10221. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10222. and \code{Void}, and we make changes to the cases for \code{Var} and
  10223. \code{Let} regarding variables. To support assignment to variables and
  10224. to make their lifetimes indefinite (see the second example in
  10225. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10226. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10227. value.
  10228. %
  10229. Now we discuss the new cases. For \code{SetBang}, we find the
  10230. variable in the environment to obtain a boxed value, and then we change
  10231. it using \code{set-box!} to the result of evaluating the right-hand
  10232. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10233. %
  10234. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10235. if the result is true, (2) evaluate the body.
  10236. The result value of a \code{while} loop is also \code{\#<void>}.
  10237. %
  10238. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10239. subexpressions \itm{es} for their effects and then evaluates
  10240. and returns the result from \itm{body}.
  10241. %
  10242. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10243. %
  10244. \fi}
  10245. {\if\edition\pythonEd\pythonColor
  10246. %
  10247. We add a new case for \code{While} in the \code{interp\_stmts}
  10248. function, in which we repeatedly interpret the \code{body} so long as the
  10249. \code{test} expression remains true.
  10250. %
  10251. \fi}
  10252. \begin{figure}[tbp]
  10253. \begin{tcolorbox}[colback=white]
  10254. {\if\edition\racketEd
  10255. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10256. (define interp-Lwhile-class
  10257. (class interp-Lif-class
  10258. (super-new)
  10259. (define/override ((interp-exp env) e)
  10260. (define recur (interp-exp env))
  10261. (match e
  10262. [(Let x e body)
  10263. (define new-env (dict-set env x (box (recur e))))
  10264. ((interp-exp new-env) body)]
  10265. [(Var x) (unbox (dict-ref env x))]
  10266. [(SetBang x rhs)
  10267. (set-box! (dict-ref env x) (recur rhs))]
  10268. [(WhileLoop cnd body)
  10269. (define (loop)
  10270. (cond [(recur cnd) (recur body) (loop)]
  10271. [else (void)]))
  10272. (loop)]
  10273. [(Begin es body)
  10274. (for ([e es]) (recur e))
  10275. (recur body)]
  10276. [(Void) (void)]
  10277. [else ((super interp-exp env) e)]))
  10278. ))
  10279. (define (interp-Lwhile p)
  10280. (send (new interp-Lwhile-class) interp-program p))
  10281. \end{lstlisting}
  10282. \fi}
  10283. {\if\edition\pythonEd\pythonColor
  10284. \begin{lstlisting}
  10285. class InterpLwhile(InterpLif):
  10286. def interp_stmt(self, s, env, cont):
  10287. match s:
  10288. case While(test, body, []):
  10289. if self.interp_exp(test, env):
  10290. self.interp_stmts(body + [s] + cont, env)
  10291. else:
  10292. return self.interp_stmts(cont, env)
  10293. case _:
  10294. return super().interp_stmt(s, env, cont)
  10295. \end{lstlisting}
  10296. \fi}
  10297. \end{tcolorbox}
  10298. \caption{Interpreter for \LangLoop{}.}
  10299. \label{fig:interp-Lwhile}
  10300. \end{figure}
  10301. The definition of the type checker for \LangLoop{} is shown in
  10302. figure~\ref{fig:type-check-Lwhile}.
  10303. %
  10304. {\if\edition\racketEd
  10305. %
  10306. The type checking of the \code{SetBang} expression requires the type
  10307. of the variable and the right-hand side to agree. The result type is
  10308. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10309. and the result type is \code{Void}. For \code{Begin}, the result type
  10310. is the type of its last subexpression.
  10311. %
  10312. \fi}
  10313. %
  10314. {\if\edition\pythonEd\pythonColor
  10315. %
  10316. A \code{while} loop is well typed if the type of the \code{test}
  10317. expression is \code{bool} and the statements in the \code{body} are
  10318. well typed.
  10319. %
  10320. \fi}
  10321. \begin{figure}[tbp]
  10322. \begin{tcolorbox}[colback=white]
  10323. {\if\edition\racketEd
  10324. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10325. (define type-check-Lwhile-class
  10326. (class type-check-Lif-class
  10327. (super-new)
  10328. (inherit check-type-equal?)
  10329. (define/override (type-check-exp env)
  10330. (lambda (e)
  10331. (define recur (type-check-exp env))
  10332. (match e
  10333. [(SetBang x rhs)
  10334. (define-values (rhs^ rhsT) (recur rhs))
  10335. (define varT (dict-ref env x))
  10336. (check-type-equal? rhsT varT e)
  10337. (values (SetBang x rhs^) 'Void)]
  10338. [(WhileLoop cnd body)
  10339. (define-values (cnd^ Tc) (recur cnd))
  10340. (check-type-equal? Tc 'Boolean e)
  10341. (define-values (body^ Tbody) ((type-check-exp env) body))
  10342. (values (WhileLoop cnd^ body^) 'Void)]
  10343. [(Begin es body)
  10344. (define-values (es^ ts)
  10345. (for/lists (l1 l2) ([e es]) (recur e)))
  10346. (define-values (body^ Tbody) (recur body))
  10347. (values (Begin es^ body^) Tbody)]
  10348. [else ((super type-check-exp env) e)])))
  10349. ))
  10350. (define (type-check-Lwhile p)
  10351. (send (new type-check-Lwhile-class) type-check-program p))
  10352. \end{lstlisting}
  10353. \fi}
  10354. {\if\edition\pythonEd\pythonColor
  10355. \begin{lstlisting}
  10356. class TypeCheckLwhile(TypeCheckLif):
  10357. def type_check_stmts(self, ss, env):
  10358. if len(ss) == 0:
  10359. return
  10360. match ss[0]:
  10361. case While(test, body, []):
  10362. test_t = self.type_check_exp(test, env)
  10363. check_type_equal(bool, test_t, test)
  10364. body_t = self.type_check_stmts(body, env)
  10365. return self.type_check_stmts(ss[1:], env)
  10366. case _:
  10367. return super().type_check_stmts(ss, env)
  10368. \end{lstlisting}
  10369. \fi}
  10370. \end{tcolorbox}
  10371. \caption{Type checker for the \LangLoop{} language.}
  10372. \label{fig:type-check-Lwhile}
  10373. \end{figure}
  10374. {\if\edition\racketEd
  10375. %
  10376. At first glance, the translation of these language features to x86
  10377. seems straightforward because the \LangCIf{} intermediate language
  10378. already supports all the ingredients that we need: assignment,
  10379. \code{goto}, conditional branching, and sequencing. However,
  10380. complications arise, which we discuss in the next section. After
  10381. that we introduce the changes necessary to the existing passes.
  10382. %
  10383. \fi}
  10384. {\if\edition\pythonEd\pythonColor
  10385. %
  10386. At first glance, the translation of \code{while} loops to x86 seems
  10387. straightforward because the \LangCIf{} intermediate language already
  10388. supports \code{goto} and conditional branching. However, there are
  10389. complications that arise, which we discuss in the next section. After
  10390. that we introduce the changes necessary to the existing passes.
  10391. %
  10392. \fi}
  10393. \section{Cyclic Control Flow and Dataflow Analysis}
  10394. \label{sec:dataflow-analysis}
  10395. Up until this point, the programs generated in
  10396. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10397. \code{while} loop introduces a cycle. Does that matter?
  10398. %
  10399. Indeed, it does. Recall that for register allocation, the compiler
  10400. performs liveness analysis to determine which variables can share the
  10401. same register. To accomplish this, we analyzed the control-flow graph
  10402. in reverse topological order
  10403. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10404. well defined only for acyclic graphs.
  10405. Let us return to the example of computing the sum of the first five
  10406. positive integers. Here is the program after instruction
  10407. selection\index{subject}{instruction selection} but before register
  10408. allocation.
  10409. \begin{center}
  10410. {\if\edition\racketEd
  10411. \begin{minipage}{0.45\textwidth}
  10412. \begin{lstlisting}
  10413. (define (main) : Integer
  10414. mainstart:
  10415. movq $0, sum
  10416. movq $5, i
  10417. jmp block5
  10418. block5:
  10419. movq i, tmp3
  10420. cmpq tmp3, $0
  10421. jl block7
  10422. jmp block8
  10423. \end{lstlisting}
  10424. \end{minipage}
  10425. \begin{minipage}{0.45\textwidth}
  10426. \begin{lstlisting}
  10427. block7:
  10428. addq i, sum
  10429. movq $1, tmp4
  10430. negq tmp4
  10431. addq tmp4, i
  10432. jmp block5
  10433. block8:
  10434. movq $27, %rax
  10435. addq sum, %rax
  10436. jmp mainconclusion)
  10437. \end{lstlisting}
  10438. \end{minipage}
  10439. \fi}
  10440. {\if\edition\pythonEd\pythonColor
  10441. \begin{minipage}{0.45\textwidth}
  10442. \begin{lstlisting}
  10443. mainstart:
  10444. movq $0, sum
  10445. movq $5, i
  10446. jmp block5
  10447. block5:
  10448. cmpq $0, i
  10449. jg block7
  10450. jmp block8
  10451. \end{lstlisting}
  10452. \end{minipage}
  10453. \begin{minipage}{0.45\textwidth}
  10454. \begin{lstlisting}
  10455. block7:
  10456. addq i, sum
  10457. subq $1, i
  10458. jmp block5
  10459. block8:
  10460. movq sum, %rdi
  10461. callq print_int
  10462. movq $0, %rax
  10463. jmp mainconclusion
  10464. \end{lstlisting}
  10465. \end{minipage}
  10466. \fi}
  10467. \end{center}
  10468. Recall that liveness analysis works backward, starting at the end
  10469. of each function. For this example we could start with \code{block8}
  10470. because we know what is live at the beginning of the conclusion:
  10471. only \code{rax} and \code{rsp}. So the live-before set
  10472. for \code{block8} is \code{\{rsp,sum\}}.
  10473. %
  10474. Next we might try to analyze \code{block5} or \code{block7}, but
  10475. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10476. we are stuck.
  10477. The way out of this impasse is to realize that we can compute an
  10478. underapproximation of each live-before set by starting with empty
  10479. live-after sets. By \emph{underapproximation}, we mean that the set
  10480. contains only variables that are live for some execution of the
  10481. program, but the set may be missing some variables that are live.
  10482. Next, the underapproximations for each block can be improved by (1)
  10483. updating the live-after set for each block using the approximate
  10484. live-before sets from the other blocks, and (2) performing liveness
  10485. analysis again on each block. In fact, by iterating this process, the
  10486. underapproximations eventually become the correct solutions!
  10487. %
  10488. This approach of iteratively analyzing a control-flow graph is
  10489. applicable to many static analysis problems and goes by the name
  10490. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10491. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10492. Washington.
  10493. Let us apply this approach to the previously presented example. We use
  10494. the empty set for the initial live-before set for each block. Let
  10495. $m_0$ be the following mapping from label names to sets of locations
  10496. (variables and registers):
  10497. \begin{center}
  10498. \begin{lstlisting}
  10499. mainstart: {}, block5: {}, block7: {}, block8: {}
  10500. \end{lstlisting}
  10501. \end{center}
  10502. Using the above live-before approximations, we determine the
  10503. live-after for each block and then apply liveness analysis to each
  10504. block. This produces our next approximation $m_1$ of the live-before
  10505. sets.
  10506. \begin{center}
  10507. \begin{lstlisting}
  10508. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10509. \end{lstlisting}
  10510. \end{center}
  10511. For the second round, the live-after for \code{mainstart} is the
  10512. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10513. the liveness analysis for \code{mainstart} computes the empty set. The
  10514. live-after for \code{block5} is the union of the live-before sets for
  10515. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10516. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10517. sum\}}. The live-after for \code{block7} is the live-before for
  10518. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10519. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10520. Together these yield the following approximation $m_2$ of
  10521. the live-before sets:
  10522. \begin{center}
  10523. \begin{lstlisting}
  10524. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10525. \end{lstlisting}
  10526. \end{center}
  10527. In the preceding iteration, only \code{block5} changed, so we can
  10528. limit our attention to \code{mainstart} and \code{block7}, the two
  10529. blocks that jump to \code{block5}. As a result, the live-before sets
  10530. for \code{mainstart} and \code{block7} are updated to include
  10531. \code{rsp}, yielding the following approximation $m_3$:
  10532. \begin{center}
  10533. \begin{lstlisting}
  10534. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10535. \end{lstlisting}
  10536. \end{center}
  10537. Because \code{block7} changed, we analyze \code{block5} once more, but
  10538. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10539. our approximations have converged, so $m_3$ is the solution.
  10540. This iteration process is guaranteed to converge to a solution by the
  10541. Kleene fixed-point theorem, a general theorem about functions on
  10542. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10543. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10544. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10545. join operator
  10546. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10547. will be working with join semilattices.} When two elements are
  10548. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10549. as much information as $m_i$, so we can think of $m_j$ as a
  10550. better-than-or-equal-to approximation in relation to $m_i$. The
  10551. bottom element $\bot$ represents the complete lack of information,
  10552. that is, the worst approximation. The join operator takes two lattice
  10553. elements and combines their information; that is, it produces the
  10554. least upper bound of the two.\index{subject}{least upper bound}
  10555. A dataflow analysis typically involves two lattices: one lattice to
  10556. represent abstract states and another lattice that aggregates the
  10557. abstract states of all the blocks in the control-flow graph. For
  10558. liveness analysis, an abstract state is a set of locations. We form
  10559. the lattice $L$ by taking its elements to be sets of locations, the
  10560. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10561. set, and the join operator to be set union.
  10562. %
  10563. We form a second lattice $M$ by taking its elements to be mappings
  10564. from the block labels to sets of locations (elements of $L$). We
  10565. order the mappings point-wise, using the ordering of $L$. So, given any
  10566. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10567. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10568. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10569. to the empty set, $\bot_M(\ell) = \emptyset$.
  10570. We can think of one iteration of liveness analysis applied to the
  10571. whole program as being a function $f$ on the lattice $M$. It takes a
  10572. mapping as input and computes a new mapping.
  10573. \[
  10574. f(m_i) = m_{i+1}
  10575. \]
  10576. Next let us think for a moment about what a final solution $m_s$
  10577. should look like. If we perform liveness analysis using the solution
  10578. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10579. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10580. \[
  10581. f(m_s) = m_s
  10582. \]
  10583. Furthermore, the solution should include only locations that are
  10584. forced to be there by performing liveness analysis on the program, so
  10585. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10586. The Kleene fixed-point theorem states that if a function $f$ is
  10587. monotone (better inputs produce better outputs), then the least fixed
  10588. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10589. chain} that starts at $\bot$ and iterates $f$ as
  10590. follows:\index{subject}{Kleene fixed-point theorem}
  10591. \[
  10592. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10593. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10594. \]
  10595. When a lattice contains only finitely long ascending chains, then
  10596. every Kleene chain tops out at some fixed point after some number of
  10597. iterations of $f$.
  10598. \[
  10599. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10600. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10601. \]
  10602. The liveness analysis is indeed a monotone function and the lattice
  10603. $M$ has finitely long ascending chains because there are only a
  10604. finite number of variables and blocks in the program. Thus we are
  10605. guaranteed that iteratively applying liveness analysis to all blocks
  10606. in the program will eventually produce the least fixed point solution.
  10607. Next let us consider dataflow analysis in general and discuss the
  10608. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10609. %
  10610. The algorithm has four parameters: the control-flow graph \code{G}, a
  10611. function \code{transfer} that applies the analysis to one block, and the
  10612. \code{bottom} and \code{join} operators for the lattice of abstract
  10613. states. The \code{analyze\_dataflow} function is formulated as a
  10614. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10615. function come from the predecessor nodes in the control-flow
  10616. graph. However, liveness analysis is a \emph{backward} dataflow
  10617. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10618. function with the transpose of the control-flow graph.
  10619. The algorithm begins by creating the bottom mapping, represented by a
  10620. hash table. It then pushes all the nodes in the control-flow graph
  10621. onto the work list (a queue). The algorithm repeats the \code{while}
  10622. loop as long as there are items in the work list. In each iteration, a
  10623. node is popped from the work list and processed. The \code{input} for
  10624. the node is computed by taking the join of the abstract states of all
  10625. the predecessor nodes. The \code{transfer} function is then applied to
  10626. obtain the \code{output} abstract state. If the output differs from
  10627. the previous state for this block, the mapping for this block is
  10628. updated and its successor nodes are pushed onto the work list.
  10629. \begin{figure}[tb]
  10630. \begin{tcolorbox}[colback=white]
  10631. {\if\edition\racketEd
  10632. \begin{lstlisting}
  10633. (define (analyze_dataflow G transfer bottom join)
  10634. (define mapping (make-hash))
  10635. (for ([v (in-vertices G)])
  10636. (dict-set! mapping v bottom))
  10637. (define worklist (make-queue))
  10638. (for ([v (in-vertices G)])
  10639. (enqueue! worklist v))
  10640. (define trans-G (transpose G))
  10641. (while (not (queue-empty? worklist))
  10642. (define node (dequeue! worklist))
  10643. (define input (for/fold ([state bottom])
  10644. ([pred (in-neighbors trans-G node)])
  10645. (join state (dict-ref mapping pred))))
  10646. (define output (transfer node input))
  10647. (cond [(not (equal? output (dict-ref mapping node)))
  10648. (dict-set! mapping node output)
  10649. (for ([v (in-neighbors G node)])
  10650. (enqueue! worklist v))]))
  10651. mapping)
  10652. \end{lstlisting}
  10653. \fi}
  10654. {\if\edition\pythonEd\pythonColor
  10655. \begin{lstlisting}
  10656. def analyze_dataflow(G, transfer, bottom, join):
  10657. trans_G = transpose(G)
  10658. mapping = dict((v, bottom) for v in G.vertices())
  10659. worklist = deque(G.vertices)
  10660. while worklist:
  10661. node = worklist.pop()
  10662. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10663. input = reduce(join, inputs, bottom)
  10664. output = transfer(node, input)
  10665. if output != mapping[node]:
  10666. mapping[node] = output
  10667. worklist.extend(G.adjacent(node))
  10668. \end{lstlisting}
  10669. \fi}
  10670. \end{tcolorbox}
  10671. \caption{Generic work list algorithm for dataflow analysis.}
  10672. \label{fig:generic-dataflow}
  10673. \end{figure}
  10674. {\if\edition\racketEd
  10675. \section{Mutable Variables and Remove Complex Operands}
  10676. There is a subtle interaction between the
  10677. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10678. and the left-to-right order of evaluation of Racket. Consider the
  10679. following example:
  10680. \begin{lstlisting}
  10681. (let ([x 2])
  10682. (+ x (begin (set! x 40) x)))
  10683. \end{lstlisting}
  10684. The result of this program is \code{42} because the first read from
  10685. \code{x} produces \code{2} and the second produces \code{40}. However,
  10686. if we naively apply the \code{remove\_complex\_operands} pass to this
  10687. example we obtain the following program whose result is \code{80}!
  10688. \begin{lstlisting}
  10689. (let ([x 2])
  10690. (let ([tmp (begin (set! x 40) x)])
  10691. (+ x tmp)))
  10692. \end{lstlisting}
  10693. The problem is that with mutable variables, the ordering between
  10694. reads and writes is important, and the
  10695. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10696. before the first read of \code{x}.
  10697. We recommend solving this problem by giving special treatment to reads
  10698. from mutable variables, that is, variables that occur on the left-hand
  10699. side of a \code{set!}. We mark each read from a mutable variable with
  10700. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10701. that the read operation is effectful in that it can produce different
  10702. results at different points in time. Let's apply this idea to the
  10703. following variation that also involves a variable that is not mutated:
  10704. % loop_test_24.rkt
  10705. \begin{lstlisting}
  10706. (let ([x 2])
  10707. (let ([y 0])
  10708. (+ y (+ x (begin (set! x 40) x)))))
  10709. \end{lstlisting}
  10710. We first analyze this program to discover that variable \code{x}
  10711. is mutable but \code{y} is not. We then transform the program as
  10712. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10713. \begin{lstlisting}
  10714. (let ([x 2])
  10715. (let ([y 0])
  10716. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10717. \end{lstlisting}
  10718. Now that we have a clear distinction between reads from mutable and
  10719. immutable variables, we can apply the \code{remove\_complex\_operands}
  10720. pass, where reads from immutable variables are still classified as
  10721. atomic expressions but reads from mutable variables are classified as
  10722. complex. Thus, \code{remove\_complex\_operands} yields the following
  10723. program:\\
  10724. \begin{minipage}{\textwidth}
  10725. \begin{lstlisting}
  10726. (let ([x 2])
  10727. (let ([y 0])
  10728. (let ([t1 x])
  10729. (let ([t2 (begin (set! x 40) x)])
  10730. (let ([t3 (+ t1 t2)])
  10731. (+ y t3))))))
  10732. \end{lstlisting}
  10733. \end{minipage}
  10734. The temporary variable \code{t1} gets the value of \code{x} before the
  10735. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10736. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10737. do not generate a temporary variable for the occurrence of \code{y}
  10738. because it's an immutable variable. We want to avoid such unnecessary
  10739. extra temporaries because they would needlessly increase the number of
  10740. variables, making it more likely for some of them to be spilled. The
  10741. result of this program is \code{42}, the same as the result prior to
  10742. \code{remove\_complex\_operands}.
  10743. The approach that we've sketched requires only a small
  10744. modification to \code{remove\_complex\_operands} to handle
  10745. \code{get!}. However, it requires a new pass, called
  10746. \code{uncover-get!}, that we discuss in
  10747. section~\ref{sec:uncover-get-bang}.
  10748. As an aside, this problematic interaction between \code{set!} and the
  10749. pass \code{remove\_complex\_operands} is particular to Racket and not
  10750. its predecessor, the Scheme language. The key difference is that
  10751. Scheme does not specify an order of evaluation for the arguments of an
  10752. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10753. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10754. would be correct results for the example program. Interestingly,
  10755. Racket is implemented on top of the Chez Scheme
  10756. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10757. presented in this section (using extra \code{let} bindings to control
  10758. the order of evaluation) is used in the translation from Racket to
  10759. Scheme~\citep{Flatt:2019tb}.
  10760. \fi} % racket
  10761. Having discussed the complications that arise from adding support for
  10762. assignment and loops, we turn to discussing the individual compilation
  10763. passes.
  10764. {\if\edition\racketEd
  10765. \section{Uncover \texttt{get!}}
  10766. \label{sec:uncover-get-bang}
  10767. The goal of this pass is to mark uses of mutable variables so that
  10768. \code{remove\_complex\_operands} can treat them as complex expressions
  10769. and thereby preserve their ordering relative to the side effects in
  10770. other operands. So, the first step is to collect all the mutable
  10771. variables. We recommend creating an auxiliary function for this,
  10772. named \code{collect-set!}, that recursively traverses expressions,
  10773. returning the set of all variables that occur on the left-hand side of a
  10774. \code{set!}. Here's an excerpt of its implementation.
  10775. \begin{center}
  10776. \begin{minipage}{\textwidth}
  10777. \begin{lstlisting}
  10778. (define (collect-set! e)
  10779. (match e
  10780. [(Var x) (set)]
  10781. [(Int n) (set)]
  10782. [(Let x rhs body)
  10783. (set-union (collect-set! rhs) (collect-set! body))]
  10784. [(SetBang var rhs)
  10785. (set-union (set var) (collect-set! rhs))]
  10786. ...))
  10787. \end{lstlisting}
  10788. \end{minipage}
  10789. \end{center}
  10790. By placing this pass after \code{uniquify}, we need not worry about
  10791. variable shadowing, and our logic for \code{Let} can remain simple, as
  10792. in this excerpt.
  10793. The second step is to mark the occurrences of the mutable variables
  10794. with the new \code{GetBang} AST node (\code{get!} in concrete
  10795. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10796. function, which takes two parameters: the set of mutable variables
  10797. \code{set!-vars} and the expression \code{e} to be processed. The
  10798. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10799. mutable variable or leaves it alone if not.
  10800. \begin{center}
  10801. \begin{minipage}{\textwidth}
  10802. \begin{lstlisting}
  10803. (define ((uncover-get!-exp set!-vars) e)
  10804. (match e
  10805. [(Var x)
  10806. (if (set-member? set!-vars x)
  10807. (GetBang x)
  10808. (Var x))]
  10809. ...))
  10810. \end{lstlisting}
  10811. \end{minipage}
  10812. \end{center}
  10813. To wrap things up, define the \code{uncover-get!} function for
  10814. processing a whole program, using \code{collect-set!} to obtain the
  10815. set of mutable variables and then \code{uncover-get!-exp} to replace
  10816. their occurrences with \code{GetBang}.
  10817. \fi}
  10818. \section{Remove Complex Operands}
  10819. \label{sec:rco-loop}
  10820. {\if\edition\racketEd
  10821. %
  10822. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10823. \code{while} are all complex expressions. The subexpressions of
  10824. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10825. %
  10826. \fi}
  10827. {\if\edition\pythonEd\pythonColor
  10828. %
  10829. The change needed for this pass is to add a case for the \code{while}
  10830. statement. The condition of a loop is allowed to be a complex
  10831. expression, just like the condition of the \code{if} statement.
  10832. %
  10833. \fi}
  10834. %
  10835. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10836. \LangLoopANF{} of this pass.
  10837. \newcommand{\LwhileMonadASTRacket}{
  10838. \begin{array}{rcl}
  10839. \Atm &::=& \VOID{} \\
  10840. \Exp &::=& \GETBANG{\Var}
  10841. \MID \SETBANG{\Var}{\Exp}
  10842. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10843. &\MID& \WHILE{\Exp}{\Exp}
  10844. \end{array}
  10845. }
  10846. \newcommand{\LwhileMonadASTPython}{
  10847. \begin{array}{rcl}
  10848. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10849. \end{array}
  10850. }
  10851. \begin{figure}[tp]
  10852. \centering
  10853. \begin{tcolorbox}[colback=white]
  10854. \small
  10855. {\if\edition\racketEd
  10856. \[
  10857. \begin{array}{l}
  10858. \gray{\LvarMonadASTRacket} \\ \hline
  10859. \gray{\LifMonadASTRacket} \\ \hline
  10860. \LwhileMonadASTRacket \\
  10861. \begin{array}{rcl}
  10862. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10863. \end{array}
  10864. \end{array}
  10865. \]
  10866. \fi}
  10867. {\if\edition\pythonEd\pythonColor
  10868. \[
  10869. \begin{array}{l}
  10870. \gray{\LvarMonadASTPython} \\ \hline
  10871. \gray{\LifMonadASTPython} \\ \hline
  10872. \LwhileMonadASTPython \\
  10873. \begin{array}{rcl}
  10874. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10875. \end{array}
  10876. \end{array}
  10877. \]
  10878. \fi}
  10879. \end{tcolorbox}
  10880. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10881. \label{fig:Lwhile-anf-syntax}
  10882. \end{figure}
  10883. {\if\edition\racketEd
  10884. %
  10885. As usual, when a complex expression appears in a grammar position that
  10886. needs to be atomic, such as the argument of a primitive operator, we
  10887. must introduce a temporary variable and bind it to the complex
  10888. expression. This approach applies, unchanged, to handle the new
  10889. language forms. For example, in the following code there are two
  10890. \code{begin} expressions appearing as arguments to the \code{+}
  10891. operator. The output of \code{rco\_exp} is then shown, in which the
  10892. \code{begin} expressions have been bound to temporary
  10893. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10894. allowed to have arbitrary expressions in their right-hand side
  10895. expression, so it is fine to place \code{begin} there.
  10896. %
  10897. \begin{center}
  10898. \begin{tabular}{lcl}
  10899. \begin{minipage}{0.4\textwidth}
  10900. \begin{lstlisting}
  10901. (let ([x2 10])
  10902. (let ([y3 0])
  10903. (+ (+ (begin
  10904. (set! y3 (read))
  10905. (get! x2))
  10906. (begin
  10907. (set! x2 (read))
  10908. (get! y3)))
  10909. (get! x2))))
  10910. \end{lstlisting}
  10911. \end{minipage}
  10912. &
  10913. $\Rightarrow$
  10914. &
  10915. \begin{minipage}{0.4\textwidth}
  10916. \begin{lstlisting}
  10917. (let ([x2 10])
  10918. (let ([y3 0])
  10919. (let ([tmp4 (begin
  10920. (set! y3 (read))
  10921. x2)])
  10922. (let ([tmp5 (begin
  10923. (set! x2 (read))
  10924. y3)])
  10925. (let ([tmp6 (+ tmp4 tmp5)])
  10926. (let ([tmp7 x2])
  10927. (+ tmp6 tmp7)))))))
  10928. \end{lstlisting}
  10929. \end{minipage}
  10930. \end{tabular}
  10931. \end{center}
  10932. \fi}
  10933. \section{Explicate Control \racket{and \LangCLoop{}}}
  10934. \label{sec:explicate-loop}
  10935. \newcommand{\CloopASTRacket}{
  10936. \begin{array}{lcl}
  10937. \Atm &::=& \VOID \\
  10938. \Stmt &::=& \READ{}
  10939. \end{array}
  10940. }
  10941. {\if\edition\racketEd
  10942. Recall that in the \code{explicate\_control} pass we define one helper
  10943. function for each kind of position in the program. For the \LangVar{}
  10944. language of integers and variables, we needed assignment and tail
  10945. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10946. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10947. another kind of position: effect position. Except for the last
  10948. subexpression, the subexpressions inside a \code{begin} are evaluated
  10949. only for their effect. Their result values are discarded. We can
  10950. generate better code by taking this fact into account.
  10951. The output language of \code{explicate\_control} is \LangCLoop{}
  10952. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10953. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10954. and that \code{read} may appear as a statement. The most significant
  10955. difference between the programs generated by \code{explicate\_control}
  10956. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10957. chapter is that the control-flow graphs of the latter may contain
  10958. cycles.
  10959. \begin{figure}[tp]
  10960. \begin{tcolorbox}[colback=white]
  10961. \small
  10962. \[
  10963. \begin{array}{l}
  10964. \gray{\CvarASTRacket} \\ \hline
  10965. \gray{\CifASTRacket} \\ \hline
  10966. \CloopASTRacket \\
  10967. \begin{array}{lcl}
  10968. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10969. \end{array}
  10970. \end{array}
  10971. \]
  10972. \end{tcolorbox}
  10973. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10974. \label{fig:c7-syntax}
  10975. \end{figure}
  10976. The new auxiliary function \code{explicate\_effect} takes an
  10977. expression (in an effect position) and the code for its
  10978. continuation. The function returns a $\Tail$ that includes the
  10979. generated code for the input expression followed by the
  10980. continuation. If the expression is obviously pure, that is, never
  10981. causes side effects, then the expression can be removed, so the result
  10982. is just the continuation.
  10983. %
  10984. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10985. interesting; the generated code is depicted in the following diagram:
  10986. \begin{center}
  10987. \begin{minipage}{0.3\textwidth}
  10988. \xymatrix{
  10989. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10990. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10991. & *+[F]{\txt{\itm{cont}}} \\
  10992. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10993. }
  10994. \end{minipage}
  10995. \end{center}
  10996. We start by creating a fresh label $\itm{loop}$ for the top of the
  10997. loop. Next, recursively process the \itm{body} (in effect position)
  10998. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10999. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11000. \itm{body'} as the \emph{then} branch and the continuation block as the
  11001. \emph{else} branch. The result should be added to the dictionary of
  11002. \code{basic-blocks} with the label \itm{loop}. The result for the
  11003. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11004. The auxiliary functions for tail, assignment, and predicate positions
  11005. need to be updated. The three new language forms, \code{while},
  11006. \code{set!}, and \code{begin}, can appear in assignment and tail
  11007. positions. Only \code{begin} may appear in predicate positions; the
  11008. other two have result type \code{Void}.
  11009. \fi}
  11010. %
  11011. {\if\edition\pythonEd\pythonColor
  11012. %
  11013. The output of this pass is the language \LangCIf{}. No new language
  11014. features are needed in the output, because a \code{while} loop can be
  11015. expressed in terms of \code{goto} and \code{if} statements, which are
  11016. already in \LangCIf{}.
  11017. %
  11018. Add a case for the \code{while} statement to the
  11019. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11020. the condition expression.
  11021. %
  11022. \fi}
  11023. {\if\edition\racketEd
  11024. \section{Select Instructions}
  11025. \label{sec:select-instructions-loop}
  11026. \index{subject}{select instructions}
  11027. Only two small additions are needed in the \code{select\_instructions}
  11028. pass to handle the changes to \LangCLoop{}. First, to handle the
  11029. addition of \VOID{} we simply translate it to \code{0}. Second,
  11030. \code{read} may appear as a stand-alone statement instead of
  11031. appearing only on the right-hand side of an assignment statement. The code
  11032. generation is nearly identical to the one for assignment; just leave
  11033. off the instruction for moving the result into the left-hand side.
  11034. \fi}
  11035. \section{Register Allocation}
  11036. \label{sec:register-allocation-loop}
  11037. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11038. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11039. which complicates the liveness analysis needed for register
  11040. allocation.
  11041. %
  11042. We recommend using the generic \code{analyze\_dataflow} function that
  11043. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11044. perform liveness analysis, replacing the code in
  11045. \code{uncover\_live} that processed the basic blocks in topological
  11046. order (section~\ref{sec:liveness-analysis-Lif}).
  11047. The \code{analyze\_dataflow} function has the following four parameters.
  11048. \begin{enumerate}
  11049. \item The first parameter \code{G} should be passed the transpose
  11050. of the control-flow graph.
  11051. \item The second parameter \code{transfer} should be passed a function
  11052. that applies liveness analysis to a basic block. It takes two
  11053. parameters: the label for the block to analyze and the live-after
  11054. set for that block. The transfer function should return the
  11055. live-before set for the block.
  11056. %
  11057. \racket{Also, as a side effect, it should update the block's
  11058. $\itm{info}$ with the liveness information for each instruction.}
  11059. %
  11060. \python{Also, as a side effect, it should update the live-before and
  11061. live-after sets for each instruction.}
  11062. %
  11063. To implement the \code{transfer} function, you should be able to
  11064. reuse the code you already have for analyzing basic blocks.
  11065. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11066. \code{bottom} and \code{join} for the lattice of abstract states,
  11067. that is, sets of locations. For liveness analysis, the bottom of the
  11068. lattice is the empty set, and the join operator is set union.
  11069. \end{enumerate}
  11070. \begin{figure}[tp]
  11071. \begin{tcolorbox}[colback=white]
  11072. {\if\edition\racketEd
  11073. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11074. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11075. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11076. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11077. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11078. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11079. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11080. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11081. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11082. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11083. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11084. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11085. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11086. \path[->,bend left=15] (Lfun) edge [above] node
  11087. {\ttfamily\footnotesize shrink} (Lfun-2);
  11088. \path[->,bend left=15] (Lfun-2) edge [above] node
  11089. {\ttfamily\footnotesize uniquify} (F1-4);
  11090. \path[->,bend left=15] (F1-4) edge [above] node
  11091. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11092. \path[->,bend left=15] (F1-5) edge [left] node
  11093. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11094. \path[->,bend left=10] (F1-6) edge [above] node
  11095. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11096. \path[->,bend left=15] (C3-2) edge [right] node
  11097. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11098. \path[->,bend right=15] (x86-2) edge [right] node
  11099. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11100. \path[->,bend right=15] (x86-2-1) edge [below] node
  11101. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11102. \path[->,bend right=15] (x86-2-2) edge [right] node
  11103. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11104. \path[->,bend left=15] (x86-3) edge [above] node
  11105. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11106. \path[->,bend left=15] (x86-4) edge [right] node
  11107. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11108. \end{tikzpicture}
  11109. \fi}
  11110. {\if\edition\pythonEd\pythonColor
  11111. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11112. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11113. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11114. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11115. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11116. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11117. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11118. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11119. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11120. \path[->,bend left=15] (Lfun) edge [above] node
  11121. {\ttfamily\footnotesize shrink} (Lfun-2);
  11122. \path[->,bend left=15] (Lfun-2) edge [above] node
  11123. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11124. \path[->,bend left=10] (F1-6) edge [right] node
  11125. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11126. \path[->,bend right=15] (C3-2) edge [right] node
  11127. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11128. \path[->,bend right=15] (x86-2) edge [below] node
  11129. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11130. \path[->,bend left=15] (x86-3) edge [above] node
  11131. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11132. \path[->,bend right=15] (x86-4) edge [below] node
  11133. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11134. \end{tikzpicture}
  11135. \fi}
  11136. \end{tcolorbox}
  11137. \caption{Diagram of the passes for \LangLoop{}.}
  11138. \label{fig:Lwhile-passes}
  11139. \end{figure}
  11140. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11141. for the compilation of \LangLoop{}.
  11142. % Further Reading: dataflow analysis
  11143. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11144. \chapter{Tuples and Garbage Collection}
  11145. \label{ch:Lvec}
  11146. \index{subject}{tuple}
  11147. \index{subject}{vector}
  11148. \setcounter{footnote}{0}
  11149. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11150. %% all the IR grammars are spelled out! \\ --Jeremy}
  11151. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11152. %% the root stack. \\ --Jeremy}
  11153. In this chapter we study the implementation of tuples\racket{, called
  11154. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11155. in which each element may have a different type.
  11156. %
  11157. This language feature is the first to use the computer's
  11158. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11159. indefinite; that is, a tuple lives forever from the programmer's
  11160. viewpoint. Of course, from an implementer's viewpoint, it is important
  11161. to reclaim the space associated with a tuple when it is no longer
  11162. needed, which is why we also study \emph{garbage collection}
  11163. \index{subject}{garbage collection} techniques in this chapter.
  11164. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11165. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11166. language (chapter~\ref{ch:Lwhile}) with tuples.
  11167. %
  11168. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11169. copying live tuples back and forth between two halves of the heap. The
  11170. garbage collector requires coordination with the compiler so that it
  11171. can find all the live tuples.
  11172. %
  11173. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11174. discuss the necessary changes and additions to the compiler passes,
  11175. including a new compiler pass named \code{expose\_allocation}.
  11176. \section{The \LangVec{} Language}
  11177. \label{sec:r3}
  11178. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11179. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11180. the definition of the abstract syntax.
  11181. %
  11182. \racket{The \LangVec{} language includes the forms \code{vector} for
  11183. creating a tuple, \code{vector-ref} for reading an element of a
  11184. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11185. \code{vector-length} for obtaining the number of elements of a
  11186. tuple.}
  11187. %
  11188. \python{The \LangVec{} language adds (1) tuple creation via a
  11189. comma-separated list of expressions; (2) accessing an element of a
  11190. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11191. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11192. comparison operator; and (4) obtaining the number of elements (the
  11193. length) of a tuple. In this chapter, we restrict access indices to
  11194. constant integers.}
  11195. %
  11196. The following program shows an example of the use of tuples. It creates a tuple
  11197. \code{t} containing the elements \code{40},
  11198. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11199. contains just \code{2}. The element at index $1$ of \code{t} is
  11200. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11201. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11202. to which we add \code{2}, the element at index $0$ of the tuple.
  11203. The result of the program is \code{42}.
  11204. %
  11205. {\if\edition\racketEd
  11206. \begin{lstlisting}
  11207. (let ([t (vector 40 #t (vector 2))])
  11208. (if (vector-ref t 1)
  11209. (+ (vector-ref t 0)
  11210. (vector-ref (vector-ref t 2) 0))
  11211. 44))
  11212. \end{lstlisting}
  11213. \fi}
  11214. {\if\edition\pythonEd\pythonColor
  11215. \begin{lstlisting}
  11216. t = 40, True, (2,)
  11217. print(t[0] + t[2][0] if t[1] else 44)
  11218. \end{lstlisting}
  11219. \fi}
  11220. \newcommand{\LtupGrammarRacket}{
  11221. \begin{array}{lcl}
  11222. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11223. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11224. \MID \LP\key{vector-length}\;\Exp\RP \\
  11225. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11226. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11227. \end{array}
  11228. }
  11229. \newcommand{\LtupASTRacket}{
  11230. \begin{array}{lcl}
  11231. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11232. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11233. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11234. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11235. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11236. \end{array}
  11237. }
  11238. \newcommand{\LtupGrammarPython}{
  11239. \begin{array}{rcl}
  11240. \itm{cmp} &::= & \key{is} \\
  11241. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11242. \end{array}
  11243. }
  11244. \newcommand{\LtupASTPython}{
  11245. \begin{array}{lcl}
  11246. \itm{cmp} &::= & \code{Is()} \\
  11247. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11248. &\MID& \LEN{\Exp}
  11249. \end{array}
  11250. }
  11251. \begin{figure}[tbp]
  11252. \centering
  11253. \begin{tcolorbox}[colback=white]
  11254. \small
  11255. {\if\edition\racketEd
  11256. \[
  11257. \begin{array}{l}
  11258. \gray{\LintGrammarRacket{}} \\ \hline
  11259. \gray{\LvarGrammarRacket{}} \\ \hline
  11260. \gray{\LifGrammarRacket{}} \\ \hline
  11261. \gray{\LwhileGrammarRacket} \\ \hline
  11262. \LtupGrammarRacket \\
  11263. \begin{array}{lcl}
  11264. \LangVecM{} &::=& \Exp
  11265. \end{array}
  11266. \end{array}
  11267. \]
  11268. \fi}
  11269. {\if\edition\pythonEd\pythonColor
  11270. \[
  11271. \begin{array}{l}
  11272. \gray{\LintGrammarPython{}} \\ \hline
  11273. \gray{\LvarGrammarPython{}} \\ \hline
  11274. \gray{\LifGrammarPython{}} \\ \hline
  11275. \gray{\LwhileGrammarPython} \\ \hline
  11276. \LtupGrammarPython \\
  11277. \begin{array}{rcl}
  11278. \LangVecM{} &::=& \Stmt^{*}
  11279. \end{array}
  11280. \end{array}
  11281. \]
  11282. \fi}
  11283. \end{tcolorbox}
  11284. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11285. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11286. \label{fig:Lvec-concrete-syntax}
  11287. \end{figure}
  11288. \begin{figure}[tp]
  11289. \centering
  11290. \begin{tcolorbox}[colback=white]
  11291. \small
  11292. {\if\edition\racketEd
  11293. \[
  11294. \begin{array}{l}
  11295. \gray{\LintOpAST} \\ \hline
  11296. \gray{\LvarASTRacket{}} \\ \hline
  11297. \gray{\LifASTRacket{}} \\ \hline
  11298. \gray{\LwhileASTRacket{}} \\ \hline
  11299. \LtupASTRacket{} \\
  11300. \begin{array}{lcl}
  11301. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11302. \end{array}
  11303. \end{array}
  11304. \]
  11305. \fi}
  11306. {\if\edition\pythonEd\pythonColor
  11307. \[
  11308. \begin{array}{l}
  11309. \gray{\LintASTPython} \\ \hline
  11310. \gray{\LvarASTPython} \\ \hline
  11311. \gray{\LifASTPython} \\ \hline
  11312. \gray{\LwhileASTPython} \\ \hline
  11313. \LtupASTPython \\
  11314. \begin{array}{lcl}
  11315. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11316. \end{array}
  11317. \end{array}
  11318. \]
  11319. \fi}
  11320. \end{tcolorbox}
  11321. \caption{The abstract syntax of \LangVec{}.}
  11322. \label{fig:Lvec-syntax}
  11323. \end{figure}
  11324. Tuples raise several interesting new issues. First, variable binding
  11325. performs a shallow copy in dealing with tuples, which means that
  11326. different variables can refer to the same tuple; that is, two
  11327. variables can be \emph{aliases}\index{subject}{alias} for the same
  11328. entity. Consider the following example, in which \code{t1} and
  11329. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11330. different tuple value with equal elements. The result of the
  11331. program is \code{42}.
  11332. \begin{center}
  11333. \begin{minipage}{0.96\textwidth}
  11334. {\if\edition\racketEd
  11335. \begin{lstlisting}
  11336. (let ([t1 (vector 3 7)])
  11337. (let ([t2 t1])
  11338. (let ([t3 (vector 3 7)])
  11339. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11340. 42
  11341. 0))))
  11342. \end{lstlisting}
  11343. \fi}
  11344. {\if\edition\pythonEd\pythonColor
  11345. \begin{lstlisting}
  11346. t1 = 3, 7
  11347. t2 = t1
  11348. t3 = 3, 7
  11349. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11350. \end{lstlisting}
  11351. \fi}
  11352. \end{minipage}
  11353. \end{center}
  11354. {\if\edition\racketEd
  11355. Whether two variables are aliased or not affects what happens
  11356. when the underlying tuple is mutated\index{subject}{mutation}.
  11357. Consider the following example in which \code{t1} and \code{t2}
  11358. again refer to the same tuple value.
  11359. \begin{center}
  11360. \begin{minipage}{0.96\textwidth}
  11361. \begin{lstlisting}
  11362. (let ([t1 (vector 3 7)])
  11363. (let ([t2 t1])
  11364. (let ([_ (vector-set! t2 0 42)])
  11365. (vector-ref t1 0))))
  11366. \end{lstlisting}
  11367. \end{minipage}
  11368. \end{center}
  11369. The mutation through \code{t2} is visible in referencing the tuple
  11370. from \code{t1}, so the result of this program is \code{42}.
  11371. \fi}
  11372. The next issue concerns the lifetime of tuples. When does a tuple's
  11373. lifetime end? Notice that \LangVec{} does not include an operation
  11374. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11375. to any notion of static scoping.
  11376. %
  11377. {\if\edition\racketEd
  11378. %
  11379. For example, the following program returns \code{42} even though the
  11380. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11381. that reads from the vector to which it was bound.
  11382. \begin{center}
  11383. \begin{minipage}{0.96\textwidth}
  11384. \begin{lstlisting}
  11385. (let ([v (vector (vector 44))])
  11386. (let ([x (let ([w (vector 42)])
  11387. (let ([_ (vector-set! v 0 w)])
  11388. 0))])
  11389. (+ x (vector-ref (vector-ref v 0) 0))))
  11390. \end{lstlisting}
  11391. \end{minipage}
  11392. \end{center}
  11393. \fi}
  11394. %
  11395. {\if\edition\pythonEd\pythonColor
  11396. %
  11397. For example, the following program returns \code{42} even though the
  11398. variable \code{x} goes out of scope when the function returns, prior
  11399. to reading the tuple element at index $0$. (We study the compilation
  11400. of functions in chapter~\ref{ch:Lfun}.)
  11401. %
  11402. \begin{center}
  11403. \begin{minipage}{0.96\textwidth}
  11404. \begin{lstlisting}
  11405. def f():
  11406. x = 42, 43
  11407. return x
  11408. t = f()
  11409. print(t[0])
  11410. \end{lstlisting}
  11411. \end{minipage}
  11412. \end{center}
  11413. \fi}
  11414. %
  11415. From the perspective of programmer-observable behavior, tuples live
  11416. forever. However, if they really lived forever then many long-running
  11417. programs would run out of memory. To solve this problem, the
  11418. language's runtime system performs automatic garbage collection.
  11419. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11420. \LangVec{} language.
  11421. %
  11422. \racket{We define the \code{vector}, \code{vector-ref},
  11423. \code{vector-set!}, and \code{vector-length} operations for
  11424. \LangVec{} in terms of the corresponding operations in Racket. One
  11425. subtle point is that the \code{vector-set!} operation returns the
  11426. \code{\#<void>} value.}
  11427. %
  11428. \python{We represent tuples with Python lists in the interpreter
  11429. because we need to write to them
  11430. (section~\ref{sec:expose-allocation}). (Python tuples are
  11431. immutable.) We define element access, the \code{is} operator, and
  11432. the \code{len} operator for \LangVec{} in terms of the corresponding
  11433. operations in Python.}
  11434. \begin{figure}[tbp]
  11435. \begin{tcolorbox}[colback=white]
  11436. {\if\edition\racketEd
  11437. \begin{lstlisting}
  11438. (define interp-Lvec-class
  11439. (class interp-Lwhile-class
  11440. (super-new)
  11441. (define/override (interp-op op)
  11442. (match op
  11443. ['eq? (lambda (v1 v2)
  11444. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11445. (and (boolean? v1) (boolean? v2))
  11446. (and (vector? v1) (vector? v2))
  11447. (and (void? v1) (void? v2)))
  11448. (eq? v1 v2)]))]
  11449. ['vector vector]
  11450. ['vector-length vector-length]
  11451. ['vector-ref vector-ref]
  11452. ['vector-set! vector-set!]
  11453. [else (super interp-op op)]
  11454. ))
  11455. (define/override ((interp-exp env) e)
  11456. (match e
  11457. [(HasType e t) ((interp-exp env) e)]
  11458. [else ((super interp-exp env) e)]
  11459. ))
  11460. ))
  11461. (define (interp-Lvec p)
  11462. (send (new interp-Lvec-class) interp-program p))
  11463. \end{lstlisting}
  11464. \fi}
  11465. %
  11466. {\if\edition\pythonEd\pythonColor
  11467. \begin{lstlisting}
  11468. class InterpLtup(InterpLwhile):
  11469. def interp_cmp(self, cmp):
  11470. match cmp:
  11471. case Is():
  11472. return lambda x, y: x is y
  11473. case _:
  11474. return super().interp_cmp(cmp)
  11475. def interp_exp(self, e, env):
  11476. match e:
  11477. case Tuple(es, Load()):
  11478. return tuple([self.interp_exp(e, env) for e in es])
  11479. case Subscript(tup, index, Load()):
  11480. t = self.interp_exp(tup, env)
  11481. n = self.interp_exp(index, env)
  11482. return t[n]
  11483. case _:
  11484. return super().interp_exp(e, env)
  11485. \end{lstlisting}
  11486. \fi}
  11487. \end{tcolorbox}
  11488. \caption{Interpreter for the \LangVec{} language.}
  11489. \label{fig:interp-Lvec}
  11490. \end{figure}
  11491. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11492. \LangVec{}.
  11493. %
  11494. The type of a tuple is a
  11495. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11496. type for each of its elements.
  11497. %
  11498. \racket{To create the s-expression for the \code{Vector} type, we use the
  11499. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11500. operator} \code{,@} to insert the list \code{t*} without its usual
  11501. start and end parentheses. \index{subject}{unquote-splicing}}
  11502. %
  11503. The type of accessing the ith element of a tuple is the ith element
  11504. type of the tuple's type, if there is one. If not, an error is
  11505. signaled. Note that the index \code{i} is required to be a constant
  11506. integer (and not, for example, a call to
  11507. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11508. can determine the element's type given the tuple type.
  11509. %
  11510. \racket{
  11511. Regarding writing an element to a tuple, the element's type must
  11512. be equal to the ith element type of the tuple's type.
  11513. The result type is \code{Void}.}
  11514. %% When allocating a tuple,
  11515. %% we need to know which elements of the tuple are themselves tuples for
  11516. %% the purposes of garbage collection. We can obtain this information
  11517. %% during type checking. The type checker shown in
  11518. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11519. %% expression; it also
  11520. %% %
  11521. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11522. %% where $T$ is the tuple's type.
  11523. %
  11524. %records the type of each tuple expression in a new field named \code{has\_type}.
  11525. \begin{figure}[tp]
  11526. \begin{tcolorbox}[colback=white]
  11527. {\if\edition\racketEd
  11528. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11529. (define type-check-Lvec-class
  11530. (class type-check-Lif-class
  11531. (super-new)
  11532. (inherit check-type-equal?)
  11533. (define/override (type-check-exp env)
  11534. (lambda (e)
  11535. (define recur (type-check-exp env))
  11536. (match e
  11537. [(Prim 'vector es)
  11538. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11539. (define t `(Vector ,@t*))
  11540. (values (Prim 'vector e*) t)]
  11541. [(Prim 'vector-ref (list e1 (Int i)))
  11542. (define-values (e1^ t) (recur e1))
  11543. (match t
  11544. [`(Vector ,ts ...)
  11545. (unless (and (0 . <= . i) (i . < . (length ts)))
  11546. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11547. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11548. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11549. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11550. (define-values (e-vec t-vec) (recur e1))
  11551. (define-values (e-elt^ t-elt) (recur elt))
  11552. (match t-vec
  11553. [`(Vector ,ts ...)
  11554. (unless (and (0 . <= . i) (i . < . (length ts)))
  11555. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11556. (check-type-equal? (list-ref ts i) t-elt e)
  11557. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11558. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11559. [(Prim 'vector-length (list e))
  11560. (define-values (e^ t) (recur e))
  11561. (match t
  11562. [`(Vector ,ts ...)
  11563. (values (Prim 'vector-length (list e^)) 'Integer)]
  11564. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11565. [(Prim 'eq? (list arg1 arg2))
  11566. (define-values (e1 t1) (recur arg1))
  11567. (define-values (e2 t2) (recur arg2))
  11568. (match* (t1 t2)
  11569. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11570. [(other wise) (check-type-equal? t1 t2 e)])
  11571. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11572. [else ((super type-check-exp env) e)]
  11573. )))
  11574. ))
  11575. (define (type-check-Lvec p)
  11576. (send (new type-check-Lvec-class) type-check-program p))
  11577. \end{lstlisting}
  11578. \fi}
  11579. {\if\edition\pythonEd\pythonColor
  11580. \begin{lstlisting}
  11581. class TypeCheckLtup(TypeCheckLwhile):
  11582. def type_check_exp(self, e, env):
  11583. match e:
  11584. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11585. l = self.type_check_exp(left, env)
  11586. r = self.type_check_exp(right, env)
  11587. check_type_equal(l, r, e)
  11588. return bool
  11589. case Tuple(es, Load()):
  11590. ts = [self.type_check_exp(e, env) for e in es]
  11591. e.has_type = TupleType(ts)
  11592. return e.has_type
  11593. case Subscript(tup, Constant(i), Load()):
  11594. tup_ty = self.type_check_exp(tup, env)
  11595. i_ty = self.type_check_exp(Constant(i), env)
  11596. check_type_equal(i_ty, int, i)
  11597. match tup_ty:
  11598. case TupleType(ts):
  11599. return ts[i]
  11600. case _:
  11601. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11602. case _:
  11603. return super().type_check_exp(e, env)
  11604. \end{lstlisting}
  11605. \fi}
  11606. \end{tcolorbox}
  11607. \caption{Type checker for the \LangVec{} language.}
  11608. \label{fig:type-check-Lvec}
  11609. \end{figure}
  11610. \section{Garbage Collection}
  11611. \label{sec:GC}
  11612. Garbage collection is a runtime technique for reclaiming space on the
  11613. heap that will not be used in the future of the running program. We
  11614. use the term \emph{object}\index{subject}{object} to refer to any
  11615. value that is stored in the heap, which for now includes only
  11616. tuples.%
  11617. %
  11618. \footnote{The term \emph{object} as it is used in the context of
  11619. object-oriented programming has a more specific meaning than the
  11620. way in which we use the term here.}
  11621. %
  11622. Unfortunately, it is impossible to know precisely which objects will
  11623. be accessed in the future and which will not. Instead, garbage
  11624. collectors overapproximate the set of objects that will be accessed by
  11625. identifying which objects can possibly be accessed. The running
  11626. program can directly access objects that are in registers and on the
  11627. procedure call stack. It can also transitively access the elements of
  11628. tuples, starting with a tuple whose address is in a register or on the
  11629. procedure call stack. We define the \emph{root
  11630. set}\index{subject}{root set} to be all the tuple addresses that are
  11631. in registers or on the procedure call stack. We define the \emph{live
  11632. objects}\index{subject}{live objects} to be the objects that are
  11633. reachable from the root set. Garbage collectors reclaim the space that
  11634. is allocated to objects that are no longer live. \index{subject}{allocate}
  11635. That means that some objects may not get reclaimed as soon as they could be,
  11636. but at least
  11637. garbage collectors do not reclaim the space dedicated to objects that
  11638. will be accessed in the future! The programmer can influence which
  11639. objects get reclaimed by causing them to become unreachable.
  11640. So the goal of the garbage collector is twofold:
  11641. \begin{enumerate}
  11642. \item to preserve all the live objects, and
  11643. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11644. \end{enumerate}
  11645. \subsection{Two-Space Copying Collector}
  11646. Here we study a relatively simple algorithm for garbage collection
  11647. that is the basis of many state-of-the-art garbage
  11648. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11649. particular, we describe a two-space copying
  11650. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11651. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11652. collector} \index{subject}{two-space copying collector}
  11653. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11654. what happens in a two-space collector, showing two time steps, prior
  11655. to garbage collection (on the top) and after garbage collection (on
  11656. the bottom). In a two-space collector, the heap is divided into two
  11657. parts named the FromSpace\index{subject}{FromSpace} and the
  11658. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11659. FromSpace until there is not enough room for the next allocation
  11660. request. At that point, the garbage collector goes to work to make
  11661. room for the next allocation.
  11662. A copying collector makes more room by copying all the live objects
  11663. from the FromSpace into the ToSpace and then performs a sleight of
  11664. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11665. as the new ToSpace. In the example shown in
  11666. figure~\ref{fig:copying-collector}, the root set consists of three
  11667. pointers, one in a register and two on the stack. All the live
  11668. objects have been copied to the ToSpace (the right-hand side of
  11669. figure~\ref{fig:copying-collector}) in a way that preserves the
  11670. pointer relationships. For example, the pointer in the register still
  11671. points to a tuple that in turn points to two other tuples. There are
  11672. four tuples that are not reachable from the root set and therefore do
  11673. not get copied into the ToSpace.
  11674. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11675. created by a well-typed program in \LangVec{} because it contains a
  11676. cycle. However, creating cycles will be possible once we get to
  11677. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11678. to deal with cycles to begin with, so we will not need to revisit this
  11679. issue.
  11680. \begin{figure}[tbp]
  11681. \centering
  11682. \begin{tcolorbox}[colback=white]
  11683. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11684. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11685. \\[5ex]
  11686. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11687. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11688. \end{tcolorbox}
  11689. \caption{A copying collector in action.}
  11690. \label{fig:copying-collector}
  11691. \end{figure}
  11692. \subsection{Graph Copying via Cheney's Algorithm}
  11693. \label{sec:cheney}
  11694. \index{subject}{Cheney's algorithm}
  11695. Let us take a closer look at the copying of the live objects. The
  11696. allocated\index{subject}{allocate} objects and pointers can be viewed
  11697. as a graph, and we need to copy the part of the graph that is
  11698. reachable from the root set. To make sure that we copy all the
  11699. reachable vertices in the graph, we need an exhaustive graph traversal
  11700. algorithm, such as depth-first search or breadth-first
  11701. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11702. take into account the possibility of cycles by marking which vertices
  11703. have already been visited, so to ensure termination of the
  11704. algorithm. These search algorithms also use a data structure such as a
  11705. stack or queue as a to-do list to keep track of the vertices that need
  11706. to be visited. We use breadth-first search and a trick due to
  11707. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11708. copying tuples into the ToSpace.
  11709. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11710. copy progresses. The queue is represented by a chunk of contiguous
  11711. memory at the beginning of the ToSpace, using two pointers to track
  11712. the front and the back of the queue, called the \emph{free pointer}
  11713. and the \emph{scan pointer}, respectively. The algorithm starts by
  11714. copying all tuples that are immediately reachable from the root set
  11715. into the ToSpace to form the initial queue. When we copy a tuple, we
  11716. mark the old tuple to indicate that it has been visited. We discuss
  11717. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11718. that any pointers inside the copied tuples in the queue still point
  11719. back to the FromSpace. Once the initial queue has been created, the
  11720. algorithm enters a loop in which it repeatedly processes the tuple at
  11721. the front of the queue and pops it off the queue. To process a tuple,
  11722. the algorithm copies all the objects that are directly reachable from it
  11723. to the ToSpace, placing them at the back of the queue. The algorithm
  11724. then updates the pointers in the popped tuple so that they point to the
  11725. newly copied objects.
  11726. \begin{figure}[tbp]
  11727. \centering
  11728. \begin{tcolorbox}[colback=white]
  11729. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11730. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11731. \end{tcolorbox}
  11732. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11733. \label{fig:cheney}
  11734. \end{figure}
  11735. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11736. tuple whose second element is $42$ to the back of the queue. The other
  11737. pointer goes to a tuple that has already been copied, so we do not
  11738. need to copy it again, but we do need to update the pointer to the new
  11739. location. This can be accomplished by storing a \emph{forwarding
  11740. pointer}\index{subject}{forwarding pointer} to the new location in the
  11741. old tuple, when we initially copied the tuple into the
  11742. ToSpace. This completes one step of the algorithm. The algorithm
  11743. continues in this way until the queue is empty; that is, when the scan
  11744. pointer catches up with the free pointer.
  11745. \subsection{Data Representation}
  11746. \label{sec:data-rep-gc}
  11747. The garbage collector places some requirements on the data
  11748. representations used by our compiler. First, the garbage collector
  11749. needs to distinguish between pointers and other kinds of data such as
  11750. integers. The following are three ways to accomplish this:
  11751. \begin{enumerate}
  11752. \item Attach a tag to each object that identifies what type of
  11753. object it is~\citep{McCarthy:1960dz}.
  11754. \item Store different types of objects in different
  11755. regions~\citep{Steele:1977ab}.
  11756. \item Use type information from the program to either (a) generate
  11757. type-specific code for collecting, or (b) generate tables that
  11758. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11759. \end{enumerate}
  11760. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11761. need to tag objects in any case, so option 1 is a natural choice for those
  11762. languages. However, \LangVec{} is a statically typed language, so it
  11763. would be unfortunate to require tags on every object, especially small
  11764. and pervasive objects like integers and Booleans. Option 3 is the
  11765. best-performing choice for statically typed languages, but it comes with
  11766. a relatively high implementation complexity. To keep this chapter
  11767. within a reasonable scope of complexity, we recommend a combination of options
  11768. 1 and 2, using separate strategies for the stack and the heap.
  11769. Regarding the stack, we recommend using a separate stack for pointers,
  11770. which we call the \emph{root stack}\index{subject}{root stack}
  11771. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11772. That is, when a local variable needs to be spilled and is of type
  11773. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11774. root stack instead of putting it on the procedure call
  11775. stack. Furthermore, we always spill tuple-typed variables if they are
  11776. live during a call to the collector, thereby ensuring that no pointers
  11777. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11778. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11779. contrasts it with the data layout using a root stack. The root stack
  11780. contains the two pointers from the regular stack and also the pointer
  11781. in the second register.
  11782. \begin{figure}[tbp]
  11783. \centering
  11784. \begin{tcolorbox}[colback=white]
  11785. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11786. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11787. \end{tcolorbox}
  11788. \caption{Maintaining a root stack to facilitate garbage collection.}
  11789. \label{fig:shadow-stack}
  11790. \end{figure}
  11791. The problem of distinguishing between pointers and other kinds of data
  11792. also arises inside each tuple on the heap. We solve this problem by
  11793. attaching a tag, an extra 64 bits, to each
  11794. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11795. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11796. Note that we have drawn the bits in a big-endian way, from right to left,
  11797. with bit location 0 (the least significant bit) on the far right,
  11798. which corresponds to the direction of the x86 shifting instructions
  11799. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11800. is dedicated to specifying which elements of the tuple are pointers,
  11801. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11802. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11803. data. The pointer mask starts at bit location 7. We limit tuples to a
  11804. maximum size of fifty elements, so we need 50 bits for the pointer
  11805. mask.%
  11806. %
  11807. \footnote{A production-quality compiler would handle
  11808. arbitrarily sized tuples and use a more complex approach.}
  11809. %
  11810. The tag also contains two other pieces of information. The length of
  11811. the tuple (number of elements) is stored in bits at locations 1 through
  11812. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11813. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11814. has not yet been copied. If the bit has value 0, then the entire tag
  11815. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11816. zero in any case, because our tuples are 8-byte aligned.)
  11817. \begin{figure}[tbp]
  11818. \centering
  11819. \begin{tcolorbox}[colback=white]
  11820. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11821. \end{tcolorbox}
  11822. \caption{Representation of tuples in the heap.}
  11823. \label{fig:tuple-rep}
  11824. \end{figure}
  11825. \subsection{Implementation of the Garbage Collector}
  11826. \label{sec:organize-gz}
  11827. \index{subject}{prelude}
  11828. An implementation of the copying collector is provided in the
  11829. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11830. interface to the garbage collector that is used by the compiler. The
  11831. \code{initialize} function creates the FromSpace, ToSpace, and root
  11832. stack and should be called in the prelude of the \code{main}
  11833. function. The arguments of \code{initialize} are the root stack size
  11834. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11835. good choice for both. The \code{initialize} function puts the address
  11836. of the beginning of the FromSpace into the global variable
  11837. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11838. the address that is one past the last element of the FromSpace. We use
  11839. half-open intervals to represent chunks of
  11840. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11841. points to the first element of the root stack.
  11842. As long as there is room left in the FromSpace, your generated code
  11843. can allocate\index{subject}{allocate} tuples simply by moving the
  11844. \code{free\_ptr} forward.
  11845. %
  11846. The amount of room left in the FromSpace is the difference between the
  11847. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11848. function should be called when there is not enough room left in the
  11849. FromSpace for the next allocation. The \code{collect} function takes
  11850. a pointer to the current top of the root stack (one past the last item
  11851. that was pushed) and the number of bytes that need to be
  11852. allocated. The \code{collect} function performs the copying collection
  11853. and leaves the heap in a state such that there is enough room for the
  11854. next allocation.
  11855. \begin{figure}[tbp]
  11856. \begin{tcolorbox}[colback=white]
  11857. \begin{lstlisting}
  11858. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11859. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11860. int64_t* free_ptr;
  11861. int64_t* fromspace_begin;
  11862. int64_t* fromspace_end;
  11863. int64_t** rootstack_begin;
  11864. \end{lstlisting}
  11865. \end{tcolorbox}
  11866. \caption{The compiler's interface to the garbage collector.}
  11867. \label{fig:gc-header}
  11868. \end{figure}
  11869. %% \begin{exercise}
  11870. %% In the file \code{runtime.c} you will find the implementation of
  11871. %% \code{initialize} and a partial implementation of \code{collect}.
  11872. %% The \code{collect} function calls another function, \code{cheney},
  11873. %% to perform the actual copy, and that function is left to the reader
  11874. %% to implement. The following is the prototype for \code{cheney}.
  11875. %% \begin{lstlisting}
  11876. %% static void cheney(int64_t** rootstack_ptr);
  11877. %% \end{lstlisting}
  11878. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11879. %% rootstack (which is an array of pointers). The \code{cheney} function
  11880. %% also communicates with \code{collect} through the global
  11881. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11882. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11883. %% the ToSpace:
  11884. %% \begin{lstlisting}
  11885. %% static int64_t* tospace_begin;
  11886. %% static int64_t* tospace_end;
  11887. %% \end{lstlisting}
  11888. %% The job of the \code{cheney} function is to copy all the live
  11889. %% objects (reachable from the root stack) into the ToSpace, update
  11890. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11891. %% update the root stack so that it points to the objects in the
  11892. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11893. %% and ToSpace.
  11894. %% \end{exercise}
  11895. The introduction of garbage collection has a nontrivial impact on our
  11896. compiler passes. We introduce a new compiler pass named
  11897. \code{expose\_allocation} that elaborates the code for allocating
  11898. tuples. We also make significant changes to
  11899. \code{select\_instructions}, \code{build\_interference},
  11900. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11901. make minor changes in several more passes.
  11902. The following program serves as our running example. It creates
  11903. two tuples, one nested inside the other. Both tuples have length
  11904. one. The program accesses the element in the inner tuple.
  11905. % tests/vectors_test_17.rkt
  11906. {\if\edition\racketEd
  11907. \begin{lstlisting}
  11908. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11909. \end{lstlisting}
  11910. \fi}
  11911. % tests/tuple/get_get.py
  11912. {\if\edition\pythonEd\pythonColor
  11913. \begin{lstlisting}
  11914. v1 = (42,)
  11915. v2 = (v1,)
  11916. print(v2[0][0])
  11917. \end{lstlisting}
  11918. \fi}
  11919. %% {\if\edition\racketEd
  11920. %% \section{Shrink}
  11921. %% \label{sec:shrink-Lvec}
  11922. %% Recall that the \code{shrink} pass translates the primitives operators
  11923. %% into a smaller set of primitives.
  11924. %% %
  11925. %% This pass comes after type checking, and the type checker adds a
  11926. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11927. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11928. %% \fi}
  11929. \section{Expose Allocation}
  11930. \label{sec:expose-allocation}
  11931. The pass \code{expose\_allocation} lowers tuple creation into making a
  11932. conditional call to the collector followed by allocating the
  11933. appropriate amount of memory and initializing it. We choose to place
  11934. the \code{expose\_allocation} pass before
  11935. \code{remove\_complex\_operands} because it generates code that
  11936. contains complex operands. However, with some care it can also be
  11937. placed before \code{remove\_complex\_operands}, which would simplify
  11938. tuple creation by removing the need to assign the initializing
  11939. expressions to temporary variables (see below).
  11940. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11941. that replaces tuple creation with new lower-level forms that we use in the
  11942. translation of tuple creation.
  11943. %
  11944. {\if\edition\racketEd
  11945. \[
  11946. \begin{array}{lcl}
  11947. \Exp &::=& (\key{collect} \,\itm{int})
  11948. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11949. \MID (\key{global-value} \,\itm{name})
  11950. \end{array}
  11951. \]
  11952. \fi}
  11953. {\if\edition\pythonEd\pythonColor
  11954. \[
  11955. \begin{array}{lcl}
  11956. \Exp &::=& \key{collect}(\itm{int})
  11957. \MID \key{allocate}(\itm{int},\itm{type})
  11958. \MID \key{global\_value}(\itm{name}) \\
  11959. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11960. \end{array}
  11961. \]
  11962. \fi}
  11963. %
  11964. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  11965. there be $n$ bytes ready to be allocated. During instruction
  11966. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  11967. form will become a call to the \code{collect} function in
  11968. \code{runtime.c}.
  11969. %
  11970. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11971. space at the front for the 64-bit tag), but the elements are not
  11972. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11973. of the tuple:
  11974. %
  11975. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11976. %
  11977. where $\Type_i$ is the type of the $i$th element.
  11978. %
  11979. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11980. variable, such as \code{free\_ptr}.
  11981. \racket{
  11982. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11983. can be obtained by running the
  11984. \code{type-check-Lvec-has-type} type checker immediately before the
  11985. \code{expose\_allocation} pass. This version of the type checker
  11986. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11987. around each tuple creation. The concrete syntax
  11988. for \code{HasType} is \code{has-type}.}
  11989. The following shows the transformation of tuple creation into (1) a
  11990. sequence of temporary variable bindings for the initializing
  11991. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11992. \code{allocate}, and (4) the initialization of the tuple. The
  11993. \itm{len} placeholder refers to the length of the tuple, and
  11994. \itm{bytes} is the total number of bytes that need to be allocated for
  11995. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11996. %
  11997. \python{The \itm{type} needed for the second argument of the
  11998. \code{allocate} form can be obtained from the \code{has\_type} field
  11999. of the tuple AST node, which is stored there by running the type
  12000. checker for \LangVec{} immediately before this pass.}
  12001. %
  12002. \begin{center}
  12003. \begin{minipage}{\textwidth}
  12004. {\if\edition\racketEd
  12005. \begin{lstlisting}
  12006. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12007. |$\Longrightarrow$|
  12008. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12009. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12010. (global-value fromspace_end))
  12011. (void)
  12012. (collect |\itm{bytes}|))])
  12013. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12014. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12015. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12016. |$v$|) ... )))) ...)
  12017. \end{lstlisting}
  12018. \fi}
  12019. {\if\edition\pythonEd\pythonColor
  12020. \begin{lstlisting}
  12021. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12022. |$\Longrightarrow$|
  12023. begin:
  12024. |$x_0$| = |$e_0$|
  12025. |$\vdots$|
  12026. |$x_{n-1}$| = |$e_{n-1}$|
  12027. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12028. 0
  12029. else:
  12030. collect(|\itm{bytes}|)
  12031. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12032. |$v$|[0] = |$x_0$|
  12033. |$\vdots$|
  12034. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12035. |$v$|
  12036. \end{lstlisting}
  12037. \fi}
  12038. \end{minipage}
  12039. \end{center}
  12040. %
  12041. \noindent The sequencing of the initializing expressions
  12042. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12043. they may trigger garbage collection and we cannot have an allocated
  12044. but uninitialized tuple on the heap during a collection.
  12045. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12046. \code{expose\_allocation} pass on our running example.
  12047. \begin{figure}[tbp]
  12048. \begin{tcolorbox}[colback=white]
  12049. % tests/s2_17.rkt
  12050. {\if\edition\racketEd
  12051. \begin{lstlisting}
  12052. (vector-ref
  12053. (vector-ref
  12054. (let ([vecinit6
  12055. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12056. (global-value fromspace_end))
  12057. (void)
  12058. (collect 16))])
  12059. (let ([alloc2 (allocate 1 (Vector Integer))])
  12060. (let ([_3 (vector-set! alloc2 0 42)])
  12061. alloc2)))])
  12062. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12063. (global-value fromspace_end))
  12064. (void)
  12065. (collect 16))])
  12066. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12067. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12068. alloc5))))
  12069. 0)
  12070. 0)
  12071. \end{lstlisting}
  12072. \fi}
  12073. {\if\edition\pythonEd\pythonColor
  12074. \begin{lstlisting}
  12075. v1 = begin:
  12076. init.514 = 42
  12077. if (free_ptr + 16) < fromspace_end:
  12078. else:
  12079. collect(16)
  12080. alloc.513 = allocate(1,tuple[int])
  12081. alloc.513[0] = init.514
  12082. alloc.513
  12083. v2 = begin:
  12084. init.516 = v1
  12085. if (free_ptr + 16) < fromspace_end:
  12086. else:
  12087. collect(16)
  12088. alloc.515 = allocate(1,tuple[tuple[int]])
  12089. alloc.515[0] = init.516
  12090. alloc.515
  12091. print(v2[0][0])
  12092. \end{lstlisting}
  12093. \fi}
  12094. \end{tcolorbox}
  12095. \caption{Output of the \code{expose\_allocation} pass.}
  12096. \label{fig:expose-alloc-output}
  12097. \end{figure}
  12098. \section{Remove Complex Operands}
  12099. \label{sec:remove-complex-opera-Lvec}
  12100. {\if\edition\racketEd
  12101. %
  12102. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12103. should be treated as complex operands.
  12104. %
  12105. \fi}
  12106. %
  12107. {\if\edition\pythonEd\pythonColor
  12108. %
  12109. The expressions \code{allocate}, \code{begin},
  12110. and tuple access should be treated as complex operands. The
  12111. subexpressions of tuple access must be atomic.
  12112. The \code{global\_value} AST node is atomic.
  12113. %
  12114. \fi}
  12115. %% A new case for
  12116. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12117. %% handled carefully to prevent the \code{Prim} node from being separated
  12118. %% from its enclosing \code{HasType}.
  12119. Figure~\ref{fig:Lvec-anf-syntax}
  12120. shows the grammar for the output language \LangAllocANF{} of this
  12121. pass, which is \LangAlloc{} in monadic normal form.
  12122. \newcommand{\LtupMonadASTRacket}{
  12123. \begin{array}{rcl}
  12124. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12125. \MID \GLOBALVALUE{\Var}
  12126. \end{array}
  12127. }
  12128. \newcommand{\LtupMonadASTPython}{
  12129. \begin{array}{rcl}
  12130. \Atm &::=& \GLOBALVALUE{\Var} \\
  12131. \Exp &::=& \GET{\Atm}{\Atm}
  12132. \MID \LEN{\Atm}\\
  12133. &\MID& \ALLOCATE{\Int}{\Type}\\
  12134. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12135. &\MID& \COLLECT{\Int}
  12136. \end{array}
  12137. }
  12138. \begin{figure}[tp]
  12139. \centering
  12140. \begin{tcolorbox}[colback=white]
  12141. \small
  12142. {\if\edition\racketEd
  12143. \[
  12144. \begin{array}{l}
  12145. \gray{\LvarMonadASTRacket} \\ \hline
  12146. \gray{\LifMonadASTRacket} \\ \hline
  12147. \gray{\LwhileMonadASTRacket} \\ \hline
  12148. \LtupMonadASTRacket \\
  12149. \begin{array}{rcl}
  12150. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12151. \end{array}
  12152. \end{array}
  12153. \]
  12154. \fi}
  12155. {\if\edition\pythonEd\pythonColor
  12156. \[
  12157. \begin{array}{l}
  12158. \gray{\LvarMonadASTPython} \\ \hline
  12159. \gray{\LifMonadASTPython} \\ \hline
  12160. \gray{\LwhileMonadASTPython} \\ \hline
  12161. \LtupMonadASTPython \\
  12162. \begin{array}{rcl}
  12163. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12164. \end{array}
  12165. \end{array}
  12166. \]
  12167. \fi}
  12168. \end{tcolorbox}
  12169. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12170. \label{fig:Lvec-anf-syntax}
  12171. \end{figure}
  12172. \section{Explicate Control and the \LangCVec{} Language}
  12173. \label{sec:explicate-control-r3}
  12174. \newcommand{\CtupASTRacket}{
  12175. \begin{array}{lcl}
  12176. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12177. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12178. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12179. &\MID& \VECLEN{\Atm} \\
  12180. &\MID& \GLOBALVALUE{\Var} \\
  12181. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12182. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12183. \end{array}
  12184. }
  12185. \newcommand{\CtupASTPython}{
  12186. \begin{array}{lcl}
  12187. \Atm &::=& \GLOBALVALUE{\Var} \\
  12188. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12189. &\MID& \LEN{\Atm} \\
  12190. \Stmt &::=& \COLLECT{\Int}
  12191. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12192. \end{array}
  12193. }
  12194. \begin{figure}[tp]
  12195. \begin{tcolorbox}[colback=white]
  12196. \small
  12197. {\if\edition\racketEd
  12198. \[
  12199. \begin{array}{l}
  12200. \gray{\CvarASTRacket} \\ \hline
  12201. \gray{\CifASTRacket} \\ \hline
  12202. \gray{\CloopASTRacket} \\ \hline
  12203. \CtupASTRacket \\
  12204. \begin{array}{lcl}
  12205. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12206. \end{array}
  12207. \end{array}
  12208. \]
  12209. \fi}
  12210. {\if\edition\pythonEd\pythonColor
  12211. \[
  12212. \begin{array}{l}
  12213. \gray{\CifASTPython} \\ \hline
  12214. \CtupASTPython \\
  12215. \begin{array}{lcl}
  12216. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12217. \end{array}
  12218. \end{array}
  12219. \]
  12220. \fi}
  12221. \end{tcolorbox}
  12222. \caption{The abstract syntax of \LangCVec{}, extending
  12223. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12224. (figure~\ref{fig:c1-syntax})}.}
  12225. \label{fig:c2-syntax}
  12226. \end{figure}
  12227. The output of \code{explicate\_control} is a program in the
  12228. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12229. shows the definition of the abstract syntax.
  12230. %
  12231. %% \racket{(The concrete syntax is defined in
  12232. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12233. %
  12234. The new expressions of \LangCVec{} include \key{allocate},
  12235. %
  12236. \racket{\key{vector-ref}, and \key{vector-set!},}
  12237. %
  12238. \python{accessing tuple elements,}
  12239. %
  12240. and \key{global\_value}.
  12241. %
  12242. \python{\LangCVec{} also includes the \code{collect} statement and
  12243. assignment to a tuple element.}
  12244. %
  12245. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12246. %
  12247. The \code{explicate\_control} pass can treat these new forms much like
  12248. the other forms that we've already encountered. The output of the
  12249. \code{explicate\_control} pass on the running example is shown on the
  12250. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12251. section.
  12252. \section{Select Instructions and the \LangXGlobal{} Language}
  12253. \label{sec:select-instructions-gc}
  12254. \index{subject}{select instructions}
  12255. %% void (rep as zero)
  12256. %% allocate
  12257. %% collect (callq collect)
  12258. %% vector-ref
  12259. %% vector-set!
  12260. %% vector-length
  12261. %% global (postpone)
  12262. In this pass we generate x86 code for most of the new operations that
  12263. are needed to compile tuples, including \code{Allocate},
  12264. \code{Collect}, accessing tuple elements, and the \code{Is}
  12265. comparison.
  12266. %
  12267. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12268. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12269. \ref{fig:x86-2}). \index{subject}{x86}
  12270. The tuple read and write forms translate into \code{movq}
  12271. instructions. (The $+1$ in the offset serves to move past the tag at the
  12272. beginning of the tuple representation.)
  12273. %
  12274. \begin{center}
  12275. \begin{minipage}{\textwidth}
  12276. {\if\edition\racketEd
  12277. \begin{lstlisting}
  12278. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12279. |$\Longrightarrow$|
  12280. movq |$\itm{tup}'$|, %r11
  12281. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12282. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12283. |$\Longrightarrow$|
  12284. movq |$\itm{tup}'$|, %r11
  12285. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12286. movq $0, |$\itm{lhs'}$|
  12287. \end{lstlisting}
  12288. \fi}
  12289. {\if\edition\pythonEd\pythonColor
  12290. \begin{lstlisting}
  12291. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12292. |$\Longrightarrow$|
  12293. movq |$\itm{tup}'$|, %r11
  12294. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12295. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12296. |$\Longrightarrow$|
  12297. movq |$\itm{tup}'$|, %r11
  12298. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12299. \end{lstlisting}
  12300. \fi}
  12301. \end{minipage}
  12302. \end{center}
  12303. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12304. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12305. are obtained by translating from \LangCVec{} to x86.
  12306. %
  12307. The move of $\itm{tup}'$ to
  12308. register \code{r11} ensures that the offset expression
  12309. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12310. removing \code{r11} from consideration by the register allocator.
  12311. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12312. \code{rax}. Then the generated code for tuple assignment would be
  12313. \begin{lstlisting}
  12314. movq |$\itm{tup}'$|, %rax
  12315. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12316. \end{lstlisting}
  12317. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12318. \code{patch\_instructions} would insert a move through \code{rax}
  12319. as follows:
  12320. \begin{lstlisting}
  12321. movq |$\itm{tup}'$|, %rax
  12322. movq |$\itm{rhs}'$|, %rax
  12323. movq %rax, |$8(n+1)$|(%rax)
  12324. \end{lstlisting}
  12325. However, this sequence of instructions does not work because we're
  12326. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12327. $\itm{rhs}'$) at the same time!
  12328. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12329. be translated into a sequence of instructions that read the tag of the
  12330. tuple and extract the 6 bits that represent the tuple length, which
  12331. are the bits starting at index 1 and going up to and including bit 6.
  12332. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12333. (shift right) can be used to accomplish this.
  12334. We compile the \code{allocate} form to operations on the
  12335. \code{free\_ptr}, as shown next. This approach is called
  12336. \emph{inline allocation} because it implements allocation without a
  12337. function call by simply incrementing the allocation pointer. It is much
  12338. more efficient than calling a function for each allocation. The
  12339. address in the \code{free\_ptr} is the next free address in the
  12340. FromSpace, so we copy it into \code{r11} and then move it forward by
  12341. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12342. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12343. the tag. We then initialize the \itm{tag} and finally copy the
  12344. address in \code{r11} to the left-hand side. Refer to
  12345. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12346. %
  12347. \racket{We recommend using the Racket operations
  12348. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12349. during compilation.}
  12350. %
  12351. \python{We recommend using the bitwise-or operator \code{|} and the
  12352. shift-left operator \code{<<} to compute the tag during
  12353. compilation.}
  12354. %
  12355. The type annotation in the \code{allocate} form is used to determine
  12356. the pointer mask region of the tag.
  12357. %
  12358. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12359. address of the \code{free\_ptr} global variable using a special
  12360. instruction-pointer-relative addressing mode of the x86-64 processor.
  12361. In particular, the assembler computes the distance $d$ between the
  12362. address of \code{free\_ptr} and where the \code{rip} would be at that
  12363. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12364. \code{$d$(\%rip)}, which at runtime will compute the address of
  12365. \code{free\_ptr}.
  12366. %
  12367. {\if\edition\racketEd
  12368. \begin{lstlisting}
  12369. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12370. |$\Longrightarrow$|
  12371. movq free_ptr(%rip), %r11
  12372. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12373. movq $|$\itm{tag}$|, 0(%r11)
  12374. movq %r11, |$\itm{lhs}'$|
  12375. \end{lstlisting}
  12376. \fi}
  12377. {\if\edition\pythonEd\pythonColor
  12378. \begin{lstlisting}
  12379. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12380. |$\Longrightarrow$|
  12381. movq free_ptr(%rip), %r11
  12382. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12383. movq $|$\itm{tag}$|, 0(%r11)
  12384. movq %r11, |$\itm{lhs}'$|
  12385. \end{lstlisting}
  12386. \fi}
  12387. %
  12388. The \code{collect} form is compiled to a call to the \code{collect}
  12389. function in the runtime. The arguments to \code{collect} are (1) the
  12390. top of the root stack, and (2) the number of bytes that need to be
  12391. allocated. We use another dedicated register, \code{r15}, to store
  12392. the pointer to the top of the root stack. Therefore \code{r15} is not
  12393. available for use by the register allocator.
  12394. %
  12395. {\if\edition\racketEd
  12396. \begin{lstlisting}
  12397. (collect |$\itm{bytes}$|)
  12398. |$\Longrightarrow$|
  12399. movq %r15, %rdi
  12400. movq $|\itm{bytes}|, %rsi
  12401. callq collect
  12402. \end{lstlisting}
  12403. \fi}
  12404. {\if\edition\pythonEd\pythonColor
  12405. \begin{lstlisting}
  12406. collect(|$\itm{bytes}$|)
  12407. |$\Longrightarrow$|
  12408. movq %r15, %rdi
  12409. movq $|\itm{bytes}|, %rsi
  12410. callq collect
  12411. \end{lstlisting}
  12412. \fi}
  12413. {\if\edition\pythonEd\pythonColor
  12414. The \code{is} comparison is compiled similarly to the other comparison
  12415. operators, using the \code{cmpq} instruction. Because the value of a
  12416. tuple is its address, we can translate \code{is} into a simple check
  12417. for equality using the \code{e} condition code. \\
  12418. \begin{tabular}{lll}
  12419. \begin{minipage}{0.4\textwidth}
  12420. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12421. \end{minipage}
  12422. &
  12423. $\Rightarrow$
  12424. &
  12425. \begin{minipage}{0.4\textwidth}
  12426. \begin{lstlisting}
  12427. cmpq |$\Arg_2$|, |$\Arg_1$|
  12428. sete %al
  12429. movzbq %al, |$\Var$|
  12430. \end{lstlisting}
  12431. \end{minipage}
  12432. \end{tabular}
  12433. \fi}
  12434. \newcommand{\GrammarXGlobal}{
  12435. \begin{array}{lcl}
  12436. \Arg &::=& \itm{label} \key{(\%rip)}
  12437. \end{array}
  12438. }
  12439. \newcommand{\ASTXGlobalRacket}{
  12440. \begin{array}{lcl}
  12441. \Arg &::=& \GLOBAL{\itm{label}}
  12442. \end{array}
  12443. }
  12444. \begin{figure}[tp]
  12445. \begin{tcolorbox}[colback=white]
  12446. \[
  12447. \begin{array}{l}
  12448. \gray{\GrammarXInt} \\ \hline
  12449. \gray{\GrammarXIf} \\ \hline
  12450. \GrammarXGlobal \\
  12451. \begin{array}{lcl}
  12452. \LangXGlobalM{} &::= & \key{.globl main} \\
  12453. & & \key{main:} \; \Instr^{*}
  12454. \end{array}
  12455. \end{array}
  12456. \]
  12457. \end{tcolorbox}
  12458. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12459. \label{fig:x86-2-concrete}
  12460. \end{figure}
  12461. \begin{figure}[tp]
  12462. \begin{tcolorbox}[colback=white]
  12463. \small
  12464. {\if\edition\racketEd
  12465. \[
  12466. \begin{array}{l}
  12467. \gray{\ASTXIntRacket} \\ \hline
  12468. \gray{\ASTXIfRacket} \\ \hline
  12469. \ASTXGlobalRacket \\
  12470. \begin{array}{lcl}
  12471. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12472. \end{array}
  12473. \end{array}
  12474. \]
  12475. \fi}
  12476. {\if\edition\pythonEd\pythonColor
  12477. \[
  12478. \begin{array}{l}
  12479. \gray{\ASTXIntPython} \\ \hline
  12480. \gray{\ASTXIfPython} \\ \hline
  12481. \ASTXGlobalRacket \\
  12482. \begin{array}{lcl}
  12483. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12484. \end{array}
  12485. \end{array}
  12486. \]
  12487. \fi}
  12488. \end{tcolorbox}
  12489. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12490. \label{fig:x86-2}
  12491. \end{figure}
  12492. The definitions of the concrete and abstract syntax of the
  12493. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12494. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12495. of global variables.
  12496. %
  12497. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12498. \code{select\_instructions} pass on the running example.
  12499. \begin{figure}[tbp]
  12500. \centering
  12501. \begin{tcolorbox}[colback=white]
  12502. {\if\edition\racketEd
  12503. % tests/s2_17.rkt
  12504. \begin{tabular}{lll}
  12505. \begin{minipage}{0.5\textwidth}
  12506. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12507. start:
  12508. tmp9 = (global-value free_ptr);
  12509. tmp0 = (+ tmp9 16);
  12510. tmp1 = (global-value fromspace_end);
  12511. if (< tmp0 tmp1)
  12512. goto block0;
  12513. else
  12514. goto block1;
  12515. block0:
  12516. _4 = (void);
  12517. goto block9;
  12518. block1:
  12519. (collect 16)
  12520. goto block9;
  12521. block9:
  12522. alloc2 = (allocate 1 (Vector Integer));
  12523. _3 = (vector-set! alloc2 0 42);
  12524. vecinit6 = alloc2;
  12525. tmp2 = (global-value free_ptr);
  12526. tmp3 = (+ tmp2 16);
  12527. tmp4 = (global-value fromspace_end);
  12528. if (< tmp3 tmp4)
  12529. goto block7;
  12530. else
  12531. goto block8;
  12532. block7:
  12533. _8 = (void);
  12534. goto block6;
  12535. block8:
  12536. (collect 16)
  12537. goto block6;
  12538. block6:
  12539. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12540. _7 = (vector-set! alloc5 0 vecinit6);
  12541. tmp5 = (vector-ref alloc5 0);
  12542. return (vector-ref tmp5 0);
  12543. \end{lstlisting}
  12544. \end{minipage}
  12545. &$\Rightarrow$&
  12546. \begin{minipage}{0.4\textwidth}
  12547. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12548. start:
  12549. movq free_ptr(%rip), tmp9
  12550. movq tmp9, tmp0
  12551. addq $16, tmp0
  12552. movq fromspace_end(%rip), tmp1
  12553. cmpq tmp1, tmp0
  12554. jl block0
  12555. jmp block1
  12556. block0:
  12557. movq $0, _4
  12558. jmp block9
  12559. block1:
  12560. movq %r15, %rdi
  12561. movq $16, %rsi
  12562. callq collect
  12563. jmp block9
  12564. block9:
  12565. movq free_ptr(%rip), %r11
  12566. addq $16, free_ptr(%rip)
  12567. movq $3, 0(%r11)
  12568. movq %r11, alloc2
  12569. movq alloc2, %r11
  12570. movq $42, 8(%r11)
  12571. movq $0, _3
  12572. movq alloc2, vecinit6
  12573. movq free_ptr(%rip), tmp2
  12574. movq tmp2, tmp3
  12575. addq $16, tmp3
  12576. movq fromspace_end(%rip), tmp4
  12577. cmpq tmp4, tmp3
  12578. jl block7
  12579. jmp block8
  12580. block7:
  12581. movq $0, _8
  12582. jmp block6
  12583. block8:
  12584. movq %r15, %rdi
  12585. movq $16, %rsi
  12586. callq collect
  12587. jmp block6
  12588. block6:
  12589. movq free_ptr(%rip), %r11
  12590. addq $16, free_ptr(%rip)
  12591. movq $131, 0(%r11)
  12592. movq %r11, alloc5
  12593. movq alloc5, %r11
  12594. movq vecinit6, 8(%r11)
  12595. movq $0, _7
  12596. movq alloc5, %r11
  12597. movq 8(%r11), tmp5
  12598. movq tmp5, %r11
  12599. movq 8(%r11), %rax
  12600. jmp conclusion
  12601. \end{lstlisting}
  12602. \end{minipage}
  12603. \end{tabular}
  12604. \fi}
  12605. {\if\edition\pythonEd
  12606. % tests/tuple/get_get.py
  12607. \begin{tabular}{lll}
  12608. \begin{minipage}{0.5\textwidth}
  12609. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12610. start:
  12611. init.514 = 42
  12612. tmp.517 = free_ptr
  12613. tmp.518 = (tmp.517 + 16)
  12614. tmp.519 = fromspace_end
  12615. if tmp.518 < tmp.519:
  12616. goto block.529
  12617. else:
  12618. goto block.530
  12619. block.529:
  12620. goto block.528
  12621. block.530:
  12622. collect(16)
  12623. goto block.528
  12624. block.528:
  12625. alloc.513 = allocate(1,tuple[int])
  12626. alloc.513:tuple[int][0] = init.514
  12627. v1 = alloc.513
  12628. init.516 = v1
  12629. tmp.520 = free_ptr
  12630. tmp.521 = (tmp.520 + 16)
  12631. tmp.522 = fromspace_end
  12632. if tmp.521 < tmp.522:
  12633. goto block.526
  12634. else:
  12635. goto block.527
  12636. block.526:
  12637. goto block.525
  12638. block.527:
  12639. collect(16)
  12640. goto block.525
  12641. block.525:
  12642. alloc.515 = allocate(1,tuple[tuple[int]])
  12643. alloc.515:tuple[tuple[int]][0] = init.516
  12644. v2 = alloc.515
  12645. tmp.523 = v2[0]
  12646. tmp.524 = tmp.523[0]
  12647. print(tmp.524)
  12648. return 0
  12649. \end{lstlisting}
  12650. \end{minipage}
  12651. &$\Rightarrow$&
  12652. \begin{minipage}{0.4\textwidth}
  12653. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12654. start:
  12655. movq $42, init.514
  12656. movq free_ptr(%rip), tmp.517
  12657. movq tmp.517, tmp.518
  12658. addq $16, tmp.518
  12659. movq fromspace_end(%rip), tmp.519
  12660. cmpq tmp.519, tmp.518
  12661. jl block.529
  12662. jmp block.530
  12663. block.529:
  12664. jmp block.528
  12665. block.530:
  12666. movq %r15, %rdi
  12667. movq $16, %rsi
  12668. callq collect
  12669. jmp block.528
  12670. block.528:
  12671. movq free_ptr(%rip), %r11
  12672. addq $16, free_ptr(%rip)
  12673. movq $3, 0(%r11)
  12674. movq %r11, alloc.513
  12675. movq alloc.513, %r11
  12676. movq init.514, 8(%r11)
  12677. movq alloc.513, v1
  12678. movq v1, init.516
  12679. movq free_ptr(%rip), tmp.520
  12680. movq tmp.520, tmp.521
  12681. addq $16, tmp.521
  12682. movq fromspace_end(%rip), tmp.522
  12683. cmpq tmp.522, tmp.521
  12684. jl block.526
  12685. jmp block.527
  12686. block.526:
  12687. jmp block.525
  12688. block.527:
  12689. movq %r15, %rdi
  12690. movq $16, %rsi
  12691. callq collect
  12692. jmp block.525
  12693. block.525:
  12694. movq free_ptr(%rip), %r11
  12695. addq $16, free_ptr(%rip)
  12696. movq $131, 0(%r11)
  12697. movq %r11, alloc.515
  12698. movq alloc.515, %r11
  12699. movq init.516, 8(%r11)
  12700. movq alloc.515, v2
  12701. movq v2, %r11
  12702. movq 8(%r11), %r11
  12703. movq %r11, tmp.523
  12704. movq tmp.523, %r11
  12705. movq 8(%r11), %r11
  12706. movq %r11, tmp.524
  12707. movq tmp.524, %rdi
  12708. callq print_int
  12709. movq $0, %rax
  12710. jmp conclusion
  12711. \end{lstlisting}
  12712. \end{minipage}
  12713. \end{tabular}
  12714. \fi}
  12715. \end{tcolorbox}
  12716. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12717. \code{select\_instructions} (\emph{right}) on the running example.}
  12718. \label{fig:select-instr-output-gc}
  12719. \end{figure}
  12720. \clearpage
  12721. \section{Register Allocation}
  12722. \label{sec:reg-alloc-gc}
  12723. \index{subject}{register allocation}
  12724. As discussed previously in this chapter, the garbage collector needs to
  12725. access all the pointers in the root set, that is, all variables that
  12726. are tuples. It will be the responsibility of the register allocator
  12727. to make sure that
  12728. \begin{enumerate}
  12729. \item the root stack is used for spilling tuple-typed variables, and
  12730. \item if a tuple-typed variable is live during a call to the
  12731. collector, it must be spilled to ensure that it is visible to the
  12732. collector.
  12733. \end{enumerate}
  12734. The latter responsibility can be handled during construction of the
  12735. interference graph, by adding interference edges between the call-live
  12736. tuple-typed variables and all the callee-saved registers. (They
  12737. already interfere with the caller-saved registers.)
  12738. %
  12739. \racket{The type information for variables is in the \code{Program}
  12740. form, so we recommend adding another parameter to the
  12741. \code{build\_interference} function to communicate this alist.}
  12742. %
  12743. \python{The type information for variables is generated by the type
  12744. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12745. the \code{CProgram} AST mode. You'll need to propagate that
  12746. information so that it is available in this pass.}
  12747. The spilling of tuple-typed variables to the root stack can be handled
  12748. after graph coloring, in choosing how to assign the colors
  12749. (integers) to registers and stack locations. The
  12750. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12751. changes to also record the number of spills to the root stack.
  12752. % build-interference
  12753. %
  12754. % callq
  12755. % extra parameter for var->type assoc. list
  12756. % update 'program' and 'if'
  12757. % allocate-registers
  12758. % allocate spilled vectors to the rootstack
  12759. % don't change color-graph
  12760. % TODO:
  12761. %\section{Patch Instructions}
  12762. %[mention that global variables are memory references]
  12763. \section{Generate Prelude and Conclusion}
  12764. \label{sec:print-x86-gc}
  12765. \label{sec:prelude-conclusion-x86-gc}
  12766. \index{subject}{prelude}\index{subject}{conclusion}
  12767. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12768. \code{prelude\_and\_conclusion} pass on the running example. In the
  12769. prelude of the \code{main} function, we allocate space
  12770. on the root stack to make room for the spills of tuple-typed
  12771. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12772. taking care that the root stack grows up instead of down. For the
  12773. running example, there was just one spill, so we increment \code{r15}
  12774. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12775. One issue that deserves special care is that there may be a call to
  12776. \code{collect} prior to the initializing assignments for all the
  12777. variables in the root stack. We do not want the garbage collector to
  12778. mistakenly determine that some uninitialized variable is a pointer that
  12779. needs to be followed. Thus, we zero out all locations on the root
  12780. stack in the prelude of \code{main}. In
  12781. figure~\ref{fig:print-x86-output-gc}, the instruction
  12782. %
  12783. \lstinline{movq $0, 0(%r15)}
  12784. %
  12785. is sufficient to accomplish this task because there is only one spill.
  12786. In general, we have to clear as many words as there are spills of
  12787. tuple-typed variables. The garbage collector tests each root to see
  12788. if it is null prior to dereferencing it.
  12789. \begin{figure}[htbp]
  12790. \begin{tcolorbox}[colback=white]
  12791. {\if\edition\racketEd
  12792. \begin{minipage}[t]{0.5\textwidth}
  12793. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12794. .globl main
  12795. main:
  12796. pushq %rbp
  12797. movq %rsp, %rbp
  12798. subq $0, %rsp
  12799. movq $65536, %rdi
  12800. movq $65536, %rsi
  12801. callq initialize
  12802. movq rootstack_begin(%rip), %r15
  12803. movq $0, 0(%r15)
  12804. addq $8, %r15
  12805. jmp start
  12806. conclusion:
  12807. subq $8, %r15
  12808. addq $0, %rsp
  12809. popq %rbp
  12810. retq
  12811. \end{lstlisting}
  12812. \end{minipage}
  12813. \fi}
  12814. {\if\edition\pythonEd
  12815. \begin{minipage}[t]{0.5\textwidth}
  12816. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12817. .globl main
  12818. main:
  12819. pushq %rbp
  12820. movq %rsp, %rbp
  12821. pushq %rbx
  12822. subq $8, %rsp
  12823. movq $65536, %rdi
  12824. movq $16, %rsi
  12825. callq initialize
  12826. movq rootstack_begin(%rip), %r15
  12827. movq $0, 0(%r15)
  12828. addq $8, %r15
  12829. jmp start
  12830. conclusion:
  12831. subq $8, %r15
  12832. addq $8, %rsp
  12833. popq %rbx
  12834. popq %rbp
  12835. retq
  12836. \end{lstlisting}
  12837. \end{minipage}
  12838. \fi}
  12839. \end{tcolorbox}
  12840. \caption{The prelude and conclusion for the running example.}
  12841. \label{fig:print-x86-output-gc}
  12842. \end{figure}
  12843. \begin{figure}[tbp]
  12844. \begin{tcolorbox}[colback=white]
  12845. {\if\edition\racketEd
  12846. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12847. \node (Lvec) at (0,2) {\large \LangVec{}};
  12848. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12849. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12850. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12851. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12852. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12853. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12854. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12855. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12856. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12857. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12858. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12859. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12860. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12861. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12862. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12863. \path[->,bend left=15] (Lvec-4) edge [right] node
  12864. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12865. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12866. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12867. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12868. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12869. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12870. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12871. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12872. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12873. \end{tikzpicture}
  12874. \fi}
  12875. {\if\edition\pythonEd\pythonColor
  12876. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12877. \node (Lvec) at (0,2) {\large \LangVec{}};
  12878. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12879. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12880. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12881. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12882. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12883. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12884. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12885. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12886. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12887. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12888. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12889. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12890. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12891. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12892. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12893. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12894. \end{tikzpicture}
  12895. \fi}
  12896. \end{tcolorbox}
  12897. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12898. \label{fig:Lvec-passes}
  12899. \end{figure}
  12900. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12901. for the compilation of \LangVec{}.
  12902. \clearpage
  12903. {\if\edition\racketEd
  12904. \section{Challenge: Simple Structures}
  12905. \label{sec:simple-structures}
  12906. \index{subject}{struct}
  12907. \index{subject}{structure}
  12908. The language \LangStruct{} extends \LangVec{} with support for simple
  12909. structures. The definition of its concrete syntax is shown in
  12910. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12911. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12912. in Typed Racket is a user-defined data type that contains named fields
  12913. and that is heap allocated\index{subject}{heap allocated},
  12914. similarly to a vector. The following is an
  12915. example of a structure definition, in this case the definition of a
  12916. \code{point} type:
  12917. \begin{lstlisting}
  12918. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12919. \end{lstlisting}
  12920. \newcommand{\LstructGrammarRacket}{
  12921. \begin{array}{lcl}
  12922. \Type &::=& \Var \\
  12923. \Exp &::=& (\Var\;\Exp \ldots)\\
  12924. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12925. \end{array}
  12926. }
  12927. \newcommand{\LstructASTRacket}{
  12928. \begin{array}{lcl}
  12929. \Type &::=& \VAR{\Var} \\
  12930. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12931. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12932. \end{array}
  12933. }
  12934. \begin{figure}[tbp]
  12935. \centering
  12936. \begin{tcolorbox}[colback=white]
  12937. \[
  12938. \begin{array}{l}
  12939. \gray{\LintGrammarRacket{}} \\ \hline
  12940. \gray{\LvarGrammarRacket{}} \\ \hline
  12941. \gray{\LifGrammarRacket{}} \\ \hline
  12942. \gray{\LwhileGrammarRacket} \\ \hline
  12943. \gray{\LtupGrammarRacket} \\ \hline
  12944. \LstructGrammarRacket \\
  12945. \begin{array}{lcl}
  12946. \LangStruct{} &::=& \Def \ldots \; \Exp
  12947. \end{array}
  12948. \end{array}
  12949. \]
  12950. \end{tcolorbox}
  12951. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12952. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12953. \label{fig:Lstruct-concrete-syntax}
  12954. \end{figure}
  12955. \begin{figure}[tbp]
  12956. \centering
  12957. \begin{tcolorbox}[colback=white]
  12958. \small
  12959. \[
  12960. \begin{array}{l}
  12961. \gray{\LintASTRacket{}} \\ \hline
  12962. \gray{\LvarASTRacket{}} \\ \hline
  12963. \gray{\LifASTRacket{}} \\ \hline
  12964. \gray{\LwhileASTRacket} \\ \hline
  12965. \gray{\LtupASTRacket} \\ \hline
  12966. \LstructASTRacket \\
  12967. \begin{array}{lcl}
  12968. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12969. \end{array}
  12970. \end{array}
  12971. \]
  12972. \end{tcolorbox}
  12973. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12974. (figure~\ref{fig:Lvec-syntax}).}
  12975. \label{fig:Lstruct-syntax}
  12976. \end{figure}
  12977. An instance of a structure is created using function-call syntax, with
  12978. the name of the structure in the function position, as follows:
  12979. \begin{lstlisting}
  12980. (point 7 12)
  12981. \end{lstlisting}
  12982. Function-call syntax is also used to read a field of a structure. The
  12983. function name is formed by the structure name, a dash, and the field
  12984. name. The following example uses \code{point-x} and \code{point-y} to
  12985. access the \code{x} and \code{y} fields of two point instances:
  12986. \begin{center}
  12987. \begin{lstlisting}
  12988. (let ([pt1 (point 7 12)])
  12989. (let ([pt2 (point 4 3)])
  12990. (+ (- (point-x pt1) (point-x pt2))
  12991. (- (point-y pt1) (point-y pt2)))))
  12992. \end{lstlisting}
  12993. \end{center}
  12994. Similarly, to write to a field of a structure, use its set function,
  12995. whose name starts with \code{set-}, followed by the structure name,
  12996. then a dash, then the field name, and finally with an exclamation
  12997. mark. The following example uses \code{set-point-x!} to change the
  12998. \code{x} field from \code{7} to \code{42}:
  12999. \begin{center}
  13000. \begin{lstlisting}
  13001. (let ([pt (point 7 12)])
  13002. (let ([_ (set-point-x! pt 42)])
  13003. (point-x pt)))
  13004. \end{lstlisting}
  13005. \end{center}
  13006. \begin{exercise}\normalfont\normalsize
  13007. Create a type checker for \LangStruct{} by extending the type
  13008. checker for \LangVec{}. Extend your compiler with support for simple
  13009. structures, compiling \LangStruct{} to x86 assembly code. Create
  13010. five new test cases that use structures, and test your compiler.
  13011. \end{exercise}
  13012. % TODO: create an interpreter for L_struct
  13013. \clearpage
  13014. \fi}
  13015. \section{Challenge: Arrays}
  13016. \label{sec:arrays}
  13017. % TODO mention trapped-error
  13018. In this chapter we have studied tuples, that is, heterogeneous
  13019. sequences of elements whose length is determined at compile time. This
  13020. challenge is also about sequences, but this time the length is
  13021. determined at runtime and all the elements have the same type (they
  13022. are homogeneous). We use the traditional term \emph{array} for this
  13023. latter kind of sequence.
  13024. %
  13025. \racket{
  13026. The Racket language does not distinguish between tuples and arrays;
  13027. they are both represented by vectors. However, Typed Racket
  13028. distinguishes between tuples and arrays: the \code{Vector} type is for
  13029. tuples, and the \code{Vectorof} type is for arrays.}%
  13030. \python{Arrays correspond to the \code{list} type in the Python language.}
  13031. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13032. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13033. presents the definition of the abstract syntax, extending \LangVec{}
  13034. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13035. \racket{\code{make-vector} primitive operator for creating an array,
  13036. whose arguments are the length of the array and an initial value for
  13037. all the elements in the array.}%
  13038. \python{bracket notation for creating an array literal.}
  13039. \racket{The \code{vector-length},
  13040. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13041. for tuples become overloaded for use with arrays.}
  13042. \python{
  13043. The subscript operator becomes overloaded for use with arrays and tuples
  13044. and now may appear on the left-hand side of an assignment.
  13045. Note that the index of the subscript, when applied to an array, may be an
  13046. arbitrary expression and not exclusively a constant integer.
  13047. The \code{len} function is also applicable to arrays.
  13048. }
  13049. %
  13050. We include integer multiplication in \LangArray{} because it is
  13051. useful in many examples involving arrays such as computing the
  13052. inner product of two arrays (figure~\ref{fig:inner_product}).
  13053. \newcommand{\LarrayGrammarRacket}{
  13054. \begin{array}{lcl}
  13055. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13056. \Exp &::=& \CMUL{\Exp}{\Exp}
  13057. \MID \CMAKEVEC{\Exp}{\Exp}
  13058. \end{array}
  13059. }
  13060. \newcommand{\LarrayASTRacket}{
  13061. \begin{array}{lcl}
  13062. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13063. \Exp &::=& \MUL{\Exp}{\Exp}
  13064. \MID \MAKEVEC{\Exp}{\Exp}
  13065. \end{array}
  13066. }
  13067. \newcommand{\LarrayGrammarPython}{
  13068. \begin{array}{lcl}
  13069. \Type &::=& \key{list}\LS\Type\RS \\
  13070. \Exp &::=& \CMUL{\Exp}{\Exp}
  13071. \MID \CGET{\Exp}{\Exp}
  13072. \MID \LS \Exp \code{,} \ldots \RS \\
  13073. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13074. \end{array}
  13075. }
  13076. \newcommand{\LarrayASTPython}{
  13077. \begin{array}{lcl}
  13078. \Type &::=& \key{ListType}\LP\Type\RP \\
  13079. \Exp &::=& \MUL{\Exp}{\Exp}
  13080. \MID \GET{\Exp}{\Exp} \\
  13081. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13082. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13083. \end{array}
  13084. }
  13085. \begin{figure}[tp]
  13086. \centering
  13087. \begin{tcolorbox}[colback=white]
  13088. \small
  13089. {\if\edition\racketEd
  13090. \[
  13091. \begin{array}{l}
  13092. \gray{\LintGrammarRacket{}} \\ \hline
  13093. \gray{\LvarGrammarRacket{}} \\ \hline
  13094. \gray{\LifGrammarRacket{}} \\ \hline
  13095. \gray{\LwhileGrammarRacket} \\ \hline
  13096. \gray{\LtupGrammarRacket} \\ \hline
  13097. \LarrayGrammarRacket \\
  13098. \begin{array}{lcl}
  13099. \LangArray{} &::=& \Exp
  13100. \end{array}
  13101. \end{array}
  13102. \]
  13103. \fi}
  13104. {\if\edition\pythonEd\pythonColor
  13105. \[
  13106. \begin{array}{l}
  13107. \gray{\LintGrammarPython{}} \\ \hline
  13108. \gray{\LvarGrammarPython{}} \\ \hline
  13109. \gray{\LifGrammarPython{}} \\ \hline
  13110. \gray{\LwhileGrammarPython} \\ \hline
  13111. \gray{\LtupGrammarPython} \\ \hline
  13112. \LarrayGrammarPython \\
  13113. \begin{array}{rcl}
  13114. \LangArrayM{} &::=& \Stmt^{*}
  13115. \end{array}
  13116. \end{array}
  13117. \]
  13118. \fi}
  13119. \end{tcolorbox}
  13120. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13121. \label{fig:Lvecof-concrete-syntax}
  13122. \end{figure}
  13123. \begin{figure}[tp]
  13124. \centering
  13125. \begin{tcolorbox}[colback=white]
  13126. \small
  13127. {\if\edition\racketEd
  13128. \[
  13129. \begin{array}{l}
  13130. \gray{\LintASTRacket{}} \\ \hline
  13131. \gray{\LvarASTRacket{}} \\ \hline
  13132. \gray{\LifASTRacket{}} \\ \hline
  13133. \gray{\LwhileASTRacket} \\ \hline
  13134. \gray{\LtupASTRacket} \\ \hline
  13135. \LarrayASTRacket \\
  13136. \begin{array}{lcl}
  13137. \LangArray{} &::=& \Exp
  13138. \end{array}
  13139. \end{array}
  13140. \]
  13141. \fi}
  13142. {\if\edition\pythonEd\pythonColor
  13143. \[
  13144. \begin{array}{l}
  13145. \gray{\LintASTPython{}} \\ \hline
  13146. \gray{\LvarASTPython{}} \\ \hline
  13147. \gray{\LifASTPython{}} \\ \hline
  13148. \gray{\LwhileASTPython} \\ \hline
  13149. \gray{\LtupASTPython} \\ \hline
  13150. \LarrayASTPython \\
  13151. \begin{array}{rcl}
  13152. \LangArrayM{} &::=& \Stmt^{*}
  13153. \end{array}
  13154. \end{array}
  13155. \]
  13156. \fi}
  13157. \end{tcolorbox}
  13158. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13159. \label{fig:Lvecof-syntax}
  13160. \end{figure}
  13161. \begin{figure}[tp]
  13162. \begin{tcolorbox}[colback=white]
  13163. {\if\edition\racketEd
  13164. % TODO: remove the function from the following example, like the python version -Jeremy
  13165. \begin{lstlisting}
  13166. (let ([A (make-vector 2 2)])
  13167. (let ([B (make-vector 2 3)])
  13168. (let ([i 0])
  13169. (let ([prod 0])
  13170. (begin
  13171. (while (< i n)
  13172. (begin
  13173. (set! prod (+ prod (* (vector-ref A i)
  13174. (vector-ref B i))))
  13175. (set! i (+ i 1))))
  13176. prod)))))
  13177. \end{lstlisting}
  13178. \fi}
  13179. {\if\edition\pythonEd\pythonColor
  13180. \begin{lstlisting}
  13181. A = [2, 2]
  13182. B = [3, 3]
  13183. i = 0
  13184. prod = 0
  13185. while i != len(A):
  13186. prod = prod + A[i] * B[i]
  13187. i = i + 1
  13188. print(prod)
  13189. \end{lstlisting}
  13190. \fi}
  13191. \end{tcolorbox}
  13192. \caption{Example program that computes the inner product.}
  13193. \label{fig:inner_product}
  13194. \end{figure}
  13195. {\if\edition\racketEd
  13196. %
  13197. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13198. checker for \LangArray{}. The result type of
  13199. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13200. of the initializing expression. The length expression is required to
  13201. have type \code{Integer}. The type checking of the operators
  13202. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13203. updated to handle the situation in which the vector has type
  13204. \code{Vectorof}. In these cases we translate the operators to their
  13205. \code{vectorof} form so that later passes can easily distinguish
  13206. between operations on tuples versus arrays. We override the
  13207. \code{operator-types} method to provide the type signature for
  13208. multiplication: it takes two integers and returns an integer.
  13209. \fi}
  13210. %
  13211. {\if\edition\pythonEd\pythonColor
  13212. %
  13213. The type checker for \LangArray{} is defined in
  13214. figures~\ref{fig:type-check-Lvecof} and
  13215. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13216. is \code{list[T]}, where \code{T} is the type of the initializing
  13217. expressions. The type checking of the \code{len} function and the
  13218. subscript operator are updated to handle lists. The type checker now
  13219. also handles a subscript on the left-hand side of an assignment.
  13220. Regarding multiplication, it takes two integers and returns an
  13221. integer.
  13222. %
  13223. \fi}
  13224. \begin{figure}[tbp]
  13225. \begin{tcolorbox}[colback=white]
  13226. {\if\edition\racketEd
  13227. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13228. (define type-check-Lvecof-class
  13229. (class type-check-Lvec-class
  13230. (super-new)
  13231. (inherit check-type-equal?)
  13232. (define/override (operator-types)
  13233. (append '((* . ((Integer Integer) . Integer)))
  13234. (super operator-types)))
  13235. (define/override (type-check-exp env)
  13236. (lambda (e)
  13237. (define recur (type-check-exp env))
  13238. (match e
  13239. [(Prim 'make-vector (list e1 e2))
  13240. (define-values (e1^ t1) (recur e1))
  13241. (define-values (e2^ elt-type) (recur e2))
  13242. (define vec-type `(Vectorof ,elt-type))
  13243. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13244. [(Prim 'vector-ref (list e1 e2))
  13245. (define-values (e1^ t1) (recur e1))
  13246. (define-values (e2^ t2) (recur e2))
  13247. (match* (t1 t2)
  13248. [(`(Vectorof ,elt-type) 'Integer)
  13249. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13250. [(other wise) ((super type-check-exp env) e)])]
  13251. [(Prim 'vector-set! (list e1 e2 e3) )
  13252. (define-values (e-vec t-vec) (recur e1))
  13253. (define-values (e2^ t2) (recur e2))
  13254. (define-values (e-arg^ t-arg) (recur e3))
  13255. (match t-vec
  13256. [`(Vectorof ,elt-type)
  13257. (check-type-equal? elt-type t-arg e)
  13258. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13259. [else ((super type-check-exp env) e)])]
  13260. [(Prim 'vector-length (list e1))
  13261. (define-values (e1^ t1) (recur e1))
  13262. (match t1
  13263. [`(Vectorof ,t)
  13264. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13265. [else ((super type-check-exp env) e)])]
  13266. [else ((super type-check-exp env) e)])))
  13267. ))
  13268. (define (type-check-Lvecof p)
  13269. (send (new type-check-Lvecof-class) type-check-program p))
  13270. \end{lstlisting}
  13271. \fi}
  13272. {\if\edition\pythonEd\pythonColor
  13273. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13274. class TypeCheckLarray(TypeCheckLtup):
  13275. def type_check_exp(self, e, env):
  13276. match e:
  13277. case ast.List(es, Load()):
  13278. ts = [self.type_check_exp(e, env) for e in es]
  13279. elt_ty = ts[0]
  13280. for (ty, elt) in zip(ts, es):
  13281. self.check_type_equal(elt_ty, ty, elt)
  13282. e.has_type = ListType(elt_ty)
  13283. return e.has_type
  13284. case Call(Name('len'), [tup]):
  13285. tup_t = self.type_check_exp(tup, env)
  13286. tup.has_type = tup_t
  13287. match tup_t:
  13288. case TupleType(ts):
  13289. return IntType()
  13290. case ListType(ty):
  13291. return IntType()
  13292. case _:
  13293. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13294. case Subscript(tup, index, Load()):
  13295. tup_ty = self.type_check_exp(tup, env)
  13296. index_ty = self.type_check_exp(index, env)
  13297. self.check_type_equal(index_ty, IntType(), index)
  13298. match tup_ty:
  13299. case TupleType(ts):
  13300. match index:
  13301. case Constant(i):
  13302. return ts[i]
  13303. case _:
  13304. raise Exception('subscript required constant integer index')
  13305. case ListType(ty):
  13306. return ty
  13307. case _:
  13308. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13309. case BinOp(left, Mult(), right):
  13310. l = self.type_check_exp(left, env)
  13311. self.check_type_equal(l, IntType(), left)
  13312. r = self.type_check_exp(right, env)
  13313. self.check_type_equal(r, IntType(), right)
  13314. return IntType()
  13315. case _:
  13316. return super().type_check_exp(e, env)
  13317. \end{lstlisting}
  13318. \fi}
  13319. \end{tcolorbox}
  13320. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13321. \label{fig:type-check-Lvecof}
  13322. \end{figure}
  13323. {\if\edition\pythonEd
  13324. \begin{figure}[tbp]
  13325. \begin{tcolorbox}[colback=white]
  13326. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13327. def type_check_stmts(self, ss, env):
  13328. if len(ss) == 0:
  13329. return VoidType()
  13330. match ss[0]:
  13331. case Assign([Subscript(tup, index, Store())], value):
  13332. tup_t = self.type_check_exp(tup, env)
  13333. value_t = self.type_check_exp(value, env)
  13334. index_ty = self.type_check_exp(index, env)
  13335. self.check_type_equal(index_ty, IntType(), index)
  13336. match tup_t:
  13337. case ListType(ty):
  13338. self.check_type_equal(ty, value_t, ss[0])
  13339. case TupleType(ts):
  13340. return self.type_check_stmts(ss, env)
  13341. case _:
  13342. raise Exception('type_check_stmts: '
  13343. 'expected tuple or list, not ' + repr(tup_t))
  13344. return self.type_check_stmts(ss[1:], env)
  13345. case _:
  13346. return super().type_check_stmts(ss, env)
  13347. \end{lstlisting}
  13348. \end{tcolorbox}
  13349. \caption{Type checker for the \LangArray{} language, part 2.}
  13350. \label{fig:type-check-Lvecof-part2}
  13351. \end{figure}
  13352. \fi}
  13353. The definition of the interpreter for \LangArray{} is shown in
  13354. \racket{figure~\ref{fig:interp-Lvecof}}
  13355. \python{figure~\ref{fig:interp-Lvecof}}.
  13356. \racket{The \code{make-vector} operator is
  13357. interpreted using Racket's \code{make-vector} function,
  13358. and multiplication is interpreted using \code{fx*},
  13359. which is multiplication for \code{fixnum} integers.
  13360. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13361. we translate array access operations
  13362. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13363. which we interpret using \code{vector} operations with additional
  13364. bounds checks that signal a \code{trapped-error}.
  13365. }
  13366. %
  13367. \python{We implement array creation with a Python list comprehension,
  13368. and multiplication is implemented with 64-bit multiplication. We
  13369. add a case for a subscript on the left-hand side of
  13370. assignment. Other uses of subscript can be handled by the existing
  13371. code for tuples.}
  13372. \begin{figure}[tbp]
  13373. \begin{tcolorbox}[colback=white]
  13374. {\if\edition\racketEd
  13375. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13376. (define interp-Lvecof-class
  13377. (class interp-Lvec-class
  13378. (super-new)
  13379. (define/override (interp-op op)
  13380. (match op
  13381. ['make-vector make-vector]
  13382. ['vectorof-length vector-length]
  13383. ['vectorof-ref
  13384. (lambda (v i)
  13385. (if (< i (vector-length v))
  13386. (vector-ref v i)
  13387. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13388. ['vectorof-set!
  13389. (lambda (v i e)
  13390. (if (< i (vector-length v))
  13391. (vector-set! v i e)
  13392. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13393. [else (super interp-op op)]))
  13394. ))
  13395. (define (interp-Lvecof p)
  13396. (send (new interp-Lvecof-class) interp-program p))
  13397. \end{lstlisting}
  13398. \fi}
  13399. {\if\edition\pythonEd\pythonColor
  13400. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13401. class InterpLarray(InterpLtup):
  13402. def interp_exp(self, e, env):
  13403. match e:
  13404. case ast.List(es, Load()):
  13405. return [self.interp_exp(e, env) for e in es]
  13406. case BinOp(left, Mult(), right):
  13407. l = self.interp_exp(left, env)
  13408. r = self.interp_exp(right, env)
  13409. return mul64(l, r)
  13410. case Subscript(tup, index, Load()):
  13411. t = self.interp_exp(tup, env)
  13412. n = self.interp_exp(index, env)
  13413. if n < len(t):
  13414. return t[n]
  13415. else:
  13416. raise TrappedError('array index out of bounds')
  13417. case _:
  13418. return super().interp_exp(e, env)
  13419. def interp_stmt(self, s, env, cont):
  13420. match s:
  13421. case Assign([Subscript(tup, index)], value):
  13422. t = self.interp_exp(tup, env)
  13423. n = self.interp_exp(index, env)
  13424. if n < len(t):
  13425. t[n] = self.interp_exp(value, env)
  13426. else:
  13427. raise TrappedError('array index out of bounds')
  13428. return self.interp_stmts(cont, env)
  13429. case _:
  13430. return super().interp_stmt(s, env, cont)
  13431. \end{lstlisting}
  13432. \fi}
  13433. \end{tcolorbox}
  13434. \caption{Interpreter for \LangArray{}.}
  13435. \label{fig:interp-Lvecof}
  13436. \end{figure}
  13437. \subsection{Data Representation}
  13438. \label{sec:array-rep}
  13439. Just as with tuples, we store arrays on the heap, which means that the
  13440. garbage collector will need to inspect arrays. An immediate thought is
  13441. to use the same representation for arrays that we use for tuples.
  13442. However, we limit tuples to a length of fifty so that their length and
  13443. pointer mask can fit into the 64-bit tag at the beginning of each
  13444. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13445. millions of elements, so we need more bits to store the length.
  13446. However, because arrays are homogeneous, we need only 1 bit for the
  13447. pointer mask instead of 1 bit per array element. Finally, the
  13448. garbage collector must be able to distinguish between tuples
  13449. and arrays, so we need to reserve one bit for that purpose. We
  13450. arrive at the following layout for the 64-bit tag at the beginning of
  13451. an array:
  13452. \begin{itemize}
  13453. \item The right-most bit is the forwarding bit, just as in a tuple.
  13454. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13455. that it is not.
  13456. \item The next bit to the left is the pointer mask. A $0$ indicates
  13457. that none of the elements are pointers, and a $1$ indicates that all
  13458. the elements are pointers.
  13459. \item The next $60$ bits store the length of the array.
  13460. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13461. and an array ($1$).
  13462. \item The left-most bit is reserved as explained in
  13463. chapter~\ref{ch:Lgrad}.
  13464. \end{itemize}
  13465. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13466. %% differentiate the kinds of values that have been injected into the
  13467. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13468. %% to indicate that the value is an array.
  13469. In the following subsections we provide hints regarding how to update
  13470. the passes to handle arrays.
  13471. \subsection{Overload Resolution}
  13472. \label{sec:array-resolution}
  13473. As noted previously, with the addition of arrays, several operators
  13474. have become \emph{overloaded}; that is, they can be applied to values
  13475. of more than one type. In this case, the element access and length
  13476. operators can be applied to both tuples and arrays. This kind of
  13477. overloading is quite common in programming languages, so many
  13478. compilers perform \emph{overload resolution}\index{subject}{overload
  13479. resolution} to handle it. The idea is to translate each overloaded
  13480. operator into different operators for the different types.
  13481. Implement a new pass named \code{resolve}.
  13482. Translate the reading of an array element to
  13483. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13484. and the writing of an array element to
  13485. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13486. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13487. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13488. When these operators are applied to tuples, leave them as is.
  13489. %
  13490. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13491. field, which can be inspected to determine whether the operator
  13492. is applied to a tuple or an array.}
  13493. \subsection{Bounds Checking}
  13494. Recall that the interpreter for \LangArray{} signals a
  13495. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13496. when there is an array access that is out of
  13497. bounds. Therefore your compiler is obliged to also catch these errors
  13498. during execution and halt, signaling an error. We recommend inserting
  13499. a new pass named \code{check\_bounds} that inserts code around each
  13500. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13501. \python{subscript} operation to ensure that the index is greater than
  13502. or equal to zero and less than the array's length. If not, the program
  13503. should halt, for which we recommend using a new primitive operation
  13504. named \code{exit}.
  13505. %% \subsection{Reveal Casts}
  13506. %% The array-access operators \code{vectorof-ref} and
  13507. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13508. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13509. %% that the type checker cannot tell whether the index will be in bounds,
  13510. %% so the bounds check must be performed at run time. Recall that the
  13511. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13512. %% an \code{If} around a vector reference for update to check whether
  13513. %% the index is less than the length. You should do the same for
  13514. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13515. %% In addition, the handling of the \code{any-vector} operators in
  13516. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13517. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13518. %% generated code should test whether the tag is for tuples (\code{010})
  13519. %% or arrays (\code{110}) and then dispatch to either
  13520. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13521. %% we add a case in \code{select\_instructions} to generate the
  13522. %% appropriate instructions for accessing the array length from the
  13523. %% header of an array.
  13524. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13525. %% the generated code needs to check that the index is less than the
  13526. %% vector length, so like the code for \code{any-vector-length}, check
  13527. %% the tag to determine whether to use \code{any-vector-length} or
  13528. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13529. %% is complete, the generated code can use \code{any-vector-ref} and
  13530. %% \code{any-vector-set!} for both tuples and arrays because the
  13531. %% instructions used for those operators do not look at the tag at the
  13532. %% front of the tuple or array.
  13533. \subsection{Expose Allocation}
  13534. This pass should translate array creation into lower-level
  13535. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13536. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13537. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13538. array. The \code{AllocateArray} AST node allocates an array of the
  13539. length specified by the $\Exp$ (of type \INTTY), but does not
  13540. initialize the elements of the array. Generate code in this pass to
  13541. initialize the elements analogous to the case for tuples.
  13542. {\if\edition\racketEd
  13543. \subsection{Uncover \texttt{get!}}
  13544. \label{sec:uncover-get-bang-vecof}
  13545. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13546. \code{uncover-get!-exp}.
  13547. \fi}
  13548. \subsection{Remove Complex Operands}
  13549. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13550. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13551. complex, and its subexpression must be atomic.
  13552. \subsection{Explicate Control}
  13553. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13554. \code{explicate\_assign}.
  13555. \subsection{Select Instructions}
  13556. \index{subject}{select instructions}
  13557. Generate instructions for \code{AllocateArray} similar to those for
  13558. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13559. except that the tag at the front of the array should instead use the
  13560. representation discussed in section~\ref{sec:array-rep}.
  13561. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13562. extract the length from the tag.
  13563. The instructions generated for accessing an element of an array differ
  13564. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13565. that the index is not a constant so you need to generate instructions
  13566. that compute the offset at runtime.
  13567. Compile the \code{exit} primitive into a call to the \code{exit}
  13568. function of the C standard library, with an argument of $255$.
  13569. %% Also, note that assignment to an array element may appear in
  13570. %% as a stand-alone statement, so make sure to handle that situation in
  13571. %% this pass.
  13572. %% Finally, the instructions for \code{any-vectorof-length} should be
  13573. %% similar to those for \code{vectorof-length}, except that one must
  13574. %% first project the array by writing zeroes into the $3$-bit tag
  13575. \begin{exercise}\normalfont\normalsize
  13576. Implement a compiler for the \LangArray{} language by extending your
  13577. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13578. programs, including the one shown in figure~\ref{fig:inner_product}
  13579. and also a program that multiplies two matrices. Note that although
  13580. matrices are two-dimensional arrays, they can be encoded into
  13581. one-dimensional arrays by laying out each row in the array, one after
  13582. the next.
  13583. \end{exercise}
  13584. {\if\edition\racketEd
  13585. \section{Challenge: Generational Collection}
  13586. The copying collector described in section~\ref{sec:GC} can incur
  13587. significant runtime overhead because the call to \code{collect} takes
  13588. time proportional to all the live data. One way to reduce this
  13589. overhead is to reduce how much data is inspected in each call to
  13590. \code{collect}. In particular, researchers have observed that recently
  13591. allocated data is more likely to become garbage then data that has
  13592. survived one or more previous calls to \code{collect}. This insight
  13593. motivated the creation of \emph{generational garbage collectors}
  13594. \index{subject}{generational garbage collector} that
  13595. (1) segregate data according to its age into two or more generations;
  13596. (2) allocate less space for younger generations, so collecting them is
  13597. faster, and more space for the older generations; and (3) perform
  13598. collection on the younger generations more frequently than on older
  13599. generations~\citep{Wilson:1992fk}.
  13600. For this challenge assignment, the goal is to adapt the copying
  13601. collector implemented in \code{runtime.c} to use two generations, one
  13602. for young data and one for old data. Each generation consists of a
  13603. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13604. \code{collect} function to use the two generations:
  13605. \begin{enumerate}
  13606. \item Copy the young generation's FromSpace to its ToSpace and then
  13607. switch the role of the ToSpace and FromSpace.
  13608. \item If there is enough space for the requested number of bytes in
  13609. the young FromSpace, then return from \code{collect}.
  13610. \item If there is not enough space in the young FromSpace for the
  13611. requested bytes, then move the data from the young generation to the
  13612. old one with the following steps:
  13613. \begin{enumerate}
  13614. \item[a.] If there is enough room in the old FromSpace, copy the young
  13615. FromSpace to the old FromSpace and then return.
  13616. \item[b.] If there is not enough room in the old FromSpace, then collect
  13617. the old generation by copying the old FromSpace to the old ToSpace
  13618. and swap the roles of the old FromSpace and ToSpace.
  13619. \item[c.] If there is enough room now, copy the young FromSpace to the
  13620. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13621. and ToSpace for the old generation. Copy the young FromSpace and
  13622. the old FromSpace into the larger FromSpace for the old
  13623. generation and then return.
  13624. \end{enumerate}
  13625. \end{enumerate}
  13626. We recommend that you generalize the \code{cheney} function so that it
  13627. can be used for all the copies mentioned: between the young FromSpace
  13628. and ToSpace, between the old FromSpace and ToSpace, and between the
  13629. young FromSpace and old FromSpace. This can be accomplished by adding
  13630. parameters to \code{cheney} that replace its use of the global
  13631. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13632. \code{tospace\_begin}, and \code{tospace\_end}.
  13633. Note that the collection of the young generation does not traverse the
  13634. old generation. This introduces a potential problem: there may be
  13635. young data that is reachable only through pointers in the old
  13636. generation. If these pointers are not taken into account, the
  13637. collector could throw away young data that is live! One solution,
  13638. called \emph{pointer recording}, is to maintain a set of all the
  13639. pointers from the old generation into the new generation and consider
  13640. this set as part of the root set. To maintain this set, the compiler
  13641. must insert extra instructions around every \code{vector-set!}. If the
  13642. vector being modified is in the old generation, and if the value being
  13643. written is a pointer into the new generation, then that pointer must
  13644. be added to the set. Also, if the value being overwritten was a
  13645. pointer into the new generation, then that pointer should be removed
  13646. from the set.
  13647. \begin{exercise}\normalfont\normalsize
  13648. Adapt the \code{collect} function in \code{runtime.c} to implement
  13649. generational garbage collection, as outlined in this section.
  13650. Update the code generation for \code{vector-set!} to implement
  13651. pointer recording. Make sure that your new compiler and runtime
  13652. execute without error on your test suite.
  13653. \end{exercise}
  13654. \fi}
  13655. \section{Further Reading}
  13656. \citet{Appel90} describes many data representation approaches
  13657. including the ones used in the compilation of Standard ML.
  13658. There are many alternatives to copying collectors (and their bigger
  13659. siblings, the generational collectors) with regard to garbage
  13660. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13661. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13662. collectors are that allocation is fast (just a comparison and pointer
  13663. increment), there is no fragmentation, cyclic garbage is collected,
  13664. and the time complexity of collection depends only on the amount of
  13665. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13666. main disadvantages of a two-space copying collector is that it uses a
  13667. lot of extra space and takes a long time to perform the copy, though
  13668. these problems are ameliorated in generational collectors.
  13669. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13670. small objects and generate a lot of garbage, so copying and
  13671. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13672. Garbage collection is an active research topic, especially concurrent
  13673. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13674. developing new techniques and revisiting old
  13675. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13676. meet every year at the International Symposium on Memory Management to
  13677. present these findings.
  13678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13679. \chapter{Functions}
  13680. \label{ch:Lfun}
  13681. \index{subject}{function}
  13682. \setcounter{footnote}{0}
  13683. This chapter studies the compilation of a subset of \racket{Typed
  13684. Racket}\python{Python} in which only top-level function definitions
  13685. are allowed. This kind of function appears in the C programming
  13686. language, and it serves as an important stepping-stone to implementing
  13687. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13688. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13689. \section{The \LangFun{} Language}
  13690. The concrete syntax and abstract syntax for function definitions and
  13691. function application are shown in
  13692. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13693. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13694. with zero or more function definitions. The function names from these
  13695. definitions are in scope for the entire program, including all the
  13696. function definitions, and therefore the ordering of function
  13697. definitions does not matter.
  13698. %
  13699. \python{The abstract syntax for function parameters in
  13700. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13701. consists of a parameter name and its type. This design differs from
  13702. Python's \code{ast} module, which has a more complex structure for
  13703. function parameters to handle keyword parameters,
  13704. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13705. complex Python abstract syntax into the simpler syntax shown in
  13706. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13707. \code{FunctionDef} constructor are for decorators and a type
  13708. comment, neither of which are used by our compiler. We recommend
  13709. replacing them with \code{None} in the \code{shrink} pass.
  13710. }
  13711. %
  13712. The concrete syntax for function application
  13713. \index{subject}{function application}
  13714. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13715. where the first expression
  13716. must evaluate to a function and the remaining expressions are the arguments. The
  13717. abstract syntax for function application is
  13718. $\APPLY{\Exp}{\Exp^*}$.
  13719. %% The syntax for function application does not include an explicit
  13720. %% keyword, which is error prone when using \code{match}. To alleviate
  13721. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13722. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13723. Functions are first-class in the sense that a function pointer
  13724. \index{subject}{function pointer} is data and can be stored in memory or passed
  13725. as a parameter to another function. Thus, there is a function
  13726. type, written
  13727. {\if\edition\racketEd
  13728. \begin{lstlisting}
  13729. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13730. \end{lstlisting}
  13731. \fi}
  13732. {\if\edition\pythonEd\pythonColor
  13733. \begin{lstlisting}
  13734. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13735. \end{lstlisting}
  13736. \fi}
  13737. %
  13738. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13739. through $\Type_n$ and whose return type is $\Type_R$. The main
  13740. limitation of these functions (with respect to
  13741. \racket{Racket}\python{Python} functions) is that they are not
  13742. lexically scoped. That is, the only external entities that can be
  13743. referenced from inside a function body are other globally defined
  13744. functions. The syntax of \LangFun{} prevents function definitions from
  13745. being nested inside each other.
  13746. \newcommand{\LfunGrammarRacket}{
  13747. \begin{array}{lcl}
  13748. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13749. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13750. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13751. \end{array}
  13752. }
  13753. \newcommand{\LfunASTRacket}{
  13754. \begin{array}{lcl}
  13755. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13756. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13757. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13758. \end{array}
  13759. }
  13760. \newcommand{\LfunGrammarPython}{
  13761. \begin{array}{lcl}
  13762. \Type &::=& \key{int}
  13763. \MID \key{bool} \MID \key{void}
  13764. \MID \key{tuple}\LS \Type^+ \RS
  13765. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13766. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13767. \Stmt &::=& \CRETURN{\Exp} \\
  13768. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13769. \end{array}
  13770. }
  13771. \newcommand{\LfunASTPython}{
  13772. \begin{array}{lcl}
  13773. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13774. \MID \key{TupleType}\LS\Type^+\RS\\
  13775. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13776. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13777. \Stmt &::=& \RETURN{\Exp} \\
  13778. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13779. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13780. \end{array}
  13781. }
  13782. \begin{figure}[tp]
  13783. \centering
  13784. \begin{tcolorbox}[colback=white]
  13785. \small
  13786. {\if\edition\racketEd
  13787. \[
  13788. \begin{array}{l}
  13789. \gray{\LintGrammarRacket{}} \\ \hline
  13790. \gray{\LvarGrammarRacket{}} \\ \hline
  13791. \gray{\LifGrammarRacket{}} \\ \hline
  13792. \gray{\LwhileGrammarRacket} \\ \hline
  13793. \gray{\LtupGrammarRacket} \\ \hline
  13794. \LfunGrammarRacket \\
  13795. \begin{array}{lcl}
  13796. \LangFunM{} &::=& \Def \ldots \; \Exp
  13797. \end{array}
  13798. \end{array}
  13799. \]
  13800. \fi}
  13801. {\if\edition\pythonEd\pythonColor
  13802. \[
  13803. \begin{array}{l}
  13804. \gray{\LintGrammarPython{}} \\ \hline
  13805. \gray{\LvarGrammarPython{}} \\ \hline
  13806. \gray{\LifGrammarPython{}} \\ \hline
  13807. \gray{\LwhileGrammarPython} \\ \hline
  13808. \gray{\LtupGrammarPython} \\ \hline
  13809. \LfunGrammarPython \\
  13810. \begin{array}{rcl}
  13811. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13812. \end{array}
  13813. \end{array}
  13814. \]
  13815. \fi}
  13816. \end{tcolorbox}
  13817. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13818. \label{fig:Lfun-concrete-syntax}
  13819. \end{figure}
  13820. \begin{figure}[tp]
  13821. \centering
  13822. \begin{tcolorbox}[colback=white]
  13823. \small
  13824. {\if\edition\racketEd
  13825. \[
  13826. \begin{array}{l}
  13827. \gray{\LintOpAST} \\ \hline
  13828. \gray{\LvarASTRacket{}} \\ \hline
  13829. \gray{\LifASTRacket{}} \\ \hline
  13830. \gray{\LwhileASTRacket{}} \\ \hline
  13831. \gray{\LtupASTRacket{}} \\ \hline
  13832. \LfunASTRacket \\
  13833. \begin{array}{lcl}
  13834. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13835. \end{array}
  13836. \end{array}
  13837. \]
  13838. \fi}
  13839. {\if\edition\pythonEd\pythonColor
  13840. \[
  13841. \begin{array}{l}
  13842. \gray{\LintASTPython{}} \\ \hline
  13843. \gray{\LvarASTPython{}} \\ \hline
  13844. \gray{\LifASTPython{}} \\ \hline
  13845. \gray{\LwhileASTPython} \\ \hline
  13846. \gray{\LtupASTPython} \\ \hline
  13847. \LfunASTPython \\
  13848. \begin{array}{rcl}
  13849. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13850. \end{array}
  13851. \end{array}
  13852. \]
  13853. \fi}
  13854. \end{tcolorbox}
  13855. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13856. \label{fig:Lfun-syntax}
  13857. \end{figure}
  13858. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13859. representative example of defining and using functions in \LangFun{}.
  13860. We define a function \code{map} that applies some other function
  13861. \code{f} to both elements of a tuple and returns a new tuple
  13862. containing the results. We also define a function \code{inc}. The
  13863. program applies \code{map} to \code{inc} and
  13864. %
  13865. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13866. %
  13867. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13868. %
  13869. from which we return \code{42}.
  13870. \begin{figure}[tbp]
  13871. \begin{tcolorbox}[colback=white]
  13872. {\if\edition\racketEd
  13873. \begin{lstlisting}
  13874. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13875. : (Vector Integer Integer)
  13876. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13877. (define (inc [x : Integer]) : Integer
  13878. (+ x 1))
  13879. (vector-ref (map inc (vector 0 41)) 1)
  13880. \end{lstlisting}
  13881. \fi}
  13882. {\if\edition\pythonEd\pythonColor
  13883. \begin{lstlisting}
  13884. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13885. return f(v[0]), f(v[1])
  13886. def inc(x : int) -> int:
  13887. return x + 1
  13888. print(map(inc, (0, 41))[1])
  13889. \end{lstlisting}
  13890. \fi}
  13891. \end{tcolorbox}
  13892. \caption{Example of using functions in \LangFun{}.}
  13893. \label{fig:Lfun-function-example}
  13894. \end{figure}
  13895. The definitional interpreter for \LangFun{} is shown in
  13896. figure~\ref{fig:interp-Lfun}. The case for the
  13897. %
  13898. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13899. %
  13900. AST is responsible for setting up the mutual recursion between the
  13901. top-level function definitions.
  13902. %
  13903. \racket{We use the classic back-patching
  13904. \index{subject}{back-patching} approach that uses mutable variables
  13905. and makes two passes over the function
  13906. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13907. top-level environment using a mutable cons cell for each function
  13908. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13909. for each function is incomplete; it does not yet include the environment.
  13910. Once the top-level environment has been constructed, we iterate over it and
  13911. update the \code{lambda} values to use the top-level environment.}
  13912. %
  13913. \python{We create a dictionary named \code{env} and fill it in
  13914. by mapping each function name to a new \code{Function} value,
  13915. each of which stores a reference to the \code{env}.
  13916. (We define the class \code{Function} for this purpose.)}
  13917. %
  13918. To interpret a function \racket{application}\python{call}, we match
  13919. the result of the function expression to obtain a function value. We
  13920. then extend the function's environment with the mapping of parameters to
  13921. argument values. Finally, we interpret the body of the function in
  13922. this extended environment.
  13923. \begin{figure}[tp]
  13924. \begin{tcolorbox}[colback=white]
  13925. {\if\edition\racketEd
  13926. \begin{lstlisting}
  13927. (define interp-Lfun-class
  13928. (class interp-Lvec-class
  13929. (super-new)
  13930. (define/override ((interp-exp env) e)
  13931. (define recur (interp-exp env))
  13932. (match e
  13933. [(Apply fun args)
  13934. (define fun-val (recur fun))
  13935. (define arg-vals (for/list ([e args]) (recur e)))
  13936. (match fun-val
  13937. [`(function (,xs ...) ,body ,fun-env)
  13938. (define params-args (for/list ([x xs] [arg arg-vals])
  13939. (cons x (box arg))))
  13940. (define new-env (append params-args fun-env))
  13941. ((interp-exp new-env) body)]
  13942. [else
  13943. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13944. [else ((super interp-exp env) e)]
  13945. ))
  13946. (define/public (interp-def d)
  13947. (match d
  13948. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13949. (cons f (box `(function ,xs ,body ())))]))
  13950. (define/override (interp-program p)
  13951. (match p
  13952. [(ProgramDefsExp info ds body)
  13953. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13954. (for/list ([f (in-dict-values top-level)])
  13955. (set-box! f (match (unbox f)
  13956. [`(function ,xs ,body ())
  13957. `(function ,xs ,body ,top-level)])))
  13958. ((interp-exp top-level) body))]))
  13959. ))
  13960. (define (interp-Lfun p)
  13961. (send (new interp-Lfun-class) interp-program p))
  13962. \end{lstlisting}
  13963. \fi}
  13964. {\if\edition\pythonEd\pythonColor
  13965. \begin{lstlisting}
  13966. class InterpLfun(InterpLtup):
  13967. def apply_fun(self, fun, args, e):
  13968. match fun:
  13969. case Function(name, xs, body, env):
  13970. new_env = env.copy().update(zip(xs, args))
  13971. return self.interp_stmts(body, new_env)
  13972. case _:
  13973. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13974. def interp_exp(self, e, env):
  13975. match e:
  13976. case Call(Name('input_int'), []):
  13977. return super().interp_exp(e, env)
  13978. case Call(func, args):
  13979. f = self.interp_exp(func, env)
  13980. vs = [self.interp_exp(arg, env) for arg in args]
  13981. return self.apply_fun(f, vs, e)
  13982. case _:
  13983. return super().interp_exp(e, env)
  13984. def interp_stmt(self, s, env, cont):
  13985. match s:
  13986. case Return(value):
  13987. return self.interp_exp(value, env)
  13988. case FunctionDef(name, params, bod, dl, returns, comment):
  13989. if isinstance(params, ast.arguments):
  13990. ps = [p.arg for p in params.args]
  13991. else:
  13992. ps = [x for (x,t) in params]
  13993. env[name] = Function(name, ps, bod, env)
  13994. return self.interp_stmts(cont, env)
  13995. case _:
  13996. return super().interp_stmt(s, env, cont)
  13997. def interp(self, p):
  13998. match p:
  13999. case Module(ss):
  14000. env = {}
  14001. self.interp_stmts(ss, env)
  14002. if 'main' in env.keys():
  14003. self.apply_fun(env['main'], [], None)
  14004. case _:
  14005. raise Exception('interp: unexpected ' + repr(p))
  14006. \end{lstlisting}
  14007. \fi}
  14008. \end{tcolorbox}
  14009. \caption{Interpreter for the \LangFun{} language.}
  14010. \label{fig:interp-Lfun}
  14011. \end{figure}
  14012. %\margincomment{TODO: explain type checker}
  14013. The type checker for \LangFun{} is shown in
  14014. figure~\ref{fig:type-check-Lfun}.
  14015. %
  14016. \python{(We omit the code that parses function parameters into the
  14017. simpler abstract syntax.)}
  14018. %
  14019. Similarly to the interpreter, the case for the
  14020. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14021. %
  14022. AST is responsible for setting up the mutual recursion between the
  14023. top-level function definitions. We begin by creating a mapping
  14024. \code{env} from every function name to its type. We then type check
  14025. the program using this mapping.
  14026. %
  14027. \python{To check a function definition, we copy and extend the
  14028. \code{env} with the parameters of the function. We then type check
  14029. the body of the function and obtain the actual return type
  14030. \code{rt}, which is either the type of the expression in a
  14031. \code{return} statement or the \code{VoidType} if control reaches
  14032. the end of the function without a \code{return} statement. (If
  14033. there are multiple \code{return} statements, the types of their
  14034. expressions must agree.) Finally, we check that the actual return
  14035. type \code{rt} is equal to the declared return type \code{returns}.}
  14036. %
  14037. To check a function \racket{application}\python{call}, we match
  14038. the type of the function expression to a function type and check that
  14039. the types of the argument expressions are equal to the function's
  14040. parameter types. The type of the \racket{application}\python{call} as
  14041. a whole is the return type from the function type.
  14042. \begin{figure}[tp]
  14043. \begin{tcolorbox}[colback=white]
  14044. {\if\edition\racketEd
  14045. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14046. (define type-check-Lfun-class
  14047. (class type-check-Lvec-class
  14048. (super-new)
  14049. (inherit check-type-equal?)
  14050. (define/public (type-check-apply env e es)
  14051. (define-values (e^ ty) ((type-check-exp env) e))
  14052. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14053. ((type-check-exp env) e)))
  14054. (match ty
  14055. [`(,ty^* ... -> ,rt)
  14056. (for ([arg-ty ty*] [param-ty ty^*])
  14057. (check-type-equal? arg-ty param-ty (Apply e es)))
  14058. (values e^ e* rt)]))
  14059. (define/override (type-check-exp env)
  14060. (lambda (e)
  14061. (match e
  14062. [(FunRef f n)
  14063. (values (FunRef f n) (dict-ref env f))]
  14064. [(Apply e es)
  14065. (define-values (e^ es^ rt) (type-check-apply env e es))
  14066. (values (Apply e^ es^) rt)]
  14067. [(Call e es)
  14068. (define-values (e^ es^ rt) (type-check-apply env e es))
  14069. (values (Call e^ es^) rt)]
  14070. [else ((super type-check-exp env) e)])))
  14071. (define/public (type-check-def env)
  14072. (lambda (e)
  14073. (match e
  14074. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14075. (define new-env (append (map cons xs ps) env))
  14076. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14077. (check-type-equal? ty^ rt body)
  14078. (Def f p:t* rt info body^)])))
  14079. (define/public (fun-def-type d)
  14080. (match d
  14081. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14082. (define/override (type-check-program e)
  14083. (match e
  14084. [(ProgramDefsExp info ds body)
  14085. (define env (for/list ([d ds])
  14086. (cons (Def-name d) (fun-def-type d))))
  14087. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14088. (define-values (body^ ty) ((type-check-exp env) body))
  14089. (check-type-equal? ty 'Integer body)
  14090. (ProgramDefsExp info ds^ body^)]))))
  14091. (define (type-check-Lfun p)
  14092. (send (new type-check-Lfun-class) type-check-program p))
  14093. \end{lstlisting}
  14094. \fi}
  14095. {\if\edition\pythonEd\pythonColor
  14096. \begin{lstlisting}
  14097. class TypeCheckLfun(TypeCheckLtup):
  14098. def type_check_exp(self, e, env):
  14099. match e:
  14100. case Call(Name('input_int'), []):
  14101. return super().type_check_exp(e, env)
  14102. case Call(func, args):
  14103. func_t = self.type_check_exp(func, env)
  14104. args_t = [self.type_check_exp(arg, env) for arg in args]
  14105. match func_t:
  14106. case FunctionType(params_t, return_t):
  14107. for (arg_t, param_t) in zip(args_t, params_t):
  14108. check_type_equal(param_t, arg_t, e)
  14109. return return_t
  14110. case _:
  14111. raise Exception('type_check_exp: in call, unexpected ' +
  14112. repr(func_t))
  14113. case _:
  14114. return super().type_check_exp(e, env)
  14115. def type_check_stmts(self, ss, env):
  14116. if len(ss) == 0:
  14117. return VoidType()
  14118. match ss[0]:
  14119. case FunctionDef(name, params, body, dl, returns, comment):
  14120. new_env = env.copy().update(params)
  14121. rt = self.type_check_stmts(body, new_env)
  14122. check_type_equal(returns, rt, ss[0])
  14123. return self.type_check_stmts(ss[1:], env)
  14124. case Return(value):
  14125. return self.type_check_exp(value, env)
  14126. case _:
  14127. return super().type_check_stmts(ss, env)
  14128. def type_check(self, p):
  14129. match p:
  14130. case Module(body):
  14131. env = {}
  14132. for s in body:
  14133. match s:
  14134. case FunctionDef(name, params, bod, dl, returns, comment):
  14135. if name in env:
  14136. raise Exception('type_check: function ' +
  14137. repr(name) + ' defined twice')
  14138. params_t = [t for (x,t) in params]
  14139. env[name] = FunctionType(params_t, returns)
  14140. self.type_check_stmts(body, env)
  14141. case _:
  14142. raise Exception('type_check: unexpected ' + repr(p))
  14143. \end{lstlisting}
  14144. \fi}
  14145. \end{tcolorbox}
  14146. \caption{Type checker for the \LangFun{} language.}
  14147. \label{fig:type-check-Lfun}
  14148. \end{figure}
  14149. \clearpage
  14150. \section{Functions in x86}
  14151. \label{sec:fun-x86}
  14152. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14153. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14154. %% \margincomment{\tiny Talk about the return address on the
  14155. %% stack and what callq and retq does.\\ --Jeremy }
  14156. The x86 architecture provides a few features to support the
  14157. implementation of functions. We have already seen that there are
  14158. labels in x86 so that one can refer to the location of an instruction,
  14159. as is needed for jump instructions. Labels can also be used to mark
  14160. the beginning of the instructions for a function. Going further, we
  14161. can obtain the address of a label by using the \key{leaq}
  14162. instruction. For example, the following puts the address of the
  14163. \code{inc} label into the \code{rbx} register:
  14164. \begin{lstlisting}
  14165. leaq inc(%rip), %rbx
  14166. \end{lstlisting}
  14167. Recall from section~\ref{sec:select-instructions-gc} that
  14168. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14169. addressing.
  14170. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14171. to functions whose locations were given by a label, such as
  14172. \code{read\_int}. To support function calls in this chapter we instead
  14173. jump to functions whose location are given by an address in
  14174. a register; that is, we use \emph{indirect function calls}. The
  14175. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14176. before the register name.\index{subject}{indirect function call}
  14177. \begin{lstlisting}
  14178. callq *%rbx
  14179. \end{lstlisting}
  14180. \subsection{Calling Conventions}
  14181. \label{sec:calling-conventions-fun}
  14182. \index{subject}{calling conventions}
  14183. The \code{callq} instruction provides partial support for implementing
  14184. functions: it pushes the return address on the stack and it jumps to
  14185. the target. However, \code{callq} does not handle
  14186. \begin{enumerate}
  14187. \item parameter passing,
  14188. \item pushing frames on the procedure call stack and popping them off,
  14189. or
  14190. \item determining how registers are shared by different functions.
  14191. \end{enumerate}
  14192. Regarding parameter passing, recall that the x86-64 calling
  14193. convention for Unix-based systems uses the following six registers to
  14194. pass arguments to a function, in the given order:
  14195. \begin{lstlisting}
  14196. rdi rsi rdx rcx r8 r9
  14197. \end{lstlisting}
  14198. If there are more than six arguments, then the calling convention
  14199. mandates using space on the frame of the caller for the rest of the
  14200. arguments. However, to ease the implementation of efficient tail calls
  14201. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14202. arguments.
  14203. %
  14204. The return value of the function is stored in register \code{rax}.
  14205. Regarding frames \index{subject}{frame} and the procedure call stack,
  14206. \index{subject}{procedure call stack} recall from
  14207. section~\ref{sec:x86} that the stack grows down and each function call
  14208. uses a chunk of space on the stack called a frame. The caller sets the
  14209. stack pointer, register \code{rsp}, to the last data item in its
  14210. frame. The callee must not change anything in the caller's frame, that
  14211. is, anything that is at or above the stack pointer. The callee is free
  14212. to use locations that are below the stack pointer.
  14213. Recall that we store variables of tuple type on the root stack. So,
  14214. the prelude\index{subject}{prelude} of a function needs to move the
  14215. root stack pointer \code{r15} up according to the number of variables
  14216. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14217. move the root stack pointer back down. Also, the prelude must
  14218. initialize to \code{0} this frame's slots in the root stack to signal
  14219. to the garbage collector that those slots do not yet contain a valid
  14220. pointer. Otherwise the garbage collector will interpret the garbage
  14221. bits in those slots as memory addresses and try to traverse them,
  14222. causing serious mayhem!
  14223. Regarding the sharing of registers between different functions, recall
  14224. from section~\ref{sec:calling-conventions} that the registers are
  14225. divided into two groups, the caller-saved registers and the
  14226. callee-saved registers. The caller should assume that all the
  14227. caller-saved registers are overwritten with arbitrary values by the
  14228. callee. For that reason we recommend in
  14229. section~\ref{sec:calling-conventions} that variables that are live
  14230. during a function call should not be assigned to caller-saved
  14231. registers.
  14232. On the flip side, if the callee wants to use a callee-saved register,
  14233. the callee must save the contents of those registers on their stack
  14234. frame and then put them back prior to returning to the caller. For
  14235. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14236. the register allocator assigns a variable to a callee-saved register,
  14237. then the prelude of the \code{main} function must save that register
  14238. to the stack and the conclusion of \code{main} must restore it. This
  14239. recommendation now generalizes to all functions.
  14240. Recall that the base pointer, register \code{rbp}, is used as a
  14241. point of reference within a frame, so that each local variable can be
  14242. accessed at a fixed offset from the base pointer
  14243. (section~\ref{sec:x86}).
  14244. %
  14245. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14246. frames.
  14247. \begin{figure}[tbp]
  14248. \centering
  14249. \begin{tcolorbox}[colback=white]
  14250. \begin{tabular}{r|r|l|l} \hline
  14251. Caller View & Callee View & Contents & Frame \\ \hline
  14252. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14253. 0(\key{\%rbp}) & & old \key{rbp} \\
  14254. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14255. \ldots & & \ldots \\
  14256. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14257. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14258. \ldots & & \ldots \\
  14259. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14260. %% & & \\
  14261. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14262. %% & \ldots & \ldots \\
  14263. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14264. \hline
  14265. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14266. & 0(\key{\%rbp}) & old \key{rbp} \\
  14267. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14268. & \ldots & \ldots \\
  14269. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14270. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14271. & \ldots & \ldots \\
  14272. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14273. \end{tabular}
  14274. \end{tcolorbox}
  14275. \caption{Memory layout of caller and callee frames.}
  14276. \label{fig:call-frames}
  14277. \end{figure}
  14278. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14279. %% local variables and for storing the values of callee-saved registers
  14280. %% (we shall refer to all of these collectively as ``locals''), and that
  14281. %% at the beginning of a function we move the stack pointer \code{rsp}
  14282. %% down to make room for them.
  14283. %% We recommend storing the local variables
  14284. %% first and then the callee-saved registers, so that the local variables
  14285. %% can be accessed using \code{rbp} the same as before the addition of
  14286. %% functions.
  14287. %% To make additional room for passing arguments, we shall
  14288. %% move the stack pointer even further down. We count how many stack
  14289. %% arguments are needed for each function call that occurs inside the
  14290. %% body of the function and find their maximum. Adding this number to the
  14291. %% number of locals gives us how much the \code{rsp} should be moved at
  14292. %% the beginning of the function. In preparation for a function call, we
  14293. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14294. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14295. %% so on.
  14296. %% Upon calling the function, the stack arguments are retrieved by the
  14297. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14298. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14299. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14300. %% the layout of the caller and callee frames. Notice how important it is
  14301. %% that we correctly compute the maximum number of arguments needed for
  14302. %% function calls; if that number is too small then the arguments and
  14303. %% local variables will smash into each other!
  14304. \subsection{Efficient Tail Calls}
  14305. \label{sec:tail-call}
  14306. In general, the amount of stack space used by a program is determined
  14307. by the longest chain of nested function calls. That is, if function
  14308. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14309. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14310. large if functions are recursive. However, in some cases we can
  14311. arrange to use only a constant amount of space for a long chain of
  14312. nested function calls.
  14313. A \emph{tail call}\index{subject}{tail call} is a function call that
  14314. happens as the last action in a function body. For example, in the
  14315. following program, the recursive call to \code{tail\_sum} is a tail
  14316. call:
  14317. \begin{center}
  14318. {\if\edition\racketEd
  14319. \begin{lstlisting}
  14320. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14321. (if (eq? n 0)
  14322. r
  14323. (tail_sum (- n 1) (+ n r))))
  14324. (+ (tail_sum 3 0) 36)
  14325. \end{lstlisting}
  14326. \fi}
  14327. {\if\edition\pythonEd\pythonColor
  14328. \begin{lstlisting}
  14329. def tail_sum(n : int, r : int) -> int:
  14330. if n == 0:
  14331. return r
  14332. else:
  14333. return tail_sum(n - 1, n + r)
  14334. print(tail_sum(3, 0) + 36)
  14335. \end{lstlisting}
  14336. \fi}
  14337. \end{center}
  14338. At a tail call, the frame of the caller is no longer needed, so we can
  14339. pop the caller's frame before making the tail
  14340. call. \index{subject}{frame} With this approach, a recursive function
  14341. that makes only tail calls ends up using a constant amount of stack
  14342. space. \racket{Functional languages like Racket rely heavily on
  14343. recursive functions, so the definition of Racket \emph{requires}
  14344. that all tail calls be optimized in this way.}
  14345. Some care is needed with regard to argument passing in tail calls. As
  14346. mentioned, for arguments beyond the sixth, the convention is to use
  14347. space in the caller's frame for passing arguments. However, for a
  14348. tail call we pop the caller's frame and can no longer use it. An
  14349. alternative is to use space in the callee's frame for passing
  14350. arguments. However, this option is also problematic because the caller
  14351. and callee's frames overlap in memory. As we begin to copy the
  14352. arguments from their sources in the caller's frame, the target
  14353. locations in the callee's frame might collide with the sources for
  14354. later arguments! We solve this problem by using the heap instead of
  14355. the stack for passing more than six arguments
  14356. (section~\ref{sec:limit-functions-r4}).
  14357. As mentioned, for a tail call we pop the caller's frame prior to
  14358. making the tail call. The instructions for popping a frame are the
  14359. instructions that we usually place in the conclusion of a
  14360. function. Thus, we also need to place such code immediately before
  14361. each tail call. These instructions include restoring the callee-saved
  14362. registers, so it is fortunate that the argument passing registers are
  14363. all caller-saved registers.
  14364. One note remains regarding which instruction to use to make the tail
  14365. call. When the callee is finished, it should not return to the current
  14366. function but instead return to the function that called the current
  14367. one. Thus, the return address that is already on the stack is the
  14368. right one, and we should not use \key{callq} to make the tail call
  14369. because that would overwrite the return address. Instead we simply use
  14370. the \key{jmp} instruction. As with the indirect function call, we write
  14371. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14372. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14373. jump target because the conclusion can overwrite just about everything
  14374. else.
  14375. \begin{lstlisting}
  14376. jmp *%rax
  14377. \end{lstlisting}
  14378. \section{Shrink \LangFun{}}
  14379. \label{sec:shrink-r4}
  14380. The \code{shrink} pass performs a minor modification to ease the
  14381. later passes. This pass introduces an explicit \code{main} function
  14382. that gobbles up all the top-level statements of the module.
  14383. %
  14384. \racket{It also changes the top \code{ProgramDefsExp} form to
  14385. \code{ProgramDefs}.}
  14386. {\if\edition\racketEd
  14387. \begin{lstlisting}
  14388. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14389. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14390. \end{lstlisting}
  14391. where $\itm{mainDef}$ is
  14392. \begin{lstlisting}
  14393. (Def 'main '() 'Integer '() |$\Exp'$|)
  14394. \end{lstlisting}
  14395. \fi}
  14396. {\if\edition\pythonEd\pythonColor
  14397. \begin{lstlisting}
  14398. Module(|$\Def\ldots\Stmt\ldots$|)
  14399. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14400. \end{lstlisting}
  14401. where $\itm{mainDef}$ is
  14402. \begin{lstlisting}
  14403. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14404. \end{lstlisting}
  14405. \fi}
  14406. \section{Reveal Functions and the \LangFunRef{} Language}
  14407. \label{sec:reveal-functions-r4}
  14408. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14409. in that it conflates the use of function names and local
  14410. variables. This is a problem because we need to compile the use of a
  14411. function name differently from the use of a local variable. In
  14412. particular, we use \code{leaq} to convert the function name (a label
  14413. in x86) to an address in a register. Thus, we create a new pass that
  14414. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14415. $n$ is the arity of the function.\python{\footnote{The arity is not
  14416. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14417. This pass is named \code{reveal\_functions} and the output language
  14418. is \LangFunRef{}.
  14419. %is defined in figure~\ref{fig:f1-syntax}.
  14420. %% The concrete syntax for a
  14421. %% function reference is $\CFUNREF{f}$.
  14422. %% \begin{figure}[tp]
  14423. %% \centering
  14424. %% \fbox{
  14425. %% \begin{minipage}{0.96\textwidth}
  14426. %% {\if\edition\racketEd
  14427. %% \[
  14428. %% \begin{array}{lcl}
  14429. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14430. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14431. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14432. %% \end{array}
  14433. %% \]
  14434. %% \fi}
  14435. %% {\if\edition\pythonEd\pythonColor
  14436. %% \[
  14437. %% \begin{array}{lcl}
  14438. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14439. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14440. %% \end{array}
  14441. %% \]
  14442. %% \fi}
  14443. %% \end{minipage}
  14444. %% }
  14445. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14446. %% (figure~\ref{fig:Lfun-syntax}).}
  14447. %% \label{fig:f1-syntax}
  14448. %% \end{figure}
  14449. %% Distinguishing between calls in tail position and non-tail position
  14450. %% requires the pass to have some notion of context. We recommend using
  14451. %% two mutually recursive functions, one for processing expressions in
  14452. %% tail position and another for the rest.
  14453. \racket{Placing this pass after \code{uniquify} will make sure that
  14454. there are no local variables and functions that share the same
  14455. name.}
  14456. %
  14457. The \code{reveal\_functions} pass should come before the
  14458. \code{remove\_complex\_operands} pass because function references
  14459. should be categorized as complex expressions.
  14460. \section{Limit Functions}
  14461. \label{sec:limit-functions-r4}
  14462. Recall that we wish to limit the number of function parameters to six
  14463. so that we do not need to use the stack for argument passing, which
  14464. makes it easier to implement efficient tail calls. However, because
  14465. the input language \LangFun{} supports arbitrary numbers of function
  14466. arguments, we have some work to do! The \code{limit\_functions} pass
  14467. transforms functions and function calls that involve more than six
  14468. arguments to pass the first five arguments as usual, but it packs the
  14469. rest of the arguments into a tuple and passes it as the sixth
  14470. argument.\footnote{The implementation this pass can be postponed to
  14471. last because you can test the rest of the passes on functions with
  14472. six or fewer parameters.}
  14473. Each function definition with seven or more parameters is transformed as
  14474. follows:
  14475. {\if\edition\racketEd
  14476. \begin{lstlisting}
  14477. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14478. |$\Rightarrow$|
  14479. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14480. \end{lstlisting}
  14481. \fi}
  14482. {\if\edition\pythonEd\pythonColor
  14483. \begin{lstlisting}
  14484. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14485. |$\Rightarrow$|
  14486. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14487. |$T_r$|, None, |$\itm{body}'$|, None)
  14488. \end{lstlisting}
  14489. \fi}
  14490. %
  14491. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14492. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14493. the $k$th element of the tuple, where $k = i - 6$.
  14494. %
  14495. {\if\edition\racketEd
  14496. \begin{lstlisting}
  14497. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14498. \end{lstlisting}
  14499. \fi}
  14500. {\if\edition\pythonEd\pythonColor
  14501. \begin{lstlisting}
  14502. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14503. \end{lstlisting}
  14504. \fi}
  14505. For function calls with too many arguments, the \code{limit\_functions}
  14506. pass transforms them in the following way:
  14507. \begin{tabular}{lll}
  14508. \begin{minipage}{0.3\textwidth}
  14509. {\if\edition\racketEd
  14510. \begin{lstlisting}
  14511. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14512. \end{lstlisting}
  14513. \fi}
  14514. {\if\edition\pythonEd\pythonColor
  14515. \begin{lstlisting}
  14516. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14517. \end{lstlisting}
  14518. \fi}
  14519. \end{minipage}
  14520. &
  14521. $\Rightarrow$
  14522. &
  14523. \begin{minipage}{0.5\textwidth}
  14524. {\if\edition\racketEd
  14525. \begin{lstlisting}
  14526. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14527. \end{lstlisting}
  14528. \fi}
  14529. {\if\edition\pythonEd\pythonColor
  14530. \begin{lstlisting}
  14531. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14532. \end{lstlisting}
  14533. \fi}
  14534. \end{minipage}
  14535. \end{tabular}
  14536. \section{Remove Complex Operands}
  14537. \label{sec:rco-r4}
  14538. The primary decisions to make for this pass are whether to classify
  14539. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14540. atomic or complex expressions. Recall that an atomic expression
  14541. ends up as an immediate argument of an x86 instruction. Function
  14542. application translates to a sequence of instructions, so
  14543. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14544. a complex expression. On the other hand, the arguments of
  14545. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14546. expressions.
  14547. %
  14548. Regarding \code{FunRef}, as discussed previously, the function label
  14549. needs to be converted to an address using the \code{leaq}
  14550. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14551. needs to be classified as a complex expression so that we generate an
  14552. assignment statement with a left-hand side that can serve as the
  14553. target of the \code{leaq}.
  14554. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14555. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14556. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14557. and augments programs to include a list of function definitions.
  14558. %
  14559. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14560. \newcommand{\LfunMonadASTRacket}{
  14561. \begin{array}{lcl}
  14562. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14563. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14564. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14565. \end{array}
  14566. }
  14567. \newcommand{\LfunMonadASTPython}{
  14568. \begin{array}{lcl}
  14569. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14570. \MID \key{TupleType}\LS\Type^+\RS\\
  14571. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14572. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14573. \Stmt &::=& \RETURN{\Exp} \\
  14574. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14575. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14576. \end{array}
  14577. }
  14578. \begin{figure}[tp]
  14579. \centering
  14580. \begin{tcolorbox}[colback=white]
  14581. \footnotesize
  14582. {\if\edition\racketEd
  14583. \[
  14584. \begin{array}{l}
  14585. \gray{\LvarMonadASTRacket} \\ \hline
  14586. \gray{\LifMonadASTRacket} \\ \hline
  14587. \gray{\LwhileMonadASTRacket} \\ \hline
  14588. \gray{\LtupMonadASTRacket} \\ \hline
  14589. \LfunMonadASTRacket \\
  14590. \begin{array}{rcl}
  14591. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14592. \end{array}
  14593. \end{array}
  14594. \]
  14595. \fi}
  14596. {\if\edition\pythonEd\pythonColor
  14597. \[
  14598. \begin{array}{l}
  14599. \gray{\LvarMonadASTPython} \\ \hline
  14600. \gray{\LifMonadASTPython} \\ \hline
  14601. \gray{\LwhileMonadASTPython} \\ \hline
  14602. \gray{\LtupMonadASTPython} \\ \hline
  14603. \LfunMonadASTPython \\
  14604. \begin{array}{rcl}
  14605. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14606. \end{array}
  14607. \end{array}
  14608. \]
  14609. \fi}
  14610. \end{tcolorbox}
  14611. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14612. \label{fig:Lfun-anf-syntax}
  14613. \end{figure}
  14614. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14615. %% \LangFunANF{} of this pass.
  14616. %% \begin{figure}[tp]
  14617. %% \centering
  14618. %% \fbox{
  14619. %% \begin{minipage}{0.96\textwidth}
  14620. %% \small
  14621. %% \[
  14622. %% \begin{array}{rcl}
  14623. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14624. %% \MID \VOID{} } \\
  14625. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14626. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14627. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14628. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14629. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14630. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14631. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14632. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14633. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14634. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14635. %% \end{array}
  14636. %% \]
  14637. %% \end{minipage}
  14638. %% }
  14639. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14640. %% \label{fig:Lfun-anf-syntax}
  14641. %% \end{figure}
  14642. \section{Explicate Control and the \LangCFun{} Language}
  14643. \label{sec:explicate-control-r4}
  14644. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14645. output of \code{explicate\_control}.
  14646. %
  14647. %% \racket{(The concrete syntax is given in
  14648. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14649. %
  14650. The auxiliary functions for assignment\racket{ and tail contexts} should
  14651. be updated with cases for
  14652. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14653. function for predicate context should be updated for
  14654. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14655. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14656. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14657. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14658. auxiliary function for processing function definitions. This code is
  14659. similar to the case for \code{Program} in \LangVec{}. The top-level
  14660. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14661. form of \LangFun{} can then apply this new function to all the
  14662. function definitions.
  14663. {\if\edition\pythonEd\pythonColor
  14664. The translation of \code{Return} statements requires a new auxiliary
  14665. function to handle expressions in tail context, called
  14666. \code{explicate\_tail}. The function should take an expression and the
  14667. dictionary of basic blocks and produce a list of statements in the
  14668. \LangCFun{} language. The \code{explicate\_tail} function should
  14669. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14670. and a default case for other kinds of expressions. The default case
  14671. should produce a \code{Return} statement. The case for \code{Call}
  14672. should change it into \code{TailCall}. The other cases should
  14673. recursively process their subexpressions and statements, choosing the
  14674. appropriate explicate functions for the various contexts.
  14675. \fi}
  14676. \newcommand{\CfunASTRacket}{
  14677. \begin{array}{lcl}
  14678. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14679. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14680. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14681. \end{array}
  14682. }
  14683. \newcommand{\CfunASTPython}{
  14684. \begin{array}{lcl}
  14685. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14686. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14687. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14688. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14689. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14690. \end{array}
  14691. }
  14692. \begin{figure}[tp]
  14693. \begin{tcolorbox}[colback=white]
  14694. \footnotesize
  14695. {\if\edition\racketEd
  14696. \[
  14697. \begin{array}{l}
  14698. \gray{\CvarASTRacket} \\ \hline
  14699. \gray{\CifASTRacket} \\ \hline
  14700. \gray{\CloopASTRacket} \\ \hline
  14701. \gray{\CtupASTRacket} \\ \hline
  14702. \CfunASTRacket \\
  14703. \begin{array}{lcl}
  14704. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14705. \end{array}
  14706. \end{array}
  14707. \]
  14708. \fi}
  14709. {\if\edition\pythonEd\pythonColor
  14710. \[
  14711. \begin{array}{l}
  14712. \gray{\CifASTPython} \\ \hline
  14713. \gray{\CtupASTPython} \\ \hline
  14714. \CfunASTPython \\
  14715. \begin{array}{lcl}
  14716. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14717. \end{array}
  14718. \end{array}
  14719. \]
  14720. \fi}
  14721. \end{tcolorbox}
  14722. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14723. \label{fig:c3-syntax}
  14724. \end{figure}
  14725. \clearpage
  14726. \section{Select Instructions and the \LangXIndCall{} Language}
  14727. \label{sec:select-r4}
  14728. \index{subject}{select instructions}
  14729. The output of select instructions is a program in the \LangXIndCall{}
  14730. language; the definition of its concrete syntax is shown in
  14731. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14732. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14733. directive on the labels of function definitions to make sure the
  14734. bottom three bits are zero, which we put to use in
  14735. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14736. this section. \index{subject}{x86}
  14737. \newcommand{\GrammarXIndCall}{
  14738. \begin{array}{lcl}
  14739. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14740. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14741. \Block &::= & \Instr^{+} \\
  14742. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14743. \end{array}
  14744. }
  14745. \newcommand{\ASTXIndCallRacket}{
  14746. \begin{array}{lcl}
  14747. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14748. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14749. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14750. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14751. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14752. \end{array}
  14753. }
  14754. \begin{figure}[tp]
  14755. \begin{tcolorbox}[colback=white]
  14756. \small
  14757. \[
  14758. \begin{array}{l}
  14759. \gray{\GrammarXInt} \\ \hline
  14760. \gray{\GrammarXIf} \\ \hline
  14761. \gray{\GrammarXGlobal} \\ \hline
  14762. \GrammarXIndCall \\
  14763. \begin{array}{lcl}
  14764. \LangXIndCallM{} &::= & \Def^{*}
  14765. \end{array}
  14766. \end{array}
  14767. \]
  14768. \end{tcolorbox}
  14769. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14770. \label{fig:x86-3-concrete}
  14771. \end{figure}
  14772. \begin{figure}[tp]
  14773. \begin{tcolorbox}[colback=white]
  14774. \small
  14775. {\if\edition\racketEd
  14776. \[\arraycolsep=3pt
  14777. \begin{array}{l}
  14778. \gray{\ASTXIntRacket} \\ \hline
  14779. \gray{\ASTXIfRacket} \\ \hline
  14780. \gray{\ASTXGlobalRacket} \\ \hline
  14781. \ASTXIndCallRacket \\
  14782. \begin{array}{lcl}
  14783. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14784. \end{array}
  14785. \end{array}
  14786. \]
  14787. \fi}
  14788. {\if\edition\pythonEd\pythonColor
  14789. \[
  14790. \begin{array}{lcl}
  14791. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14792. \MID \BYTEREG{\Reg} } \\
  14793. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14794. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14795. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14796. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14797. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14798. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14799. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14800. \end{array}
  14801. \]
  14802. \fi}
  14803. \end{tcolorbox}
  14804. \caption{The abstract syntax of \LangXIndCall{} (extends
  14805. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14806. \label{fig:x86-3}
  14807. \end{figure}
  14808. An assignment of a function reference to a variable becomes a
  14809. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14810. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14811. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14812. node, whose concrete syntax is instruction-pointer-relative
  14813. addressing.
  14814. \begin{center}
  14815. \begin{tabular}{lcl}
  14816. \begin{minipage}{0.35\textwidth}
  14817. {\if\edition\racketEd
  14818. \begin{lstlisting}
  14819. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14820. \end{lstlisting}
  14821. \fi}
  14822. {\if\edition\pythonEd\pythonColor
  14823. \begin{lstlisting}
  14824. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14825. \end{lstlisting}
  14826. \fi}
  14827. \end{minipage}
  14828. &
  14829. $\Rightarrow$\qquad\qquad
  14830. &
  14831. \begin{minipage}{0.3\textwidth}
  14832. \begin{lstlisting}
  14833. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14834. \end{lstlisting}
  14835. \end{minipage}
  14836. \end{tabular}
  14837. \end{center}
  14838. Regarding function definitions, we need to remove the parameters and
  14839. instead perform parameter passing using the conventions discussed in
  14840. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14841. registers. We recommend turning the parameters into local variables
  14842. and generating instructions at the beginning of the function to move
  14843. from the argument-passing registers
  14844. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14845. {\if\edition\racketEd
  14846. \begin{lstlisting}
  14847. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14848. |$\Rightarrow$|
  14849. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14850. \end{lstlisting}
  14851. \fi}
  14852. {\if\edition\pythonEd\pythonColor
  14853. \begin{lstlisting}
  14854. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14855. |$\Rightarrow$|
  14856. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14857. \end{lstlisting}
  14858. \fi}
  14859. The basic blocks $B'$ are the same as $B$ except that the
  14860. \code{start} block is modified to add the instructions for moving from
  14861. the argument registers to the parameter variables. So the \code{start}
  14862. block of $B$ shown on the left of the following is changed to the code
  14863. on the right:
  14864. \begin{center}
  14865. \begin{minipage}{0.3\textwidth}
  14866. \begin{lstlisting}
  14867. start:
  14868. |$\itm{instr}_1$|
  14869. |$\cdots$|
  14870. |$\itm{instr}_n$|
  14871. \end{lstlisting}
  14872. \end{minipage}
  14873. $\Rightarrow$
  14874. \begin{minipage}{0.3\textwidth}
  14875. \begin{lstlisting}
  14876. |$f$|start:
  14877. movq %rdi, |$x_1$|
  14878. movq %rsi, |$x_2$|
  14879. |$\cdots$|
  14880. |$\itm{instr}_1$|
  14881. |$\cdots$|
  14882. |$\itm{instr}_n$|
  14883. \end{lstlisting}
  14884. \end{minipage}
  14885. \end{center}
  14886. Recall that we use the label \code{start} for the initial block of a
  14887. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14888. the conclusion of the program with \code{conclusion}, so that
  14889. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14890. by a jump to \code{conclusion}. With the addition of function
  14891. definitions, there is a start block and conclusion for each function,
  14892. but their labels need to be unique. We recommend prepending the
  14893. function's name to \code{start} and \code{conclusion}, respectively,
  14894. to obtain unique labels.
  14895. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14896. number of parameters the function expects, but the parameters are no
  14897. longer in the syntax of function definitions. Instead, add an entry
  14898. to $\itm{info}$ that maps \code{num-params} to the number of
  14899. parameters to construct $\itm{info}'$.}
  14900. By changing the parameters to local variables, we are giving the
  14901. register allocator control over which registers or stack locations to
  14902. use for them. If you implement the move-biasing challenge
  14903. (section~\ref{sec:move-biasing}), the register allocator will try to
  14904. assign the parameter variables to the corresponding argument register,
  14905. in which case the \code{patch\_instructions} pass will remove the
  14906. \code{movq} instruction. This happens in the example translation given
  14907. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14908. the \code{add} function.
  14909. %
  14910. Also, note that the register allocator will perform liveness analysis
  14911. on this sequence of move instructions and build the interference
  14912. graph. So, for example, $x_1$ will be marked as interfering with
  14913. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14914. which is good because otherwise the first \code{movq} would overwrite
  14915. the argument in \code{rsi} that is needed for $x_2$.
  14916. Next, consider the compilation of function calls. In the mirror image
  14917. of the handling of parameters in function definitions, the arguments
  14918. are moved to the argument-passing registers. Note that the function
  14919. is not given as a label, but its address is produced by the argument
  14920. $\itm{arg}_0$. So, we translate the call into an indirect function
  14921. call. The return value from the function is stored in \code{rax}, so
  14922. it needs to be moved into the \itm{lhs}.
  14923. \begin{lstlisting}
  14924. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14925. |$\Rightarrow$|
  14926. movq |$\itm{arg}_1$|, %rdi
  14927. movq |$\itm{arg}_2$|, %rsi
  14928. |$\vdots$|
  14929. callq *|$\itm{arg}_0$|
  14930. movq %rax, |$\itm{lhs}$|
  14931. \end{lstlisting}
  14932. The \code{IndirectCallq} AST node includes an integer for the arity of
  14933. the function, that is, the number of parameters. That information is
  14934. useful in the \code{uncover\_live} pass for determining which
  14935. argument-passing registers are potentially read during the call.
  14936. For tail calls, the parameter passing is the same as non-tail calls:
  14937. generate instructions to move the arguments into the argument-passing
  14938. registers. After that we need to pop the frame from the procedure
  14939. call stack. However, we do not yet know how big the frame is; that
  14940. gets determined during register allocation. So, instead of generating
  14941. those instructions here, we invent a new instruction that means ``pop
  14942. the frame and then do an indirect jump,'' which we name
  14943. \code{TailJmp}. The abstract syntax for this instruction includes an
  14944. argument that specifies where to jump and an integer that represents
  14945. the arity of the function being called.
  14946. \section{Register Allocation}
  14947. \label{sec:register-allocation-r4}
  14948. The addition of functions requires some changes to all three aspects
  14949. of register allocation, which we discuss in the following subsections.
  14950. \subsection{Liveness Analysis}
  14951. \label{sec:liveness-analysis-r4}
  14952. \index{subject}{liveness analysis}
  14953. %% The rest of the passes need only minor modifications to handle the new
  14954. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14955. %% \code{leaq}.
  14956. The \code{IndirectCallq} instruction should be treated like
  14957. \code{Callq} regarding its written locations $W$, in that they should
  14958. include all the caller-saved registers. Recall that the reason for
  14959. that is to force variables that are live across a function call to be assigned to callee-saved
  14960. registers or to be spilled to the stack.
  14961. Regarding the set of read locations $R$, the arity fields of
  14962. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14963. argument-passing registers should be considered as read by those
  14964. instructions. Also, the target field of \code{TailJmp} and
  14965. \code{IndirectCallq} should be included in the set of read locations
  14966. $R$.
  14967. \subsection{Build Interference Graph}
  14968. \label{sec:build-interference-r4}
  14969. With the addition of function definitions, we compute a separate interference
  14970. graph for each function (not just one for the whole program).
  14971. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14972. spill tuple-typed variables that are live during a call to
  14973. \code{collect}, the garbage collector. With the addition of functions
  14974. to our language, we need to revisit this issue. Functions that perform
  14975. allocation contain calls to the collector. Thus, we should not only
  14976. spill a tuple-typed variable when it is live during a call to
  14977. \code{collect}, but we should spill the variable if it is live during
  14978. a call to any user-defined function. Thus, in the
  14979. \code{build\_interference} pass, we recommend adding interference
  14980. edges between call-live tuple-typed variables and the callee-saved
  14981. registers (in addition to creating edges between
  14982. call-live variables and the caller-saved registers).
  14983. \subsection{Allocate Registers}
  14984. The primary change to the \code{allocate\_registers} pass is adding an
  14985. auxiliary function for handling definitions (the \Def{} nonterminal
  14986. shown in figure~\ref{fig:x86-3}) with one case for function
  14987. definitions. The logic is the same as described in
  14988. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14989. allocation is performed many times, once for each function definition,
  14990. instead of just once for the whole program.
  14991. \section{Patch Instructions}
  14992. In \code{patch\_instructions}, you should deal with the x86
  14993. idiosyncrasy that the destination argument of \code{leaq} must be a
  14994. register. Additionally, you should ensure that the argument of
  14995. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14996. trample many other registers before the tail call, as explained in the
  14997. next section.
  14998. \section{Generate Prelude and Conclusion}
  14999. Now that register allocation is complete, we can translate the
  15000. \code{TailJmp} into a sequence of instructions. A naive translation of
  15001. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15002. before the jump we need to pop the current frame to achieve efficient
  15003. tail calls. This sequence of instructions is the same as the code for
  15004. the conclusion of a function, except that the \code{retq} is replaced with
  15005. \code{jmp *$\itm{arg}$}.
  15006. Regarding function definitions, we generate a prelude and conclusion
  15007. for each one. This code is similar to the prelude and conclusion
  15008. generated for the \code{main} function presented in
  15009. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15010. carry out the following steps:
  15011. % TODO: .align the functions!
  15012. \begin{enumerate}
  15013. %% \item Start with \code{.global} and \code{.align} directives followed
  15014. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15015. %% example.)
  15016. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15017. pointer.
  15018. \item Push to the stack all the callee-saved registers that were
  15019. used for register allocation.
  15020. \item Move the stack pointer \code{rsp} down to make room for the
  15021. regular spills (aligned to 16 bytes).
  15022. \item Move the root stack pointer \code{r15} up by the size of the
  15023. root-stack frame for this function, which depends on the number of
  15024. spilled tuple-typed variables. \label{root-stack-init}
  15025. \item Initialize to zero all new entries in the root-stack frame.
  15026. \item Jump to the start block.
  15027. \end{enumerate}
  15028. The prelude of the \code{main} function has an additional task: call
  15029. the \code{initialize} function to set up the garbage collector, and
  15030. then move the value of the global \code{rootstack\_begin} in
  15031. \code{r15}. This initialization should happen before step
  15032. \ref{root-stack-init}, which depends on \code{r15}.
  15033. The conclusion of every function should do the following:
  15034. \begin{enumerate}
  15035. \item Move the stack pointer back up past the regular spills.
  15036. \item Restore the callee-saved registers by popping them from the
  15037. stack.
  15038. \item Move the root stack pointer back down by the size of the
  15039. root-stack frame for this function.
  15040. \item Restore \code{rbp} by popping it from the stack.
  15041. \item Return to the caller with the \code{retq} instruction.
  15042. \end{enumerate}
  15043. The output of this pass is \LangXIndCallFlat{}, which differs from
  15044. \LangXIndCall{} in that there is no longer an AST node for function
  15045. definitions. Instead, a program is just
  15046. \racket{an association list}\python{a dictionary}
  15047. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15048. {\if\edition\racketEd
  15049. \[
  15050. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15051. \]
  15052. \fi}
  15053. {\if\edition\pythonEd
  15054. \[
  15055. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15056. \]
  15057. \fi}
  15058. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15059. compiling \LangFun{} to x86.
  15060. \begin{exercise}\normalfont\normalsize
  15061. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15062. Create eight new programs that use functions including examples that
  15063. pass functions and return functions from other functions, recursive
  15064. functions, functions that create tuples, and functions that make tail
  15065. calls. Test your compiler on these new programs and all your
  15066. previously created test programs.
  15067. \end{exercise}
  15068. \begin{figure}[tbp]
  15069. \begin{tcolorbox}[colback=white]
  15070. {\if\edition\racketEd
  15071. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15072. \node (Lfun) at (0,2) {\large \LangFun{}};
  15073. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15074. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15075. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15076. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15077. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15078. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15079. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15080. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15081. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15082. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15083. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15084. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15085. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15086. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15087. \path[->,bend left=15] (Lfun) edge [above] node
  15088. {\ttfamily\footnotesize shrink} (Lfun-1);
  15089. \path[->,bend left=15] (Lfun-1) edge [above] node
  15090. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15091. \path[->,bend left=15] (Lfun-2) edge [above] node
  15092. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15093. \path[->,bend left=15] (F1-1) edge [left] node
  15094. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15095. \path[->,bend left=15] (F1-2) edge [below] node
  15096. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15097. \path[->,bend left=15] (F1-3) edge [below] node
  15098. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15099. \path[->,bend right=15] (F1-4) edge [above] node
  15100. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15101. \path[->,bend right=15] (F1-5) edge [right] node
  15102. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15103. \path[->,bend right=15] (C3-2) edge [right] node
  15104. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15105. \path[->,bend left=15] (x86-2) edge [right] node
  15106. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15107. \path[->,bend right=15] (x86-2-1) edge [below] node
  15108. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15109. \path[->,bend right=15] (x86-2-2) edge [right] node
  15110. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15111. \path[->,bend left=15] (x86-3) edge [above] node
  15112. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15113. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15114. \end{tikzpicture}
  15115. \fi}
  15116. {\if\edition\pythonEd\pythonColor
  15117. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15118. \node (Lfun) at (0,2) {\large \LangFun{}};
  15119. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15120. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15121. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15122. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15123. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15124. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15125. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15126. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15127. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15128. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15129. \path[->,bend left=15] (Lfun) edge [above] node
  15130. {\ttfamily\footnotesize shrink} (Lfun-2);
  15131. \path[->,bend left=15] (Lfun-2) edge [above] node
  15132. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15133. \path[->,bend left=15] (F1-1) edge [above] node
  15134. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15135. \path[->,bend left=15] (F1-2) edge [right] node
  15136. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15137. \path[->,bend right=15] (F1-4) edge [above] node
  15138. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15139. \path[->,bend right=15] (F1-5) edge [right] node
  15140. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15141. \path[->,bend left=15] (C3-2) edge [right] node
  15142. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15143. \path[->,bend right=15] (x86-2) edge [below] node
  15144. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15145. \path[->,bend left=15] (x86-3) edge [above] node
  15146. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15147. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15148. \end{tikzpicture}
  15149. \fi}
  15150. \end{tcolorbox}
  15151. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15152. \label{fig:Lfun-passes}
  15153. \end{figure}
  15154. \section{An Example Translation}
  15155. \label{sec:functions-example}
  15156. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15157. function in \LangFun{} to x86. The figure includes the results of
  15158. \code{explicate\_control} and \code{select\_instructions}.
  15159. \begin{figure}[hbtp]
  15160. \begin{tcolorbox}[colback=white]
  15161. \begin{tabular}{ll}
  15162. \begin{minipage}{0.4\textwidth}
  15163. % s3_2.rkt
  15164. {\if\edition\racketEd
  15165. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15166. (define (add [x : Integer]
  15167. [y : Integer])
  15168. : Integer
  15169. (+ x y))
  15170. (add 40 2)
  15171. \end{lstlisting}
  15172. \fi}
  15173. {\if\edition\pythonEd\pythonColor
  15174. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15175. def add(x:int, y:int) -> int:
  15176. return x + y
  15177. print(add(40, 2))
  15178. \end{lstlisting}
  15179. \fi}
  15180. $\Downarrow$
  15181. {\if\edition\racketEd
  15182. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15183. (define (add86 [x87 : Integer]
  15184. [y88 : Integer])
  15185. : Integer
  15186. add86start:
  15187. return (+ x87 y88);
  15188. )
  15189. (define (main) : Integer ()
  15190. mainstart:
  15191. tmp89 = (fun-ref add86 2);
  15192. (tail-call tmp89 40 2)
  15193. )
  15194. \end{lstlisting}
  15195. \fi}
  15196. {\if\edition\pythonEd\pythonColor
  15197. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15198. def add(x:int, y:int) -> int:
  15199. addstart:
  15200. return x + y
  15201. def main() -> int:
  15202. mainstart:
  15203. fun.0 = add
  15204. tmp.1 = fun.0(40, 2)
  15205. print(tmp.1)
  15206. return 0
  15207. \end{lstlisting}
  15208. \fi}
  15209. \end{minipage}
  15210. &
  15211. $\Rightarrow$
  15212. \begin{minipage}{0.5\textwidth}
  15213. {\if\edition\racketEd
  15214. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15215. (define (add86) : Integer
  15216. add86start:
  15217. movq %rdi, x87
  15218. movq %rsi, y88
  15219. movq x87, %rax
  15220. addq y88, %rax
  15221. jmp inc1389conclusion
  15222. )
  15223. (define (main) : Integer
  15224. mainstart:
  15225. leaq (fun-ref add86 2), tmp89
  15226. movq $40, %rdi
  15227. movq $2, %rsi
  15228. tail-jmp tmp89
  15229. )
  15230. \end{lstlisting}
  15231. \fi}
  15232. {\if\edition\pythonEd\pythonColor
  15233. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15234. def add() -> int:
  15235. addstart:
  15236. movq %rdi, x
  15237. movq %rsi, y
  15238. movq x, %rax
  15239. addq y, %rax
  15240. jmp addconclusion
  15241. def main() -> int:
  15242. mainstart:
  15243. leaq add, fun.0
  15244. movq $40, %rdi
  15245. movq $2, %rsi
  15246. callq *fun.0
  15247. movq %rax, tmp.1
  15248. movq tmp.1, %rdi
  15249. callq print_int
  15250. movq $0, %rax
  15251. jmp mainconclusion
  15252. \end{lstlisting}
  15253. \fi}
  15254. $\Downarrow$
  15255. \end{minipage}
  15256. \end{tabular}
  15257. \begin{tabular}{ll}
  15258. \begin{minipage}{0.3\textwidth}
  15259. {\if\edition\racketEd
  15260. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15261. .globl add86
  15262. .align 8
  15263. add86:
  15264. pushq %rbp
  15265. movq %rsp, %rbp
  15266. jmp add86start
  15267. add86start:
  15268. movq %rdi, %rax
  15269. addq %rsi, %rax
  15270. jmp add86conclusion
  15271. add86conclusion:
  15272. popq %rbp
  15273. retq
  15274. \end{lstlisting}
  15275. \fi}
  15276. {\if\edition\pythonEd\pythonColor
  15277. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15278. .align 8
  15279. add:
  15280. pushq %rbp
  15281. movq %rsp, %rbp
  15282. subq $0, %rsp
  15283. jmp addstart
  15284. addstart:
  15285. movq %rdi, %rdx
  15286. movq %rsi, %rcx
  15287. movq %rdx, %rax
  15288. addq %rcx, %rax
  15289. jmp addconclusion
  15290. addconclusion:
  15291. subq $0, %r15
  15292. addq $0, %rsp
  15293. popq %rbp
  15294. retq
  15295. \end{lstlisting}
  15296. \fi}
  15297. \end{minipage}
  15298. &
  15299. \begin{minipage}{0.5\textwidth}
  15300. {\if\edition\racketEd
  15301. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15302. .globl main
  15303. .align 8
  15304. main:
  15305. pushq %rbp
  15306. movq %rsp, %rbp
  15307. movq $16384, %rdi
  15308. movq $16384, %rsi
  15309. callq initialize
  15310. movq rootstack_begin(%rip), %r15
  15311. jmp mainstart
  15312. mainstart:
  15313. leaq add86(%rip), %rcx
  15314. movq $40, %rdi
  15315. movq $2, %rsi
  15316. movq %rcx, %rax
  15317. popq %rbp
  15318. jmp *%rax
  15319. mainconclusion:
  15320. popq %rbp
  15321. retq
  15322. \end{lstlisting}
  15323. \fi}
  15324. {\if\edition\pythonEd\pythonColor
  15325. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15326. .globl main
  15327. .align 8
  15328. main:
  15329. pushq %rbp
  15330. movq %rsp, %rbp
  15331. subq $0, %rsp
  15332. movq $65536, %rdi
  15333. movq $65536, %rsi
  15334. callq initialize
  15335. movq rootstack_begin(%rip), %r15
  15336. jmp mainstart
  15337. mainstart:
  15338. leaq add(%rip), %rcx
  15339. movq $40, %rdi
  15340. movq $2, %rsi
  15341. callq *%rcx
  15342. movq %rax, %rcx
  15343. movq %rcx, %rdi
  15344. callq print_int
  15345. movq $0, %rax
  15346. jmp mainconclusion
  15347. mainconclusion:
  15348. subq $0, %r15
  15349. addq $0, %rsp
  15350. popq %rbp
  15351. retq
  15352. \end{lstlisting}
  15353. \fi}
  15354. \end{minipage}
  15355. \end{tabular}
  15356. \end{tcolorbox}
  15357. \caption{Example compilation of a simple function to x86.}
  15358. \label{fig:add-fun}
  15359. \end{figure}
  15360. % Challenge idea: inlining! (simple version)
  15361. % Further Reading
  15362. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15363. \chapter{Lexically Scoped Functions}
  15364. \label{ch:Llambda}
  15365. \setcounter{footnote}{0}
  15366. This chapter studies lexically scoped functions. Lexical
  15367. scoping\index{subject}{lexical scoping} means that a function's body
  15368. may refer to variables whose binding site is outside of the function,
  15369. in an enclosing scope.
  15370. %
  15371. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15372. in \LangLam{}, which extends \LangFun{} with the
  15373. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15374. functions. The body of the \key{lambda} refers to three variables:
  15375. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15376. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15377. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15378. function \code{f}}, and \code{x} is a parameter of function
  15379. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15380. result value. The main expression of the program includes two calls to
  15381. \code{f} with different arguments for \code{x}: first \code{5} and
  15382. then \code{3}. The functions returned from \code{f} are bound to
  15383. variables \code{g} and \code{h}. Even though these two functions were
  15384. created by the same \code{lambda}, they are really different functions
  15385. because they use different values for \code{x}. Applying \code{g} to
  15386. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15387. produces \code{22}, so the result of the program is \code{42}.
  15388. \begin{figure}[btp]
  15389. \begin{tcolorbox}[colback=white]
  15390. {\if\edition\racketEd
  15391. % lambda_test_21.rkt
  15392. \begin{lstlisting}
  15393. (define (f [x : Integer]) : (Integer -> Integer)
  15394. (let ([y 4])
  15395. (lambda: ([z : Integer]) : Integer
  15396. (+ x (+ y z)))))
  15397. (let ([g (f 5)])
  15398. (let ([h (f 3)])
  15399. (+ (g 11) (h 15))))
  15400. \end{lstlisting}
  15401. \fi}
  15402. {\if\edition\pythonEd\pythonColor
  15403. \begin{lstlisting}
  15404. def f(x : int) -> Callable[[int], int]:
  15405. y = 4
  15406. return lambda z: x + y + z
  15407. g = f(5)
  15408. h = f(3)
  15409. print(g(11) + h(15))
  15410. \end{lstlisting}
  15411. \fi}
  15412. \end{tcolorbox}
  15413. \caption{Example of a lexically scoped function.}
  15414. \label{fig:lexical-scoping}
  15415. \end{figure}
  15416. The approach that we take for implementing lexically scoped functions
  15417. is to compile them into top-level function definitions, translating
  15418. from \LangLam{} into \LangFun{}. However, the compiler must give
  15419. special treatment to variable occurrences such as \code{x} and
  15420. \code{y} in the body of the \code{lambda} shown in
  15421. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15422. may not refer to variables defined outside of it. To identify such
  15423. variable occurrences, we review the standard notion of free variable.
  15424. \begin{definition}\normalfont
  15425. A variable is \emph{free in expression} $e$ if the variable occurs
  15426. inside $e$ but does not have an enclosing definition that is also in
  15427. $e$.\index{subject}{free variable}
  15428. \end{definition}
  15429. For example, in the expression
  15430. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15431. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15432. only \code{x} and \code{y} are free in the following expression,
  15433. because \code{z} is defined by the \code{lambda}
  15434. {\if\edition\racketEd
  15435. \begin{lstlisting}
  15436. (lambda: ([z : Integer]) : Integer
  15437. (+ x (+ y z)))
  15438. \end{lstlisting}
  15439. \fi}
  15440. {\if\edition\pythonEd\pythonColor
  15441. \begin{lstlisting}
  15442. lambda z: x + y + z
  15443. \end{lstlisting}
  15444. \fi}
  15445. %
  15446. \noindent Thus the free variables of a \code{lambda} are the ones that
  15447. need special treatment. We need to transport at runtime the values
  15448. of those variables from the point where the \code{lambda} was created
  15449. to the point where the \code{lambda} is applied. An efficient solution
  15450. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15451. values of the free variables together with a function pointer into a
  15452. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15453. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15454. closure}
  15455. %
  15456. By design, we have all the ingredients to make closures:
  15457. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15458. function pointers. The function pointer resides at index $0$, and the
  15459. values for the free variables fill in the rest of the tuple.
  15460. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15461. to see how closures work. It is a three-step dance. The program calls
  15462. function \code{f}, which creates a closure for the \code{lambda}. The
  15463. closure is a tuple whose first element is a pointer to the top-level
  15464. function that we will generate for the \code{lambda}; the second
  15465. element is the value of \code{x}, which is \code{5}; and the third
  15466. element is \code{4}, the value of \code{y}. The closure does not
  15467. contain an element for \code{z} because \code{z} is not a free
  15468. variable of the \code{lambda}. Creating the closure is step 1 of the
  15469. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15470. shown in figure~\ref{fig:closures}.
  15471. %
  15472. The second call to \code{f} creates another closure, this time with
  15473. \code{3} in the second slot (for \code{x}). This closure is also
  15474. returned from \code{f} but bound to \code{h}, which is also shown in
  15475. figure~\ref{fig:closures}.
  15476. \begin{figure}[tbp]
  15477. \centering
  15478. \begin{minipage}{0.65\textwidth}
  15479. \begin{tcolorbox}[colback=white]
  15480. \includegraphics[width=\textwidth]{figs/closures}
  15481. \end{tcolorbox}
  15482. \end{minipage}
  15483. \caption{Flat closure representations for the two functions
  15484. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15485. \label{fig:closures}
  15486. \end{figure}
  15487. Continuing with the example, consider the application of \code{g} to
  15488. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15489. closure, we obtain the function pointer from the first element of the
  15490. closure and call it, passing in the closure itself and then the
  15491. regular arguments, in this case \code{11}. This technique for applying
  15492. a closure is step 2 of the dance.
  15493. %
  15494. But doesn't this \code{lambda} take only one argument, for parameter
  15495. \code{z}? The third and final step of the dance is generating a
  15496. top-level function for a \code{lambda}. We add an additional
  15497. parameter for the closure and insert an initialization at the beginning
  15498. of the function for each free variable, to bind those variables to the
  15499. appropriate elements from the closure parameter.
  15500. %
  15501. This three-step dance is known as \emph{closure
  15502. conversion}\index{subject}{closure conversion}. We discuss the
  15503. details of closure conversion in section~\ref{sec:closure-conversion}
  15504. and show the code generated from the example in
  15505. section~\ref{sec:example-lambda}. First, we define the syntax and
  15506. semantics of \LangLam{} in section~\ref{sec:r5}.
  15507. \section{The \LangLam{} Language}
  15508. \label{sec:r5}
  15509. The definitions of the concrete syntax and abstract syntax for
  15510. \LangLam{}, a language with anonymous functions and lexical scoping,
  15511. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15512. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15513. for \LangFun{}, which already has syntax for function application.
  15514. %
  15515. \python{The syntax also includes an assignment statement that includes
  15516. a type annotation for the variable on the left-hand side, which
  15517. facilitates the type checking of \code{lambda} expressions that we
  15518. discuss later in this section.}
  15519. %
  15520. \racket{The \code{procedure-arity} operation returns the number of parameters
  15521. of a given function, an operation that we need for the translation
  15522. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15523. %
  15524. \python{The \code{arity} operation returns the number of parameters of
  15525. a given function, an operation that we need for the translation
  15526. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15527. The \code{arity} operation is not in Python, but the same functionality
  15528. is available in a more complex form. We include \code{arity} in the
  15529. \LangLam{} source language to enable testing.}
  15530. \newcommand{\LlambdaGrammarRacket}{
  15531. \begin{array}{lcl}
  15532. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15533. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15534. \end{array}
  15535. }
  15536. \newcommand{\LlambdaASTRacket}{
  15537. \begin{array}{lcl}
  15538. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15539. \itm{op} &::=& \code{procedure-arity}
  15540. \end{array}
  15541. }
  15542. \newcommand{\LlambdaGrammarPython}{
  15543. \begin{array}{lcl}
  15544. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15545. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15546. \end{array}
  15547. }
  15548. \newcommand{\LlambdaASTPython}{
  15549. \begin{array}{lcl}
  15550. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15551. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15552. \end{array}
  15553. }
  15554. % include AnnAssign in ASTPython
  15555. \begin{figure}[tp]
  15556. \centering
  15557. \begin{tcolorbox}[colback=white]
  15558. \small
  15559. {\if\edition\racketEd
  15560. \[
  15561. \begin{array}{l}
  15562. \gray{\LintGrammarRacket{}} \\ \hline
  15563. \gray{\LvarGrammarRacket{}} \\ \hline
  15564. \gray{\LifGrammarRacket{}} \\ \hline
  15565. \gray{\LwhileGrammarRacket} \\ \hline
  15566. \gray{\LtupGrammarRacket} \\ \hline
  15567. \gray{\LfunGrammarRacket} \\ \hline
  15568. \LlambdaGrammarRacket \\
  15569. \begin{array}{lcl}
  15570. \LangLamM{} &::=& \Def\ldots \; \Exp
  15571. \end{array}
  15572. \end{array}
  15573. \]
  15574. \fi}
  15575. {\if\edition\pythonEd\pythonColor
  15576. \[
  15577. \begin{array}{l}
  15578. \gray{\LintGrammarPython{}} \\ \hline
  15579. \gray{\LvarGrammarPython{}} \\ \hline
  15580. \gray{\LifGrammarPython{}} \\ \hline
  15581. \gray{\LwhileGrammarPython} \\ \hline
  15582. \gray{\LtupGrammarPython} \\ \hline
  15583. \gray{\LfunGrammarPython} \\ \hline
  15584. \LlambdaGrammarPython \\
  15585. \begin{array}{lcl}
  15586. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15587. \end{array}
  15588. \end{array}
  15589. \]
  15590. \fi}
  15591. \end{tcolorbox}
  15592. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15593. with \key{lambda}.}
  15594. \label{fig:Llam-concrete-syntax}
  15595. \end{figure}
  15596. \begin{figure}[tp]
  15597. \centering
  15598. \begin{tcolorbox}[colback=white]
  15599. \small
  15600. {\if\edition\racketEd
  15601. \[\arraycolsep=3pt
  15602. \begin{array}{l}
  15603. \gray{\LintOpAST} \\ \hline
  15604. \gray{\LvarASTRacket{}} \\ \hline
  15605. \gray{\LifASTRacket{}} \\ \hline
  15606. \gray{\LwhileASTRacket{}} \\ \hline
  15607. \gray{\LtupASTRacket{}} \\ \hline
  15608. \gray{\LfunASTRacket} \\ \hline
  15609. \LlambdaASTRacket \\
  15610. \begin{array}{lcl}
  15611. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15612. \end{array}
  15613. \end{array}
  15614. \]
  15615. \fi}
  15616. {\if\edition\pythonEd\pythonColor
  15617. \[
  15618. \begin{array}{l}
  15619. \gray{\LintASTPython} \\ \hline
  15620. \gray{\LvarASTPython{}} \\ \hline
  15621. \gray{\LifASTPython{}} \\ \hline
  15622. \gray{\LwhileASTPython{}} \\ \hline
  15623. \gray{\LtupASTPython{}} \\ \hline
  15624. \gray{\LfunASTPython} \\ \hline
  15625. \LlambdaASTPython \\
  15626. \begin{array}{lcl}
  15627. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15628. \end{array}
  15629. \end{array}
  15630. \]
  15631. \fi}
  15632. \end{tcolorbox}
  15633. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15634. \label{fig:Llam-syntax}
  15635. \end{figure}
  15636. Figure~\ref{fig:interp-Llambda} shows the definitional
  15637. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15638. \key{Lambda} saves the current environment inside the returned
  15639. function value. Recall that during function application, the
  15640. environment stored in the function value, extended with the mapping of
  15641. parameters to argument values, is used to interpret the body of the
  15642. function.
  15643. \begin{figure}[tbp]
  15644. \begin{tcolorbox}[colback=white]
  15645. {\if\edition\racketEd
  15646. \begin{lstlisting}
  15647. (define interp-Llambda-class
  15648. (class interp-Lfun-class
  15649. (super-new)
  15650. (define/override (interp-op op)
  15651. (match op
  15652. ['procedure-arity
  15653. (lambda (v)
  15654. (match v
  15655. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15656. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15657. [else (super interp-op op)]))
  15658. (define/override ((interp-exp env) e)
  15659. (define recur (interp-exp env))
  15660. (match e
  15661. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15662. `(function ,xs ,body ,env)]
  15663. [else ((super interp-exp env) e)]))
  15664. ))
  15665. (define (interp-Llambda p)
  15666. (send (new interp-Llambda-class) interp-program p))
  15667. \end{lstlisting}
  15668. \fi}
  15669. {\if\edition\pythonEd\pythonColor
  15670. \begin{lstlisting}
  15671. class InterpLlambda(InterpLfun):
  15672. def arity(self, v):
  15673. match v:
  15674. case Function(name, params, body, env):
  15675. return len(params)
  15676. case _:
  15677. raise Exception('Llambda arity unexpected ' + repr(v))
  15678. def interp_exp(self, e, env):
  15679. match e:
  15680. case Call(Name('arity'), [fun]):
  15681. f = self.interp_exp(fun, env)
  15682. return self.arity(f)
  15683. case Lambda(params, body):
  15684. return Function('lambda', params, [Return(body)], env)
  15685. case _:
  15686. return super().interp_exp(e, env)
  15687. def interp_stmt(self, s, env, cont):
  15688. match s:
  15689. case AnnAssign(lhs, typ, value, simple):
  15690. env[lhs.id] = self.interp_exp(value, env)
  15691. return self.interp_stmts(cont, env)
  15692. case Pass():
  15693. return self.interp_stmts(cont, env)
  15694. case _:
  15695. return super().interp_stmt(s, env, cont)
  15696. \end{lstlisting}
  15697. \fi}
  15698. \end{tcolorbox}
  15699. \caption{Interpreter for \LangLam{}.}
  15700. \label{fig:interp-Llambda}
  15701. \end{figure}
  15702. {\if\edition\racketEd
  15703. %
  15704. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15705. \key{lambda} form. The body of the \key{lambda} is checked in an
  15706. environment that includes the current environment (because it is
  15707. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15708. require the body's type to match the declared return type.
  15709. %
  15710. \fi}
  15711. {\if\edition\pythonEd\pythonColor
  15712. %
  15713. Figures~\ref{fig:type-check-Llambda} and
  15714. \ref{fig:type-check-Llambda-part2} define the type checker for
  15715. \LangLam{}, which is more complex than one might expect. The reason
  15716. for the added complexity is that the syntax of \key{lambda} does not
  15717. include type annotations for the parameters or return type. Instead
  15718. they must be inferred. There are many approaches to type inference
  15719. from which to choose, of varying degrees of complexity. We choose one
  15720. of the simpler approaches, bidirectional type
  15721. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15722. book is compilation, not type inference.
  15723. The main idea of bidirectional type inference is to add an auxiliary
  15724. function, here named \code{check\_exp}, that takes an expected type
  15725. and checks whether the given expression is of that type. Thus, in
  15726. \code{check\_exp}, type information flows in a top-down manner with
  15727. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15728. function, where type information flows in a primarily bottom-up
  15729. manner.
  15730. %
  15731. The idea then is to use \code{check\_exp} in all the places where we
  15732. already know what the type of an expression should be, such as in the
  15733. \code{return} statement of a top-level function definition or on the
  15734. right-hand side of an annotated assignment statement.
  15735. With regard to \code{lambda}, it is straightforward to check a
  15736. \code{lambda} inside \code{check\_exp} because the expected type
  15737. provides the parameter types and the return type. On the other hand,
  15738. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15739. that we do not allow \code{lambda} in contexts in which we don't already
  15740. know its type. This restriction does not incur a loss of
  15741. expressiveness for \LangLam{} because it is straightforward to modify
  15742. a program to sidestep the restriction, for example, by using an
  15743. annotated assignment statement to assign the \code{lambda} to a
  15744. temporary variable.
  15745. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15746. checker records their type in a \code{has\_type} field. This type
  15747. information is used further on in this chapter.
  15748. %
  15749. \fi}
  15750. \begin{figure}[tbp]
  15751. \begin{tcolorbox}[colback=white]
  15752. {\if\edition\racketEd
  15753. \begin{lstlisting}
  15754. (define (type-check-Llambda env)
  15755. (lambda (e)
  15756. (match e
  15757. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15758. (define-values (new-body bodyT)
  15759. ((type-check-exp (append (map cons xs Ts) env)) body))
  15760. (define ty `(,@Ts -> ,rT))
  15761. (cond
  15762. [(equal? rT bodyT)
  15763. (values (HasType (Lambda params rT new-body) ty) ty)]
  15764. [else
  15765. (error "mismatch in return type" bodyT rT)])]
  15766. ...
  15767. )))
  15768. \end{lstlisting}
  15769. \fi}
  15770. {\if\edition\pythonEd\pythonColor
  15771. \begin{lstlisting}
  15772. class TypeCheckLlambda(TypeCheckLfun):
  15773. def type_check_exp(self, e, env):
  15774. match e:
  15775. case Name(id):
  15776. e.has_type = env[id]
  15777. return env[id]
  15778. case Lambda(params, body):
  15779. raise Exception('cannot synthesize a type for a lambda')
  15780. case Call(Name('arity'), [func]):
  15781. func_t = self.type_check_exp(func, env)
  15782. match func_t:
  15783. case FunctionType(params_t, return_t):
  15784. return IntType()
  15785. case _:
  15786. raise Exception('in arity, unexpected ' + repr(func_t))
  15787. case _:
  15788. return super().type_check_exp(e, env)
  15789. def check_exp(self, e, ty, env):
  15790. match e:
  15791. case Lambda(params, body):
  15792. e.has_type = ty
  15793. match ty:
  15794. case FunctionType(params_t, return_t):
  15795. new_env = env.copy().update(zip(params, params_t))
  15796. self.check_exp(body, return_t, new_env)
  15797. case _:
  15798. raise Exception('lambda does not have type ' + str(ty))
  15799. case Call(func, args):
  15800. func_t = self.type_check_exp(func, env)
  15801. match func_t:
  15802. case FunctionType(params_t, return_t):
  15803. for (arg, param_t) in zip(args, params_t):
  15804. self.check_exp(arg, param_t, env)
  15805. self.check_type_equal(return_t, ty, e)
  15806. case _:
  15807. raise Exception('type_check_exp: in call, unexpected ' + \
  15808. repr(func_t))
  15809. case _:
  15810. t = self.type_check_exp(e, env)
  15811. self.check_type_equal(t, ty, e)
  15812. \end{lstlisting}
  15813. \fi}
  15814. \end{tcolorbox}
  15815. \caption{Type checking \LangLam{}\python{, part 1}.}
  15816. \label{fig:type-check-Llambda}
  15817. \end{figure}
  15818. {\if\edition\pythonEd\pythonColor
  15819. \begin{figure}[tbp]
  15820. \begin{tcolorbox}[colback=white]
  15821. \begin{lstlisting}
  15822. def check_stmts(self, ss, return_ty, env):
  15823. if len(ss) == 0:
  15824. return
  15825. match ss[0]:
  15826. case FunctionDef(name, params, body, dl, returns, comment):
  15827. new_env = env.copy().update(params)
  15828. rt = self.check_stmts(body, returns, new_env)
  15829. self.check_stmts(ss[1:], return_ty, env)
  15830. case Return(value):
  15831. self.check_exp(value, return_ty, env)
  15832. case Assign([Name(id)], value):
  15833. if id in env:
  15834. self.check_exp(value, env[id], env)
  15835. else:
  15836. env[id] = self.type_check_exp(value, env)
  15837. self.check_stmts(ss[1:], return_ty, env)
  15838. case Assign([Subscript(tup, Constant(index), Store())], value):
  15839. tup_t = self.type_check_exp(tup, env)
  15840. match tup_t:
  15841. case TupleType(ts):
  15842. self.check_exp(value, ts[index], env)
  15843. case _:
  15844. raise Exception('expected a tuple, not ' + repr(tup_t))
  15845. self.check_stmts(ss[1:], return_ty, env)
  15846. case AnnAssign(Name(id), ty_annot, value, simple):
  15847. ss[0].annotation = ty_annot
  15848. if id in env:
  15849. self.check_type_equal(env[id], ty_annot)
  15850. else:
  15851. env[id] = ty_annot
  15852. self.check_exp(value, ty_annot, env)
  15853. self.check_stmts(ss[1:], return_ty, env)
  15854. case _:
  15855. self.type_check_stmts(ss, env)
  15856. def type_check(self, p):
  15857. match p:
  15858. case Module(body):
  15859. env = {}
  15860. for s in body:
  15861. match s:
  15862. case FunctionDef(name, params, bod, dl, returns, comment):
  15863. params_t = [t for (x,t) in params]
  15864. env[name] = FunctionType(params_t, returns)
  15865. self.check_stmts(body, int, env)
  15866. \end{lstlisting}
  15867. \end{tcolorbox}
  15868. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15869. \label{fig:type-check-Llambda-part2}
  15870. \end{figure}
  15871. \fi}
  15872. \clearpage
  15873. \section{Assignment and Lexically Scoped Functions}
  15874. \label{sec:assignment-scoping}
  15875. The combination of lexically scoped functions and assignment to
  15876. variables raises a challenge with the flat-closure approach to
  15877. implementing lexically scoped functions. Consider the following
  15878. example in which function \code{f} has a free variable \code{x} that
  15879. is changed after \code{f} is created but before the call to \code{f}.
  15880. % loop_test_11.rkt
  15881. {\if\edition\racketEd
  15882. \begin{lstlisting}
  15883. (let ([x 0])
  15884. (let ([y 0])
  15885. (let ([z 20])
  15886. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15887. (begin
  15888. (set! x 10)
  15889. (set! y 12)
  15890. (f y))))))
  15891. \end{lstlisting}
  15892. \fi}
  15893. {\if\edition\pythonEd\pythonColor
  15894. % box_free_assign.py
  15895. \begin{lstlisting}
  15896. def g(z : int) -> int:
  15897. x = 0
  15898. y = 0
  15899. f : Callable[[int],int] = lambda a: a + x + z
  15900. x = 10
  15901. y = 12
  15902. return f(y)
  15903. print(g(20))
  15904. \end{lstlisting}
  15905. \fi} The correct output for this example is \code{42} because the call
  15906. to \code{f} is required to use the current value of \code{x} (which is
  15907. \code{10}). Unfortunately, the closure conversion pass
  15908. (section~\ref{sec:closure-conversion}) generates code for the
  15909. \code{lambda} that copies the old value of \code{x} into a
  15910. closure. Thus, if we naively applied closure conversion, the output of
  15911. this program would be \code{32}.
  15912. A first attempt at solving this problem would be to save a pointer to
  15913. \code{x} in the closure and change the occurrences of \code{x} inside
  15914. the lambda to dereference the pointer. Of course, this would require
  15915. assigning \code{x} to the stack and not to a register. However, the
  15916. problem goes a bit deeper.
  15917. Consider the following example that returns a function that refers to
  15918. a local variable of the enclosing function:
  15919. \begin{center}
  15920. \begin{minipage}{\textwidth}
  15921. {\if\edition\racketEd
  15922. \begin{lstlisting}
  15923. (define (f) : ( -> Integer)
  15924. (let ([x 0])
  15925. (let ([g (lambda: () : Integer x)])
  15926. (begin
  15927. (set! x 42)
  15928. g))))
  15929. ((f))
  15930. \end{lstlisting}
  15931. \fi}
  15932. {\if\edition\pythonEd\pythonColor
  15933. % counter.py
  15934. \begin{lstlisting}
  15935. def f():
  15936. x = 0
  15937. g = lambda: x
  15938. x = 42
  15939. return g
  15940. print(f()())
  15941. \end{lstlisting}
  15942. \fi}
  15943. \end{minipage}
  15944. \end{center}
  15945. In this example, the lifetime of \code{x} extends beyond the lifetime
  15946. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15947. stack frame for the call to \code{f}, it would be gone by the time we
  15948. called \code{g}, leaving us with dangling pointers for
  15949. \code{x}. This example demonstrates that when a variable occurs free
  15950. inside a function, its lifetime becomes indefinite. Thus, the value of
  15951. the variable needs to live on the heap. The verb
  15952. \emph{box}\index{subject}{box} is often used for allocating a single
  15953. value on the heap, producing a pointer, and
  15954. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15955. %
  15956. We introduce a new pass named \code{convert\_assignments} to address
  15957. this challenge.
  15958. %
  15959. \python{But before diving into that, we have one more
  15960. problem to discuss.}
  15961. {\if\edition\pythonEd\pythonColor
  15962. \section{Uniquify Variables}
  15963. \label{sec:uniquify-lambda}
  15964. With the addition of \code{lambda} we have a complication to deal
  15965. with: name shadowing. Consider the following program with a function
  15966. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15967. \code{lambda} expressions. The first \code{lambda} has a parameter
  15968. that is also named \code{x}.
  15969. \begin{lstlisting}
  15970. def f(x:int, y:int) -> Callable[[int], int]:
  15971. g : Callable[[int],int] = (lambda x: x + y)
  15972. h : Callable[[int],int] = (lambda y: x + y)
  15973. x = input_int()
  15974. return g
  15975. print(f(0, 10)(32))
  15976. \end{lstlisting}
  15977. Many of our compiler passes rely on being able to connect variable
  15978. uses with their definitions using just the name of the
  15979. variable. However, in the example above, the name of the variable does
  15980. not uniquely determine its definition. To solve this problem we
  15981. recommend implementing a pass named \code{uniquify} that renames every
  15982. variable in the program to make sure that they are all unique.
  15983. The following shows the result of \code{uniquify} for the example
  15984. above. The \code{x} parameter of function \code{f} is renamed to
  15985. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15986. renamed to \code{x\_4}.
  15987. \begin{lstlisting}
  15988. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15989. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15990. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15991. x_0 = input_int()
  15992. return g_2
  15993. def main() -> int :
  15994. print(f(0, 10)(32))
  15995. return 0
  15996. \end{lstlisting}
  15997. \fi} % pythonEd
  15998. %% \section{Reveal Functions}
  15999. %% \label{sec:reveal-functions-r5}
  16000. %% \racket{To support the \code{procedure-arity} operator we need to
  16001. %% communicate the arity of a function to the point of closure
  16002. %% creation.}
  16003. %% %
  16004. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16005. %% function at runtime. Thus, we need to communicate the arity of a
  16006. %% function to the point of closure creation.}
  16007. %% %
  16008. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16009. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16010. %% \[
  16011. %% \begin{array}{lcl}
  16012. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16013. %% \end{array}
  16014. %% \]
  16015. \section{Assignment Conversion}
  16016. \label{sec:convert-assignments}
  16017. The purpose of the \code{convert\_assignments} pass is to address the
  16018. challenge regarding the interaction between variable assignments and
  16019. closure conversion. First we identify which variables need to be
  16020. boxed, and then we transform the program to box those variables. In
  16021. general, boxing introduces runtime overhead that we would like to
  16022. avoid, so we should box as few variables as possible. We recommend
  16023. boxing the variables in the intersection of the following two sets of
  16024. variables:
  16025. \begin{enumerate}
  16026. \item The variables that are free in a \code{lambda}.
  16027. \item The variables that appear on the left-hand side of an
  16028. assignment.
  16029. \end{enumerate}
  16030. The first condition is a must but the second condition is
  16031. conservative. It is possible to develop a more liberal condition using
  16032. static program analysis.
  16033. Consider again the first example from
  16034. section~\ref{sec:assignment-scoping}:
  16035. %
  16036. {\if\edition\racketEd
  16037. \begin{lstlisting}
  16038. (let ([x 0])
  16039. (let ([y 0])
  16040. (let ([z 20])
  16041. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16042. (begin
  16043. (set! x 10)
  16044. (set! y 12)
  16045. (f y))))))
  16046. \end{lstlisting}
  16047. \fi}
  16048. {\if\edition\pythonEd\pythonColor
  16049. \begin{lstlisting}
  16050. def g(z : int) -> int:
  16051. x = 0
  16052. y = 0
  16053. f : Callable[[int],int] = lambda a: a + x + z
  16054. x = 10
  16055. y = 12
  16056. return f(y)
  16057. print(g(20))
  16058. \end{lstlisting}
  16059. \fi}
  16060. %
  16061. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16062. side of assignments. The variables \code{x} and \code{z} occur free
  16063. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16064. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16065. three transformations: initialize \code{x} with a tuple whose element
  16066. is uninitialized, replace reads from \code{x} with tuple reads, and
  16067. replace each assignment to \code{x} with a tuple write. The output of
  16068. \code{convert\_assignments} for this example is as follows:
  16069. %
  16070. {\if\edition\racketEd
  16071. \begin{lstlisting}
  16072. (define (main) : Integer
  16073. (let ([x0 (vector 0)])
  16074. (let ([y1 0])
  16075. (let ([z2 20])
  16076. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16077. (+ a3 (+ (vector-ref x0 0) z2)))])
  16078. (begin
  16079. (vector-set! x0 0 10)
  16080. (set! y1 12)
  16081. (f4 y1)))))))
  16082. \end{lstlisting}
  16083. \fi}
  16084. %
  16085. {\if\edition\pythonEd\pythonColor
  16086. \begin{lstlisting}
  16087. def g(z : int)-> int:
  16088. x = (uninitialized(int),)
  16089. x[0] = 0
  16090. y = 0
  16091. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16092. x[0] = 10
  16093. y = 12
  16094. return f(y)
  16095. def main() -> int:
  16096. print(g(20))
  16097. return 0
  16098. \end{lstlisting}
  16099. \fi}
  16100. To compute the free variables of all the \code{lambda} expressions, we
  16101. recommend defining the following two auxiliary functions:
  16102. \begin{enumerate}
  16103. \item \code{free\_variables} computes the free variables of an expression, and
  16104. \item \code{free\_in\_lambda} collects all the variables that are
  16105. free in any of the \code{lambda} expressions, using
  16106. \code{free\_variables} in the case for each \code{lambda}.
  16107. \end{enumerate}
  16108. {\if\edition\racketEd
  16109. %
  16110. To compute the variables that are assigned to, we recommend updating
  16111. the \code{collect-set!} function that we introduced in
  16112. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16113. as \code{Lambda}.
  16114. %
  16115. \fi}
  16116. {\if\edition\pythonEd\pythonColor
  16117. %
  16118. To compute the variables that are assigned to, we recommend defining
  16119. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16120. the set of variables that occur in the left-hand side of an assignment
  16121. statement and otherwise returns the empty set.
  16122. %
  16123. \fi}
  16124. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16125. free in a \code{lambda} and that are assigned to in the enclosing
  16126. function definition.
  16127. Next we discuss the \code{convert\_assignments} pass. In the case for
  16128. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16129. $\VAR{x}$ to a tuple read.
  16130. %
  16131. {\if\edition\racketEd
  16132. \begin{lstlisting}
  16133. (Var |$x$|)
  16134. |$\Rightarrow$|
  16135. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16136. \end{lstlisting}
  16137. \fi}
  16138. %
  16139. {\if\edition\pythonEd\pythonColor
  16140. \begin{lstlisting}
  16141. Name(|$x$|)
  16142. |$\Rightarrow$|
  16143. Subscript(Name(|$x$|), Constant(0), Load())
  16144. \end{lstlisting}
  16145. \fi}
  16146. %
  16147. \noindent In the case for assignment, recursively process the
  16148. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16149. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16150. as follows:
  16151. %
  16152. {\if\edition\racketEd
  16153. \begin{lstlisting}
  16154. (SetBang |$x$| |$\itm{rhs}$|)
  16155. |$\Rightarrow$|
  16156. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16157. \end{lstlisting}
  16158. \fi}
  16159. {\if\edition\pythonEd\pythonColor
  16160. \begin{lstlisting}
  16161. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16162. |$\Rightarrow$|
  16163. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16164. \end{lstlisting}
  16165. \fi}
  16166. %
  16167. {\if\edition\racketEd
  16168. The case for \code{Lambda} is nontrivial, but it is similar to the
  16169. case for function definitions, which we discuss next.
  16170. \fi}
  16171. %
  16172. To translate a function definition, we first compute $\mathit{AF}$,
  16173. the intersection of the variables that are free in a \code{lambda} and
  16174. that are assigned to. We then apply assignment conversion to the body
  16175. of the function definition. Finally, we box the parameters of this
  16176. function definition that are in $\mathit{AF}$. For example,
  16177. the parameter \code{x} of the following function \code{g}
  16178. needs to be boxed:
  16179. {\if\edition\racketEd
  16180. \begin{lstlisting}
  16181. (define (g [x : Integer]) : Integer
  16182. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16183. (begin
  16184. (set! x 10)
  16185. (f 32))))
  16186. \end{lstlisting}
  16187. \fi}
  16188. %
  16189. {\if\edition\pythonEd\pythonColor
  16190. \begin{lstlisting}
  16191. def g(x : int) -> int:
  16192. f : Callable[[int],int] = lambda a: a + x
  16193. x = 10
  16194. return f(32)
  16195. \end{lstlisting}
  16196. \fi}
  16197. %
  16198. \noindent We box parameter \code{x} by creating a local variable named
  16199. \code{x} that is initialized to a tuple whose contents is the value of
  16200. the parameter, which is renamed to \code{x\_0}.
  16201. %
  16202. {\if\edition\racketEd
  16203. \begin{lstlisting}
  16204. (define (g [x_0 : Integer]) : Integer
  16205. (let ([x (vector x_0)])
  16206. (let ([f (lambda: ([a : Integer]) : Integer
  16207. (+ a (vector-ref x 0)))])
  16208. (begin
  16209. (vector-set! x 0 10)
  16210. (f 32)))))
  16211. \end{lstlisting}
  16212. \fi}
  16213. %
  16214. {\if\edition\pythonEd\pythonColor
  16215. \begin{lstlisting}
  16216. def g(x_0 : int)-> int:
  16217. x = (x_0,)
  16218. f : Callable[[int], int] = (lambda a: a + x[0])
  16219. x[0] = 10
  16220. return f(32)
  16221. \end{lstlisting}
  16222. \fi}
  16223. \section{Closure Conversion}
  16224. \label{sec:closure-conversion}
  16225. \index{subject}{closure conversion}
  16226. The compiling of lexically scoped functions into top-level function
  16227. definitions and flat closures is accomplished in the pass
  16228. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16229. and before \code{limit\_functions}.
  16230. As usual, we implement the pass as a recursive function over the
  16231. AST. The interesting cases are for \key{lambda} and function
  16232. application. We transform a \key{lambda} expression into an expression
  16233. that creates a closure, that is, a tuple for which the first element
  16234. is a function pointer and the rest of the elements are the values of
  16235. the free variables of the \key{lambda}.
  16236. %
  16237. However, we use the \code{Closure} AST node instead of using a tuple
  16238. so that we can record the arity.
  16239. %
  16240. In the generated code that follows, \itm{fvs} is the list of free
  16241. variables of the lambda and \itm{name} is a unique symbol generated to
  16242. identify the lambda.
  16243. %
  16244. \racket{The \itm{arity} is the number of parameters (the length of
  16245. \itm{ps}).}
  16246. %
  16247. {\if\edition\racketEd
  16248. \begin{lstlisting}
  16249. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16250. |$\Rightarrow$|
  16251. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16252. \end{lstlisting}
  16253. \fi}
  16254. %
  16255. {\if\edition\pythonEd\pythonColor
  16256. \begin{lstlisting}
  16257. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16258. |$\Rightarrow$|
  16259. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16260. \end{lstlisting}
  16261. \fi}
  16262. %
  16263. In addition to transforming each \key{Lambda} AST node into a
  16264. tuple, we create a top-level function definition for each
  16265. \key{Lambda}, as shown next.\\
  16266. \begin{minipage}{0.8\textwidth}
  16267. {\if\edition\racketEd
  16268. \begin{lstlisting}
  16269. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16270. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16271. ...
  16272. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16273. |\itm{body'}|)...))
  16274. \end{lstlisting}
  16275. \fi}
  16276. {\if\edition\pythonEd\pythonColor
  16277. \begin{lstlisting}
  16278. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16279. |$\itm{fvs}_1$| = clos[1]
  16280. |$\ldots$|
  16281. |$\itm{fvs}_m$| = clos[|$m$|]
  16282. |\itm{body'}|
  16283. \end{lstlisting}
  16284. \fi}
  16285. \end{minipage}\\
  16286. %
  16287. The \code{clos} parameter refers to the closure. The type
  16288. \itm{closTy} is a tuple type for which the first element type is
  16289. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16290. rest of the element types are the types of the free variables in the
  16291. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16292. is nontrivial to give a type to the function in the closure's
  16293. type.\footnote{To give an accurate type to a closure, we would need to
  16294. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16295. %
  16296. \racket{Translate the type
  16297. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16298. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16299. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16300. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16301. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16302. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16303. %% The dummy type is considered to be equal to any other type during type
  16304. %% checking.
  16305. The free variables become local variables that are initialized with
  16306. their values in the closure.
  16307. Closure conversion turns every function into a tuple, so the type
  16308. annotations in the program must also be translated. We recommend
  16309. defining an auxiliary recursive function for this purpose. Function
  16310. types should be translated as follows:
  16311. %
  16312. {\if\edition\racketEd
  16313. \begin{lstlisting}
  16314. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16315. |$\Rightarrow$|
  16316. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16317. \end{lstlisting}
  16318. \fi}
  16319. {\if\edition\pythonEd\pythonColor
  16320. \begin{lstlisting}
  16321. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16322. |$\Rightarrow$|
  16323. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16324. \end{lstlisting}
  16325. \fi}
  16326. %
  16327. This type indicates that the first thing in the tuple is a
  16328. function. The first parameter of the function is a tuple (a closure)
  16329. and the rest of the parameters are the ones from the original
  16330. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16331. omits the types of the free variables because (1) those types are not
  16332. available in this context, and (2) we do not need them in the code that
  16333. is generated for function application. So this type describes only the
  16334. first component of the closure tuple. At runtime the tuple may have
  16335. more components, but we ignore them at this point.
  16336. We transform function application into code that retrieves the
  16337. function from the closure and then calls the function, passing the
  16338. closure as the first argument. We place $e'$ in a temporary variable
  16339. to avoid code duplication.
  16340. \begin{center}
  16341. \begin{minipage}{\textwidth}
  16342. {\if\edition\racketEd
  16343. \begin{lstlisting}
  16344. (Apply |$e$| |$\itm{es}$|)
  16345. |$\Rightarrow$|
  16346. (Let |$\itm{tmp}$| |$e'$|
  16347. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16348. \end{lstlisting}
  16349. \fi}
  16350. %
  16351. {\if\edition\pythonEd\pythonColor
  16352. \begin{lstlisting}
  16353. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16354. |$\Rightarrow$|
  16355. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16356. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16357. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16358. \end{lstlisting}
  16359. \fi}
  16360. \end{minipage}
  16361. \end{center}
  16362. There is also the question of what to do with references to top-level
  16363. function definitions. To maintain a uniform translation of function
  16364. application, we turn function references into closures.
  16365. \begin{tabular}{lll}
  16366. \begin{minipage}{0.2\textwidth}
  16367. {\if\edition\racketEd
  16368. \begin{lstlisting}
  16369. (FunRef |$f$| |$n$|)
  16370. \end{lstlisting}
  16371. \fi}
  16372. {\if\edition\pythonEd\pythonColor
  16373. \begin{lstlisting}
  16374. FunRef(|$f$|, |$n$|)
  16375. \end{lstlisting}
  16376. \fi}
  16377. \end{minipage}
  16378. &
  16379. $\Rightarrow\qquad$
  16380. &
  16381. \begin{minipage}{0.5\textwidth}
  16382. {\if\edition\racketEd
  16383. \begin{lstlisting}
  16384. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16385. \end{lstlisting}
  16386. \fi}
  16387. {\if\edition\pythonEd\pythonColor
  16388. \begin{lstlisting}
  16389. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16390. \end{lstlisting}
  16391. \fi}
  16392. \end{minipage}
  16393. \end{tabular} \\
  16394. We no longer need the annotated assignment statement \code{AnnAssign}
  16395. to support the type checking of \code{lambda} expressions, so we
  16396. translate it to a regular \code{Assign} statement.
  16397. The top-level function definitions need to be updated to take an extra
  16398. closure parameter, but that parameter is ignored in the body of those
  16399. functions.
  16400. \subsection{An Example Translation}
  16401. \label{sec:example-lambda}
  16402. Figure~\ref{fig:lexical-functions-example} shows the result of
  16403. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16404. program demonstrating lexical scoping that we discussed at the
  16405. beginning of this chapter.
  16406. \begin{figure}[tbp]
  16407. \begin{tcolorbox}[colback=white]
  16408. \begin{minipage}{0.8\textwidth}
  16409. {\if\edition\racketEd
  16410. % tests/lambda_test_6.rkt
  16411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16412. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16413. (let ([y8 4])
  16414. (lambda: ([z9 : Integer]) : Integer
  16415. (+ x7 (+ y8 z9)))))
  16416. (define (main) : Integer
  16417. (let ([g0 ((fun-ref f6 1) 5)])
  16418. (let ([h1 ((fun-ref f6 1) 3)])
  16419. (+ (g0 11) (h1 15)))))
  16420. \end{lstlisting}
  16421. $\Rightarrow$
  16422. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16423. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16424. (let ([y8 4])
  16425. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16426. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16427. (let ([x7 (vector-ref fvs3 1)])
  16428. (let ([y8 (vector-ref fvs3 2)])
  16429. (+ x7 (+ y8 z9)))))
  16430. (define (main) : Integer
  16431. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16432. ((vector-ref clos5 0) clos5 5))])
  16433. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16434. ((vector-ref clos6 0) clos6 3))])
  16435. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16436. \end{lstlisting}
  16437. \fi}
  16438. %
  16439. {\if\edition\pythonEd\pythonColor
  16440. % free_var.py
  16441. \begin{lstlisting}
  16442. def f(x: int) -> Callable[[int],int]:
  16443. y = 4
  16444. return lambda z: x + y + z
  16445. g = f(5)
  16446. h = f(3)
  16447. print(g(11) + h(15))
  16448. \end{lstlisting}
  16449. $\Rightarrow$
  16450. \begin{lstlisting}
  16451. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16452. x = fvs_1[1]
  16453. y = fvs_1[2]
  16454. return (x + y[0] + z)
  16455. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16456. y = (uninitialized(int),)
  16457. y[0] = 4
  16458. return closure{1}({lambda_0}, x, y)
  16459. def main() -> int:
  16460. g = (begin: clos_3 = closure{1}({f})
  16461. clos_3[0](clos_3, 5))
  16462. h = (begin: clos_4 = closure{1}({f})
  16463. clos_4[0](clos_4, 3))
  16464. print((begin: clos_5 = g
  16465. clos_5[0](clos_5, 11))
  16466. + (begin: clos_6 = h
  16467. clos_6[0](clos_6, 15)))
  16468. return 0
  16469. \end{lstlisting}
  16470. \fi}
  16471. \end{minipage}
  16472. \end{tcolorbox}
  16473. \caption{Example of closure conversion.}
  16474. \label{fig:lexical-functions-example}
  16475. \end{figure}
  16476. \begin{exercise}\normalfont\normalsize
  16477. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16478. Create five new programs that use \key{lambda} functions and make use of
  16479. lexical scoping. Test your compiler on these new programs and all
  16480. your previously created test programs.
  16481. \end{exercise}
  16482. \section{Expose Allocation}
  16483. \label{sec:expose-allocation-r5}
  16484. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16485. allocates and initializes a tuple, similar to the translation of the
  16486. tuple creation in section~\ref{sec:expose-allocation}. The main
  16487. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16488. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16489. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16490. type, but only a single element tuple type. The types of the tuple
  16491. elements that correspond to the free variables of the closure should
  16492. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16493. can be used to adjust the result type.
  16494. \section{Explicate Control and \LangCLam{}}
  16495. \label{sec:explicate-r5}
  16496. The output language of \code{explicate\_control} is \LangCLam{}; the
  16497. definition of its abstract syntax is shown in
  16498. figure~\ref{fig:Clam-syntax}.
  16499. %
  16500. \racket{The only differences with respect to \LangCFun{} are the
  16501. addition of the \code{AllocateClosure} form to the grammar for
  16502. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16503. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16504. similar to the handling of other expressions such as primitive
  16505. operators.}
  16506. %
  16507. \python{The differences with respect to \LangCFun{} are the
  16508. additions of \code{Uninitialized}, \code{AllocateClosure},
  16509. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16510. \code{explicate\_control} pass is similar to the handling of other
  16511. expressions such as primitive operators.}
  16512. \newcommand{\ClambdaASTRacket}{
  16513. \begin{array}{lcl}
  16514. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16515. \itm{op} &::= & \code{procedure-arity}
  16516. \end{array}
  16517. }
  16518. \newcommand{\ClambdaASTPython}{
  16519. \begin{array}{lcl}
  16520. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16521. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16522. &\MID& \ARITY{\Atm}
  16523. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16524. \end{array}
  16525. }
  16526. \begin{figure}[tp]
  16527. \begin{tcolorbox}[colback=white]
  16528. \small
  16529. {\if\edition\racketEd
  16530. \[
  16531. \begin{array}{l}
  16532. \gray{\CvarASTRacket} \\ \hline
  16533. \gray{\CifASTRacket} \\ \hline
  16534. \gray{\CloopASTRacket} \\ \hline
  16535. \gray{\CtupASTRacket} \\ \hline
  16536. \gray{\CfunASTRacket} \\ \hline
  16537. \ClambdaASTRacket \\
  16538. \begin{array}{lcl}
  16539. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16540. \end{array}
  16541. \end{array}
  16542. \]
  16543. \fi}
  16544. {\if\edition\pythonEd\pythonColor
  16545. \[
  16546. \begin{array}{l}
  16547. \gray{\CifASTPython} \\ \hline
  16548. \gray{\CtupASTPython} \\ \hline
  16549. \gray{\CfunASTPython} \\ \hline
  16550. \ClambdaASTPython \\
  16551. \begin{array}{lcl}
  16552. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16553. \end{array}
  16554. \end{array}
  16555. \]
  16556. \fi}
  16557. \end{tcolorbox}
  16558. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16559. \label{fig:Clam-syntax}
  16560. \end{figure}
  16561. \section{Select Instructions}
  16562. \label{sec:select-instructions-Llambda}
  16563. \index{subject}{select instructions}
  16564. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16565. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16566. (section~\ref{sec:select-instructions-gc}). The only difference is
  16567. that you should place the \itm{arity} in the tag that is stored at
  16568. position $0$ of the tuple. Recall that in
  16569. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16570. was not used. We store the arity in the $5$ bits starting at position
  16571. $58$.
  16572. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16573. instructions that access the tag from position $0$ of the vector and
  16574. extract the $5$ bits starting at position $58$ from the tag.}
  16575. %
  16576. \python{Compile a call to the \code{arity} operator to a sequence of
  16577. instructions that access the tag from position $0$ of the tuple
  16578. (representing a closure) and extract the $5$ bits starting at position
  16579. $58$ from the tag.}
  16580. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16581. needed for the compilation of \LangLam{}.
  16582. \begin{figure}[bthp]
  16583. \begin{tcolorbox}[colback=white]
  16584. {\if\edition\racketEd
  16585. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16586. \node (Lfun) at (0,2) {\large \LangLam{}};
  16587. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16588. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16589. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16590. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16591. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16592. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16593. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16594. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16595. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16596. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16597. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16598. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16599. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16600. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16601. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16602. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16603. \path[->,bend left=15] (Lfun) edge [above] node
  16604. {\ttfamily\footnotesize shrink} (Lfun-2);
  16605. \path[->,bend left=15] (Lfun-2) edge [above] node
  16606. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16607. \path[->,bend left=15] (Lfun-3) edge [above] node
  16608. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16609. \path[->,bend left=15] (F1-0) edge [left] node
  16610. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16611. \path[->,bend left=15] (F1-1) edge [below] node
  16612. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16613. \path[->,bend right=15] (F1-2) edge [above] node
  16614. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16615. \path[->,bend right=15] (F1-3) edge [above] node
  16616. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16617. \path[->,bend left=15] (F1-4) edge [right] node
  16618. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16619. \path[->,bend right=15] (F1-5) edge [below] node
  16620. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16621. \path[->,bend left=15] (F1-6) edge [above] node
  16622. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16623. \path[->] (C3-2) edge [right] node
  16624. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16625. \path[->,bend right=15] (x86-2) edge [right] node
  16626. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16627. \path[->,bend right=15] (x86-2-1) edge [below] node
  16628. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16629. \path[->,bend right=15] (x86-2-2) edge [right] node
  16630. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16631. \path[->,bend left=15] (x86-3) edge [above] node
  16632. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16633. \path[->,bend left=15] (x86-4) edge [right] node
  16634. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16635. \end{tikzpicture}
  16636. \fi}
  16637. {\if\edition\pythonEd\pythonColor
  16638. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16639. \node (Lfun) at (0,2) {\large \LangLam{}};
  16640. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16641. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16642. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16643. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16644. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16645. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16646. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16647. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16648. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16649. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16650. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16651. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16652. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16653. \path[->,bend left=15] (Lfun) edge [above] node
  16654. {\ttfamily\footnotesize shrink} (Lfun-2);
  16655. \path[->,bend left=15] (Lfun-2) edge [above] node
  16656. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16657. \path[->,bend left=15] (Lfun-3) edge [above] node
  16658. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16659. \path[->,bend left=15] (F1-0) edge [left] node
  16660. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16661. \path[->,bend left=15] (F1-1) edge [below] node
  16662. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16663. \path[->,bend left=15] (F1-2) edge [below] node
  16664. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16665. \path[->,bend right=15] (F1-3) edge [above] node
  16666. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16667. \path[->,bend right=15] (F1-5) edge [right] node
  16668. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16669. \path[->,bend left=15] (F1-6) edge [right] node
  16670. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16671. \path[->,bend right=15] (C3-2) edge [right] node
  16672. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16673. \path[->,bend right=15] (x86-2) edge [below] node
  16674. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16675. \path[->,bend right=15] (x86-3) edge [below] node
  16676. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16677. \path[->,bend left=15] (x86-4) edge [above] node
  16678. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16679. \end{tikzpicture}
  16680. \fi}
  16681. \end{tcolorbox}
  16682. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16683. functions.}
  16684. \label{fig:Llambda-passes}
  16685. \end{figure}
  16686. \clearpage
  16687. \section{Challenge: Optimize Closures}
  16688. \label{sec:optimize-closures}
  16689. In this chapter we compile lexically scoped functions into a
  16690. relatively efficient representation: flat closures. However, even this
  16691. representation comes with some overhead. For example, consider the
  16692. following program with a function \code{tail\_sum} that does not have
  16693. any free variables and where all the uses of \code{tail\_sum} are in
  16694. applications in which we know that only \code{tail\_sum} is being applied
  16695. (and not any other functions):
  16696. \begin{center}
  16697. \begin{minipage}{0.95\textwidth}
  16698. {\if\edition\racketEd
  16699. \begin{lstlisting}
  16700. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16701. (if (eq? n 0)
  16702. s
  16703. (tail_sum (- n 1) (+ n s))))
  16704. (+ (tail_sum 3 0) 36)
  16705. \end{lstlisting}
  16706. \fi}
  16707. {\if\edition\pythonEd\pythonColor
  16708. \begin{lstlisting}
  16709. def tail_sum(n : int, s : int) -> int:
  16710. if n == 0:
  16711. return s
  16712. else:
  16713. return tail_sum(n - 1, n + s)
  16714. print(tail_sum(3, 0) + 36)
  16715. \end{lstlisting}
  16716. \fi}
  16717. \end{minipage}
  16718. \end{center}
  16719. As described in this chapter, we uniformly apply closure conversion to
  16720. all functions, obtaining the following output for this program:
  16721. \begin{center}
  16722. \begin{minipage}{0.95\textwidth}
  16723. {\if\edition\racketEd
  16724. \begin{lstlisting}
  16725. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16726. (if (eq? n2 0)
  16727. s3
  16728. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16729. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16730. (define (main) : Integer
  16731. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16732. ((vector-ref clos6 0) clos6 3 0)) 27))
  16733. \end{lstlisting}
  16734. \fi}
  16735. {\if\edition\pythonEd\pythonColor
  16736. \begin{lstlisting}
  16737. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16738. if n_0 == 0:
  16739. return s_1
  16740. else:
  16741. return (begin: clos_2 = (tail_sum,)
  16742. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16743. def main() -> int :
  16744. print((begin: clos_4 = (tail_sum,)
  16745. clos_4[0](clos_4, 3, 0)) + 36)
  16746. return 0
  16747. \end{lstlisting}
  16748. \fi}
  16749. \end{minipage}
  16750. \end{center}
  16751. If this program were compiled according to the previous chapter, there
  16752. would be no allocation and the calls to \code{tail\_sum} would be
  16753. direct calls. In contrast, the program presented here allocates memory
  16754. for each closure and the calls to \code{tail\_sum} are indirect. These
  16755. two differences incur considerable overhead in a program such as this,
  16756. in which the allocations and indirect calls occur inside a tight loop.
  16757. One might think that this problem is trivial to solve: can't we just
  16758. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16759. and compile them to direct calls instead of treating it like a call to
  16760. a closure? We would also drop the new \code{fvs} parameter of
  16761. \code{tail\_sum}.
  16762. %
  16763. However, this problem is not so trivial, because a global function may
  16764. \emph{escape} and become involved in applications that also involve
  16765. closures. Consider the following example in which the application
  16766. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16767. application because the \code{lambda} may flow into \code{f}, but the
  16768. \code{inc} function might also flow into \code{f}:
  16769. \begin{center}
  16770. \begin{minipage}{\textwidth}
  16771. % lambda_test_30.rkt
  16772. {\if\edition\racketEd
  16773. \begin{lstlisting}
  16774. (define (inc [x : Integer]) : Integer
  16775. (+ x 1))
  16776. (let ([y (read)])
  16777. (let ([f (if (eq? (read) 0)
  16778. inc
  16779. (lambda: ([x : Integer]) : Integer (- x y)))])
  16780. (f 41)))
  16781. \end{lstlisting}
  16782. \fi}
  16783. {\if\edition\pythonEd\pythonColor
  16784. \begin{lstlisting}
  16785. def add1(x : int) -> int:
  16786. return x + 1
  16787. y = input_int()
  16788. g : Callable[[int], int] = lambda x: x - y
  16789. f = add1 if input_int() == 0 else g
  16790. print(f(41))
  16791. \end{lstlisting}
  16792. \fi}
  16793. \end{minipage}
  16794. \end{center}
  16795. If a global function name is used in any way other than as the
  16796. operator in a direct call, then we say that the function
  16797. \emph{escapes}. If a global function does not escape, then we do not
  16798. need to perform closure conversion on the function.
  16799. \begin{exercise}\normalfont\normalsize
  16800. Implement an auxiliary function for detecting which global
  16801. functions escape. Using that function, implement an improved version
  16802. of closure conversion that does not apply closure conversion to
  16803. global functions that do not escape but instead compiles them as
  16804. regular functions. Create several new test cases that check whether
  16805. your compiler properly detects whether global functions escape or not.
  16806. \end{exercise}
  16807. So far we have reduced the overhead of calling global functions, but
  16808. it would also be nice to reduce the overhead of calling a
  16809. \code{lambda} when we can determine at compile time which
  16810. \code{lambda} will be called. We refer to such calls as \emph{known
  16811. calls}. Consider the following example in which a \code{lambda} is
  16812. bound to \code{f} and then applied.
  16813. {\if\edition\racketEd
  16814. % lambda_test_9.rkt
  16815. \begin{lstlisting}
  16816. (let ([y (read)])
  16817. (let ([f (lambda: ([x : Integer]) : Integer
  16818. (+ x y))])
  16819. (f 21)))
  16820. \end{lstlisting}
  16821. \fi}
  16822. {\if\edition\pythonEd\pythonColor
  16823. \begin{lstlisting}
  16824. y = input_int()
  16825. f : Callable[[int],int] = lambda x: x + y
  16826. print(f(21))
  16827. \end{lstlisting}
  16828. \fi}
  16829. %
  16830. \noindent Closure conversion compiles the application
  16831. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16832. %
  16833. {\if\edition\racketEd
  16834. \begin{lstlisting}
  16835. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16836. (let ([y2 (vector-ref fvs6 1)])
  16837. (+ x3 y2)))
  16838. (define (main) : Integer
  16839. (let ([y2 (read)])
  16840. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16841. ((vector-ref f4 0) f4 21))))
  16842. \end{lstlisting}
  16843. \fi}
  16844. {\if\edition\pythonEd\pythonColor
  16845. \begin{lstlisting}
  16846. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16847. y_1 = fvs_4[1]
  16848. return x_2 + y_1[0]
  16849. def main() -> int:
  16850. y_1 = (777,)
  16851. y_1[0] = input_int()
  16852. f_0 = (lambda_3, y_1)
  16853. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16854. return 0
  16855. \end{lstlisting}
  16856. \fi}
  16857. %
  16858. \noindent However, we can instead compile the application
  16859. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16860. %
  16861. {\if\edition\racketEd
  16862. \begin{lstlisting}
  16863. (define (main) : Integer
  16864. (let ([y2 (read)])
  16865. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16866. ((fun-ref lambda5 1) f4 21))))
  16867. \end{lstlisting}
  16868. \fi}
  16869. {\if\edition\pythonEd\pythonColor
  16870. \begin{lstlisting}
  16871. def main() -> int:
  16872. y_1 = (777,)
  16873. y_1[0] = input_int()
  16874. f_0 = (lambda_3, y_1)
  16875. print(lambda_3(f_0, 21))
  16876. return 0
  16877. \end{lstlisting}
  16878. \fi}
  16879. The problem of determining which \code{lambda} will be called from a
  16880. particular application is quite challenging in general and the topic
  16881. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16882. following exercise we recommend that you compile an application to a
  16883. direct call when the operator is a variable and \racket{the variable
  16884. is \code{let}-bound to a closure}\python{the previous assignment to
  16885. the variable is a closure}. This can be accomplished by maintaining
  16886. an environment that maps variables to function names. Extend the
  16887. environment whenever you encounter a closure on the right-hand side of
  16888. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16889. name of the global function for the closure. This pass should come
  16890. after closure conversion.
  16891. \begin{exercise}\normalfont\normalsize
  16892. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16893. compiles known calls into direct calls. Verify that your compiler is
  16894. successful in this regard on several example programs.
  16895. \end{exercise}
  16896. These exercises only scratch the surface of closure optimization. A
  16897. good next step for the interested reader is to look at the work of
  16898. \citet{Keep:2012ab}.
  16899. \section{Further Reading}
  16900. The notion of lexically scoped functions predates modern computers by
  16901. about a decade. They were invented by \citet{Church:1932aa}, who
  16902. proposed the lambda calculus as a foundation for logic. Anonymous
  16903. functions were included in the LISP~\citep{McCarthy:1960dz}
  16904. programming language but were initially dynamically scoped. The Scheme
  16905. dialect of LISP adopted lexical scoping, and
  16906. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16907. Scheme programs. However, environments were represented as linked
  16908. lists, so variable look-up was linear in the size of the
  16909. environment. \citet{Appel91} gives a detailed description of several
  16910. closure representations. In this chapter we represent environments
  16911. using flat closures, which were invented by
  16912. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16913. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16914. closures, variable look-up is constant time but the time to create a
  16915. closure is proportional to the number of its free variables. Flat
  16916. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16917. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16918. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16919. % compilers)
  16920. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16921. \chapter{Dynamic Typing}
  16922. \label{ch:Ldyn}
  16923. \index{subject}{dynamic typing}
  16924. \setcounter{footnote}{0}
  16925. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16926. typed language that is a subset of \racket{Racket}\python{Python}. The
  16927. focus on dynamic typing is in contrast to the previous chapters, which
  16928. have studied the compilation of statically typed languages. In
  16929. dynamically typed languages such as \LangDyn{}, a particular
  16930. expression may produce a value of a different type each time it is
  16931. executed. Consider the following example with a conditional \code{if}
  16932. expression that may return a Boolean or an integer depending on the
  16933. input to the program:
  16934. % part of dynamic_test_25.rkt
  16935. {\if\edition\racketEd
  16936. \begin{lstlisting}
  16937. (not (if (eq? (read) 1) #f 0))
  16938. \end{lstlisting}
  16939. \fi}
  16940. {\if\edition\pythonEd\pythonColor
  16941. \begin{lstlisting}
  16942. not (False if input_int() == 1 else 0)
  16943. \end{lstlisting}
  16944. \fi}
  16945. Languages that allow expressions to produce different kinds of values
  16946. are called \emph{polymorphic}, a word composed of the Greek roots
  16947. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16948. There are several kinds of polymorphism in programming languages, such as
  16949. subtype polymorphism\index{subject}{subtype polymorphism} and
  16950. parametric polymorphism\index{subject}{parametric polymorphism}
  16951. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16952. study in this chapter does not have a special name; it is the kind
  16953. that arises in dynamically typed languages.
  16954. Another characteristic of dynamically typed languages is that
  16955. their primitive operations, such as \code{not}, are often defined to operate
  16956. on many different types of values. In fact, in
  16957. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16958. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16959. given anything else it returns \FALSE{}.
  16960. Furthermore, even when primitive operations restrict their inputs to
  16961. values of a certain type, this restriction is enforced at runtime
  16962. instead of during compilation. For example, the tuple read
  16963. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16964. results in a runtime error because the first argument must
  16965. be a tuple, not a Boolean.
  16966. \section{The \LangDyn{} Language}
  16967. \newcommand{\LdynGrammarRacket}{
  16968. \begin{array}{rcl}
  16969. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16970. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16971. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16972. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16973. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16974. \end{array}
  16975. }
  16976. \newcommand{\LdynASTRacket}{
  16977. \begin{array}{lcl}
  16978. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16979. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16980. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16981. \end{array}
  16982. }
  16983. \begin{figure}[tp]
  16984. \centering
  16985. \begin{tcolorbox}[colback=white]
  16986. \small
  16987. {\if\edition\racketEd
  16988. \[
  16989. \begin{array}{l}
  16990. \gray{\LintGrammarRacket{}} \\ \hline
  16991. \gray{\LvarGrammarRacket{}} \\ \hline
  16992. \gray{\LifGrammarRacket{}} \\ \hline
  16993. \gray{\LwhileGrammarRacket} \\ \hline
  16994. \gray{\LtupGrammarRacket} \\ \hline
  16995. \LdynGrammarRacket \\
  16996. \begin{array}{rcl}
  16997. \LangDynM{} &::=& \Def\ldots\; \Exp
  16998. \end{array}
  16999. \end{array}
  17000. \]
  17001. \fi}
  17002. {\if\edition\pythonEd\pythonColor
  17003. \[
  17004. \begin{array}{rcl}
  17005. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17006. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17007. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17008. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17009. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17010. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17011. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17012. \MID \CLEN{\Exp} \\
  17013. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17014. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17015. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17016. \MID \Var\mathop{\key{=}}\Exp \\
  17017. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17018. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17019. &\MID& \CRETURN{\Exp} \\
  17020. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17021. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17022. \end{array}
  17023. \]
  17024. \fi}
  17025. \end{tcolorbox}
  17026. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17027. \label{fig:r7-concrete-syntax}
  17028. \end{figure}
  17029. \begin{figure}[tp]
  17030. \centering
  17031. \begin{tcolorbox}[colback=white]
  17032. \small
  17033. {\if\edition\racketEd
  17034. \[
  17035. \begin{array}{l}
  17036. \gray{\LintASTRacket{}} \\ \hline
  17037. \gray{\LvarASTRacket{}} \\ \hline
  17038. \gray{\LifASTRacket{}} \\ \hline
  17039. \gray{\LwhileASTRacket} \\ \hline
  17040. \gray{\LtupASTRacket} \\ \hline
  17041. \LdynASTRacket \\
  17042. \begin{array}{lcl}
  17043. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17044. \end{array}
  17045. \end{array}
  17046. \]
  17047. \fi}
  17048. {\if\edition\pythonEd\pythonColor
  17049. \[
  17050. \begin{array}{rcl}
  17051. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17052. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17053. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17054. \MID \code{Is()} \\
  17055. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17056. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17057. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17058. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17059. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17060. &\MID& \VAR{\Var{}}
  17061. \MID \BOOL{\itm{bool}}
  17062. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17063. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17064. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17065. &\MID& \LEN{\Exp} \\
  17066. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17067. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17068. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17069. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17070. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17071. &\MID& \RETURN{\Exp} \\
  17072. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17073. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17074. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17075. \end{array}
  17076. \]
  17077. \fi}
  17078. \end{tcolorbox}
  17079. \caption{The abstract syntax of \LangDyn{}.}
  17080. \label{fig:r7-syntax}
  17081. \end{figure}
  17082. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17083. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17084. %
  17085. There is no type checker for \LangDyn{} because it checks types only
  17086. at runtime.
  17087. The definitional interpreter for \LangDyn{} is presented in
  17088. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17089. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17090. \INT{n}. Instead of simply returning the integer \code{n} (as
  17091. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17092. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17093. value} that combines an underlying value with a tag that identifies
  17094. what kind of value it is. We define the following \racket{struct}\python{class}
  17095. to represent tagged values:
  17096. %
  17097. {\if\edition\racketEd
  17098. \begin{lstlisting}
  17099. (struct Tagged (value tag) #:transparent)
  17100. \end{lstlisting}
  17101. \fi}
  17102. {\if\edition\pythonEd\pythonColor
  17103. \begin{minipage}{\textwidth}
  17104. \begin{lstlisting}
  17105. @dataclass(eq=True)
  17106. class Tagged(Value):
  17107. value : Value
  17108. tag : str
  17109. def __str__(self):
  17110. return str(self.value)
  17111. \end{lstlisting}
  17112. \end{minipage}
  17113. \fi}
  17114. %
  17115. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17116. \code{Vector}, and \code{Procedure}.}
  17117. %
  17118. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17119. \skey{tuple}, and \skey{function}.}
  17120. %
  17121. Tags are closely related to types but do not always capture all the
  17122. information that a type does.
  17123. %
  17124. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17125. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17126. Any)} is tagged with \code{Procedure}.}
  17127. %
  17128. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17129. is tagged with \skey{tuple} and a function of type
  17130. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17131. is tagged with \skey{function}.}
  17132. Next consider the match case for accessing the element of a tuple.
  17133. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17134. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17135. argument is a tuple and the second is an integer.
  17136. \racket{
  17137. If they are not, a \code{trapped-error} is raised. Recall from
  17138. section~\ref{sec:interp_Lint} that when a definition interpreter
  17139. raises a \code{trapped-error} error, the compiled code must also
  17140. signal an error by exiting with return code \code{255}. A
  17141. \code{trapped-error} is also raised if the index is not less than the
  17142. length of the vector.
  17143. }
  17144. %
  17145. \python{If they are not, an exception is raised. The compiled code
  17146. must also signal an error by exiting with return code \code{255}. A
  17147. exception is also raised if the index is not less than the length of the
  17148. tuple or if it is negative.}
  17149. \begin{figure}[tbp]
  17150. \begin{tcolorbox}[colback=white]
  17151. {\if\edition\racketEd
  17152. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17153. (define ((interp-Ldyn-exp env) ast)
  17154. (define recur (interp-Ldyn-exp env))
  17155. (match ast
  17156. [(Var x) (dict-ref env x)]
  17157. [(Int n) (Tagged n 'Integer)]
  17158. [(Bool b) (Tagged b 'Boolean)]
  17159. [(Lambda xs rt body)
  17160. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17161. [(Prim 'vector es)
  17162. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17163. [(Prim 'vector-ref (list e1 e2))
  17164. (define vec (recur e1)) (define i (recur e2))
  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-ref (Tagged-value vec) (Tagged-value i))]
  17169. [(Prim 'vector-set! (list e1 e2 e3))
  17170. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17171. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17172. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17173. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17174. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17175. (Tagged (void) 'Void)]
  17176. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17177. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17178. [(Prim 'or (list e1 e2))
  17179. (define v1 (recur e1))
  17180. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17181. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17182. [(Prim op (list e1))
  17183. #:when (set-member? type-predicates op)
  17184. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17185. [(Prim op es)
  17186. (define args (map recur es))
  17187. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17188. (unless (for/or ([expected-tags (op-tags op)])
  17189. (equal? expected-tags tags))
  17190. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17191. (tag-value
  17192. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17193. [(If q t f)
  17194. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17195. [(Apply f es)
  17196. (define new-f (recur f)) (define args (map recur es))
  17197. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17198. (match f-val
  17199. [`(function ,xs ,body ,lam-env)
  17200. (unless (eq? (length xs) (length args))
  17201. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17202. (define new-env (append (map cons xs args) lam-env))
  17203. ((interp-Ldyn-exp new-env) body)]
  17204. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17205. \end{lstlisting}
  17206. \fi}
  17207. {\if\edition\pythonEd\pythonColor
  17208. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17209. class InterpLdyn(InterpLlambda):
  17210. def interp_exp(self, e, env):
  17211. match e:
  17212. case Constant(n):
  17213. return self.tag(super().interp_exp(e, env))
  17214. case Tuple(es, Load()):
  17215. return self.tag(super().interp_exp(e, env))
  17216. case Lambda(params, body):
  17217. return self.tag(super().interp_exp(e, env))
  17218. case Call(Name('input_int'), []):
  17219. return self.tag(super().interp_exp(e, env))
  17220. case BinOp(left, Add(), right):
  17221. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17222. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17223. case BinOp(left, Sub(), right):
  17224. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17225. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17226. case UnaryOp(USub(), e1):
  17227. v = self.interp_exp(e1, env)
  17228. return self.tag(- self.untag(v, 'int', e))
  17229. case IfExp(test, body, orelse):
  17230. v = self.interp_exp(test, env)
  17231. if self.untag(v, 'bool', e):
  17232. return self.interp_exp(body, env)
  17233. else:
  17234. return self.interp_exp(orelse, env)
  17235. case UnaryOp(Not(), e1):
  17236. v = self.interp_exp(e1, env)
  17237. return self.tag(not self.untag(v, 'bool', e))
  17238. case BoolOp(And(), values):
  17239. left = values[0]; right = values[1]
  17240. l = self.interp_exp(left, env)
  17241. if self.untag(l, 'bool', e):
  17242. return self.interp_exp(right, env)
  17243. else:
  17244. return self.tag(False)
  17245. case BoolOp(Or(), values):
  17246. left = values[0]; right = values[1]
  17247. l = self.interp_exp(left, env)
  17248. if self.untag(l, 'bool', e):
  17249. return self.tag(True)
  17250. else:
  17251. return self.interp_exp(right, env)
  17252. \end{lstlisting}
  17253. \fi}
  17254. \end{tcolorbox}
  17255. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17256. \label{fig:interp-Ldyn}
  17257. \end{figure}
  17258. {\if\edition\pythonEd\pythonColor
  17259. \begin{figure}[tbp]
  17260. \begin{tcolorbox}[colback=white]
  17261. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17262. # interp_exp continued
  17263. case Compare(left, [cmp], [right]):
  17264. l = self.interp_exp(left, env)
  17265. r = self.interp_exp(right, env)
  17266. if l.tag == r.tag:
  17267. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17268. else:
  17269. raise Exception('interp Compare unexpected '
  17270. + repr(l) + ' ' + repr(r))
  17271. case Subscript(tup, index, Load()):
  17272. t = self.interp_exp(tup, env)
  17273. n = self.interp_exp(index, env)
  17274. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17275. case Call(Name('len'), [tup]):
  17276. t = self.interp_exp(tup, env)
  17277. return self.tag(len(self.untag(t, 'tuple', e)))
  17278. case _:
  17279. return self.tag(super().interp_exp(e, env))
  17280. def interp_stmt(self, s, env, cont):
  17281. match s:
  17282. case If(test, body, orelse):
  17283. v = self.interp_exp(test, env)
  17284. match self.untag(v, 'bool', s):
  17285. case True:
  17286. return self.interp_stmts(body + cont, env)
  17287. case False:
  17288. return self.interp_stmts(orelse + cont, env)
  17289. case While(test, body, []):
  17290. v = self.interp_exp(test, env)
  17291. if self.untag(v, 'bool', test):
  17292. self.interp_stmts(body + [s] + cont, env)
  17293. else:
  17294. return self.interp_stmts(cont, env)
  17295. case Assign([Subscript(tup, index)], value):
  17296. tup = self.interp_exp(tup, env)
  17297. index = self.interp_exp(index, env)
  17298. tup_v = self.untag(tup, 'tuple', s)
  17299. index_v = self.untag(index, 'int', s)
  17300. tup_v[index_v] = self.interp_exp(value, env)
  17301. return self.interp_stmts(cont, env)
  17302. case FunctionDef(name, params, bod, dl, returns, comment):
  17303. if isinstance(params, ast.arguments):
  17304. ps = [p.arg for p in params.args]
  17305. else:
  17306. ps = [x for (x,t) in params]
  17307. env[name] = self.tag(Function(name, ps, bod, env))
  17308. return self.interp_stmts(cont, env)
  17309. case _:
  17310. return super().interp_stmt(s, env, cont)
  17311. \end{lstlisting}
  17312. \end{tcolorbox}
  17313. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17314. \label{fig:interp-Ldyn-2}
  17315. \end{figure}
  17316. \fi}
  17317. \begin{figure}[tbp]
  17318. \begin{tcolorbox}[colback=white]
  17319. {\if\edition\racketEd
  17320. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17321. (define (interp-op op)
  17322. (match op
  17323. ['+ fx+]
  17324. ['- fx-]
  17325. ['read read-fixnum]
  17326. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17327. ['< (lambda (v1 v2)
  17328. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17329. ['<= (lambda (v1 v2)
  17330. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17331. ['> (lambda (v1 v2)
  17332. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17333. ['>= (lambda (v1 v2)
  17334. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17335. ['boolean? boolean?]
  17336. ['integer? fixnum?]
  17337. ['void? void?]
  17338. ['vector? vector?]
  17339. ['vector-length vector-length]
  17340. ['procedure? (match-lambda
  17341. [`(functions ,xs ,body ,env) #t] [else #f])]
  17342. [else (error 'interp-op "unknown operator" op)]))
  17343. (define (op-tags op)
  17344. (match op
  17345. ['+ '((Integer Integer))]
  17346. ['- '((Integer Integer) (Integer))]
  17347. ['read '(())]
  17348. ['not '((Boolean))]
  17349. ['< '((Integer Integer))]
  17350. ['<= '((Integer Integer))]
  17351. ['> '((Integer Integer))]
  17352. ['>= '((Integer Integer))]
  17353. ['vector-length '((Vector))]))
  17354. (define type-predicates
  17355. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17356. (define (tag-value v)
  17357. (cond [(boolean? v) (Tagged v 'Boolean)]
  17358. [(fixnum? v) (Tagged v 'Integer)]
  17359. [(procedure? v) (Tagged v 'Procedure)]
  17360. [(vector? v) (Tagged v 'Vector)]
  17361. [(void? v) (Tagged v 'Void)]
  17362. [else (error 'tag-value "unidentified value ~a" v)]))
  17363. (define (check-tag val expected ast)
  17364. (define tag (Tagged-tag val))
  17365. (unless (eq? tag expected)
  17366. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17367. \end{lstlisting}
  17368. \fi}
  17369. {\if\edition\pythonEd\pythonColor
  17370. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17371. class InterpLdyn(InterpLlambda):
  17372. def tag(self, v):
  17373. if v is True or v is False:
  17374. return Tagged(v, 'bool')
  17375. elif isinstance(v, int):
  17376. return Tagged(v, 'int')
  17377. elif isinstance(v, Function):
  17378. return Tagged(v, 'function')
  17379. elif isinstance(v, tuple):
  17380. return Tagged(v, 'tuple')
  17381. elif isinstance(v, type(None)):
  17382. return Tagged(v, 'none')
  17383. else:
  17384. raise Exception('tag: unexpected ' + repr(v))
  17385. def untag(self, v, expected_tag, ast):
  17386. match v:
  17387. case Tagged(val, tag) if tag == expected_tag:
  17388. return val
  17389. case _:
  17390. raise TrappedError('expected Tagged value with '
  17391. + expected_tag + ', not ' + ' ' + repr(v))
  17392. def apply_fun(self, fun, args, e):
  17393. f = self.untag(fun, 'function', e)
  17394. return super().apply_fun(f, args, e)
  17395. \end{lstlisting}
  17396. \fi}
  17397. \end{tcolorbox}
  17398. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17399. \label{fig:interp-Ldyn-aux}
  17400. \end{figure}
  17401. %\clearpage
  17402. \section{Representation of Tagged Values}
  17403. The interpreter for \LangDyn{} introduced a new kind of value: the
  17404. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17405. represent tagged values at the bit level. Because almost every
  17406. operation in \LangDyn{} involves manipulating tagged values, the
  17407. representation must be efficient. Recall that all our values are 64
  17408. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17409. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17410. $011$ for procedures, and $101$ for the void value\python{,
  17411. \key{None}}. We define the following auxiliary function for mapping
  17412. types to tag codes:
  17413. %
  17414. {\if\edition\racketEd
  17415. \begin{align*}
  17416. \itm{tagof}(\key{Integer}) &= 001 \\
  17417. \itm{tagof}(\key{Boolean}) &= 100 \\
  17418. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17419. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17420. \itm{tagof}(\key{Void}) &= 101
  17421. \end{align*}
  17422. \fi}
  17423. {\if\edition\pythonEd\pythonColor
  17424. \begin{align*}
  17425. \itm{tagof}(\key{IntType()}) &= 001 \\
  17426. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17427. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17428. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17429. \itm{tagof}(\key{type(None)}) &= 101
  17430. \end{align*}
  17431. \fi}
  17432. %
  17433. This stealing of 3 bits comes at some price: integers are now restricted
  17434. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17435. affect tuples and procedures because those values are addresses, and
  17436. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17437. they are always $000$. Thus, we do not lose information by overwriting
  17438. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17439. to recover the original address.
  17440. To make tagged values into first-class entities, we can give them a
  17441. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17442. operations such as \code{Inject} and \code{Project} for creating and
  17443. using them, yielding the statically typed \LangAny{} intermediate
  17444. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17445. section~\ref{sec:compile-r7}; in the next section we describe the
  17446. \LangAny{} language in greater detail.
  17447. \section{The \LangAny{} Language}
  17448. \label{sec:Rany-lang}
  17449. \newcommand{\LanyASTRacket}{
  17450. \begin{array}{lcl}
  17451. \Type &::= & \ANYTY \\
  17452. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17453. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17454. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17455. \itm{op} &::= & \code{any-vector-length}
  17456. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17457. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17458. \MID \code{procedure?} \MID \code{void?} \\
  17459. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17460. \end{array}
  17461. }
  17462. \newcommand{\LanyASTPython}{
  17463. \begin{array}{lcl}
  17464. \Type &::= & \key{AnyType()} \\
  17465. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17466. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17467. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17468. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17469. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17470. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17471. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17472. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17473. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17474. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17475. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17476. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17477. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17478. \end{array}
  17479. }
  17480. \begin{figure}[tp]
  17481. \centering
  17482. \begin{tcolorbox}[colback=white]
  17483. \small
  17484. {\if\edition\racketEd
  17485. \[
  17486. \begin{array}{l}
  17487. \gray{\LintOpAST} \\ \hline
  17488. \gray{\LvarASTRacket{}} \\ \hline
  17489. \gray{\LifASTRacket{}} \\ \hline
  17490. \gray{\LwhileASTRacket{}} \\ \hline
  17491. \gray{\LtupASTRacket{}} \\ \hline
  17492. \gray{\LfunASTRacket} \\ \hline
  17493. \gray{\LlambdaASTRacket} \\ \hline
  17494. \LanyASTRacket \\
  17495. \begin{array}{lcl}
  17496. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17497. \end{array}
  17498. \end{array}
  17499. \]
  17500. \fi}
  17501. {\if\edition\pythonEd\pythonColor
  17502. \[
  17503. \begin{array}{l}
  17504. \gray{\LintASTPython} \\ \hline
  17505. \gray{\LvarASTPython{}} \\ \hline
  17506. \gray{\LifASTPython{}} \\ \hline
  17507. \gray{\LwhileASTPython{}} \\ \hline
  17508. \gray{\LtupASTPython{}} \\ \hline
  17509. \gray{\LfunASTPython} \\ \hline
  17510. \gray{\LlambdaASTPython} \\ \hline
  17511. \LanyASTPython \\
  17512. \begin{array}{lcl}
  17513. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17514. \end{array}
  17515. \end{array}
  17516. \]
  17517. \fi}
  17518. \end{tcolorbox}
  17519. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17520. \label{fig:Lany-syntax}
  17521. \end{figure}
  17522. The definition of the abstract syntax of \LangAny{} is given in
  17523. figure~\ref{fig:Lany-syntax}.
  17524. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17525. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17526. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17527. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17528. converts the tagged value produced by expression $e$ into a value of
  17529. type $T$ or halts the program if the type tag does not match $T$.
  17530. %
  17531. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17532. restricted to be a flat type (the nonterminal $\FType$) which
  17533. simplifies the implementation and complies with the needs for
  17534. compiling \LangDyn{}.
  17535. The \racket{\code{any-vector}} operators
  17536. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17537. operations so that they can be applied to a value of type
  17538. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17539. tuple operations in that the index is not restricted to a literal
  17540. integer in the grammar but is allowed to be any expression.
  17541. \racket{The type predicates such as
  17542. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17543. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17544. the predicate and return {\FALSE} otherwise.}
  17545. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17546. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17547. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17548. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17549. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17550. \begin{figure}[btp]
  17551. \begin{tcolorbox}[colback=white]
  17552. {\if\edition\racketEd
  17553. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17554. (define type-check-Lany-class
  17555. (class type-check-Llambda-class
  17556. (super-new)
  17557. (inherit check-type-equal?)
  17558. (define/override (type-check-exp env)
  17559. (lambda (e)
  17560. (define recur (type-check-exp env))
  17561. (match e
  17562. [(Inject e1 ty)
  17563. (unless (flat-ty? ty)
  17564. (error 'type-check "may only inject from flat type, not ~a" ty))
  17565. (define-values (new-e1 e-ty) (recur e1))
  17566. (check-type-equal? e-ty ty e)
  17567. (values (Inject new-e1 ty) 'Any)]
  17568. [(Project e1 ty)
  17569. (unless (flat-ty? ty)
  17570. (error 'type-check "may only project to flat type, not ~a" ty))
  17571. (define-values (new-e1 e-ty) (recur e1))
  17572. (check-type-equal? e-ty 'Any e)
  17573. (values (Project new-e1 ty) ty)]
  17574. [(Prim 'any-vector-length (list e1))
  17575. (define-values (e1^ t1) (recur e1))
  17576. (check-type-equal? t1 'Any e)
  17577. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17578. [(Prim 'any-vector-ref (list e1 e2))
  17579. (define-values (e1^ t1) (recur e1))
  17580. (define-values (e2^ t2) (recur e2))
  17581. (check-type-equal? t1 'Any e)
  17582. (check-type-equal? t2 'Integer e)
  17583. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17584. [(Prim 'any-vector-set! (list e1 e2 e3))
  17585. (define-values (e1^ t1) (recur e1))
  17586. (define-values (e2^ t2) (recur e2))
  17587. (define-values (e3^ t3) (recur e3))
  17588. (check-type-equal? t1 'Any e)
  17589. (check-type-equal? t2 'Integer e)
  17590. (check-type-equal? t3 'Any e)
  17591. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17592. [(Prim pred (list e1))
  17593. #:when (set-member? (type-predicates) pred)
  17594. (define-values (new-e1 e-ty) (recur e1))
  17595. (check-type-equal? e-ty 'Any e)
  17596. (values (Prim pred (list new-e1)) 'Boolean)]
  17597. [(Prim 'eq? (list arg1 arg2))
  17598. (define-values (e1 t1) (recur arg1))
  17599. (define-values (e2 t2) (recur arg2))
  17600. (match* (t1 t2)
  17601. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17602. [(other wise) (check-type-equal? t1 t2 e)])
  17603. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17604. [else ((super type-check-exp env) e)])))
  17605. ))
  17606. \end{lstlisting}
  17607. \fi}
  17608. {\if\edition\pythonEd\pythonColor
  17609. \begin{lstlisting}
  17610. class TypeCheckLany(TypeCheckLlambda):
  17611. def type_check_exp(self, e, env):
  17612. match e:
  17613. case Inject(value, typ):
  17614. self.check_exp(value, typ, env)
  17615. return AnyType()
  17616. case Project(value, typ):
  17617. self.check_exp(value, AnyType(), env)
  17618. return typ
  17619. case Call(Name('any_tuple_load'), [tup, index]):
  17620. self.check_exp(tup, AnyType(), env)
  17621. self.check_exp(index, IntType(), env)
  17622. return AnyType()
  17623. case Call(Name('any_len'), [tup]):
  17624. self.check_exp(tup, AnyType(), env)
  17625. return IntType()
  17626. case Call(Name('arity'), [fun]):
  17627. ty = self.type_check_exp(fun, env)
  17628. match ty:
  17629. case FunctionType(ps, rt):
  17630. return IntType()
  17631. case TupleType([FunctionType(ps,rs)]):
  17632. return IntType()
  17633. case _:
  17634. raise Exception('type check arity unexpected ' + repr(ty))
  17635. case Call(Name('make_any'), [value, tag]):
  17636. self.type_check_exp(value, env)
  17637. self.check_exp(tag, IntType(), env)
  17638. return AnyType()
  17639. case AnnLambda(params, returns, body):
  17640. new_env = {x:t for (x,t) in env.items()}
  17641. for (x,t) in params:
  17642. new_env[x] = t
  17643. return_t = self.type_check_exp(body, new_env)
  17644. self.check_type_equal(returns, return_t, e)
  17645. return FunctionType([t for (x,t) in params], return_t)
  17646. case _:
  17647. return super().type_check_exp(e, env)
  17648. \end{lstlisting}
  17649. \fi}
  17650. \end{tcolorbox}
  17651. \caption{Type checker for the \LangAny{} language.}
  17652. \label{fig:type-check-Lany}
  17653. \end{figure}
  17654. {\if\edition\racketEd
  17655. \begin{figure}[tbp]
  17656. \begin{tcolorbox}[colback=white]
  17657. \begin{lstlisting}
  17658. (define/override (operator-types)
  17659. (append
  17660. '((integer? . ((Any) . Boolean))
  17661. (vector? . ((Any) . Boolean))
  17662. (procedure? . ((Any) . Boolean))
  17663. (void? . ((Any) . Boolean)))
  17664. (super operator-types)))
  17665. (define/public (type-predicates)
  17666. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17667. (define/public (flat-ty? ty)
  17668. (match ty
  17669. [(or `Integer `Boolean `Void) #t]
  17670. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17671. [`(,ts ... -> ,rt)
  17672. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17673. [else #f]))
  17674. \end{lstlisting}
  17675. \end{tcolorbox}
  17676. \caption{Auxiliary methods for type checking \LangAny{}.}
  17677. \label{fig:type-check-Lany-aux}
  17678. \end{figure}
  17679. \fi}
  17680. \begin{figure}[tbp]
  17681. \begin{tcolorbox}[colback=white]
  17682. {\if\edition\racketEd
  17683. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17684. (define interp-Lany-class
  17685. (class interp-Llambda-class
  17686. (super-new)
  17687. (define/override (interp-op op)
  17688. (match op
  17689. ['boolean? (match-lambda
  17690. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17691. [else #f])]
  17692. ['integer? (match-lambda
  17693. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17694. [else #f])]
  17695. ['vector? (match-lambda
  17696. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17697. [else #f])]
  17698. ['procedure? (match-lambda
  17699. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17700. [else #f])]
  17701. ['eq? (match-lambda*
  17702. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17703. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17704. [ls (apply (super interp-op op) ls)])]
  17705. ['any-vector-ref (lambda (v i)
  17706. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17707. ['any-vector-set! (lambda (v i a)
  17708. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17709. ['any-vector-length (lambda (v)
  17710. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17711. [else (super interp-op op)]))
  17712. (define/override ((interp-exp env) e)
  17713. (define recur (interp-exp env))
  17714. (match e
  17715. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17716. [(Project e ty2) (apply-project (recur e) ty2)]
  17717. [else ((super interp-exp env) e)]))
  17718. ))
  17719. (define (interp-Lany p)
  17720. (send (new interp-Lany-class) interp-program p))
  17721. \end{lstlisting}
  17722. \fi}
  17723. {\if\edition\pythonEd\pythonColor
  17724. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17725. class InterpLany(InterpLlambda):
  17726. def interp_exp(self, e, env):
  17727. match e:
  17728. case Inject(value, typ):
  17729. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17730. case Project(value, typ):
  17731. match self.interp_exp(value, env):
  17732. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17733. return val
  17734. case _:
  17735. raise Exception('failed project to ' + self.type_to_tag(typ))
  17736. case Call(Name('any_tuple_load'), [tup, index]):
  17737. match self.interp_exp(tup, env):
  17738. case Tagged(v, tag):
  17739. return v[self.interp_exp(index, env)]
  17740. case _:
  17741. raise Exception('in any_tuple_load untagged value')
  17742. case Call(Name('any_len'), [value]):
  17743. match self.interp_exp(value, env):
  17744. case Tagged(value, tag):
  17745. return len(value)
  17746. case _:
  17747. raise Exception('interp any_len untagged value')
  17748. case Call(Name('arity'), [fun]):
  17749. return self.arity(self.interp_exp(fun, env))
  17750. case _:
  17751. return super().interp_exp(e, env)
  17752. \end{lstlisting}
  17753. \fi}
  17754. \end{tcolorbox}
  17755. \caption{Interpreter for \LangAny{}.}
  17756. \label{fig:interp-Lany}
  17757. \end{figure}
  17758. \begin{figure}[btp]
  17759. \begin{tcolorbox}[colback=white]
  17760. {\if\edition\racketEd
  17761. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17762. (define/public (apply-inject v tg) (Tagged v tg))
  17763. (define/public (apply-project v ty2)
  17764. (define tag2 (any-tag ty2))
  17765. (match v
  17766. [(Tagged v1 tag1)
  17767. (cond
  17768. [(eq? tag1 tag2)
  17769. (match ty2
  17770. [`(Vector ,ts ...)
  17771. (define l1 ((interp-op 'vector-length) v1))
  17772. (cond
  17773. [(eq? l1 (length ts)) v1]
  17774. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17775. l1 (length ts))])]
  17776. [`(,ts ... -> ,rt)
  17777. (match v1
  17778. [`(function ,xs ,body ,env)
  17779. (cond [(eq? (length xs) (length ts)) v1]
  17780. [else
  17781. (error 'apply-project "arity mismatch ~a != ~a"
  17782. (length xs) (length ts))])]
  17783. [else (error 'apply-project "expected function not ~a" v1)])]
  17784. [else v1])]
  17785. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17786. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17787. \end{lstlisting}
  17788. \fi}
  17789. {\if\edition\pythonEd\pythonColor
  17790. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17791. class InterpLany(InterpLlambda):
  17792. def type_to_tag(self, typ):
  17793. match typ:
  17794. case FunctionType(params, rt):
  17795. return 'function'
  17796. case TupleType(fields):
  17797. return 'tuple'
  17798. case IntType():
  17799. return 'int'
  17800. case BoolType():
  17801. return 'bool'
  17802. case _:
  17803. raise Exception('type_to_tag unexpected ' + repr(typ))
  17804. def arity(self, v):
  17805. match v:
  17806. case Function(name, params, body, env):
  17807. return len(params)
  17808. case _:
  17809. raise Exception('Lany arity unexpected ' + repr(v))
  17810. \end{lstlisting}
  17811. \fi}
  17812. \end{tcolorbox}
  17813. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17814. \label{fig:interp-Lany-aux}
  17815. \end{figure}
  17816. \clearpage
  17817. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17818. \label{sec:compile-r7}
  17819. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17820. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17821. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17822. is that given any subexpression $e$ in the \LangDyn{} program, the
  17823. pass will produce an expression $e'$ in \LangAny{} that has type
  17824. \ANYTY{}. For example, the first row in
  17825. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17826. \TRUE{}, which must be injected to produce an expression of type
  17827. \ANYTY{}.
  17828. %
  17829. The compilation of addition is shown in the second row of
  17830. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17831. representative of many primitive operations: the arguments have type
  17832. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17833. be performed.
  17834. The compilation of \key{lambda} (third row of
  17835. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17836. produce type annotations: we simply use \ANYTY{}.
  17837. %
  17838. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17839. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17840. this pass has to account for some differences in behavior between
  17841. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17842. permissive than \LangAny{} regarding what kind of values can be used
  17843. in various places. For example, the condition of an \key{if} does
  17844. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17845. of the same type (in that case the result is \code{\#f}).}
  17846. \begin{figure}[btp]
  17847. \centering
  17848. \begin{tcolorbox}[colback=white]
  17849. {\if\edition\racketEd
  17850. \begin{tabular}{lll}
  17851. \begin{minipage}{0.27\textwidth}
  17852. \begin{lstlisting}
  17853. #t
  17854. \end{lstlisting}
  17855. \end{minipage}
  17856. &
  17857. $\Rightarrow$
  17858. &
  17859. \begin{minipage}{0.65\textwidth}
  17860. \begin{lstlisting}
  17861. (inject #t Boolean)
  17862. \end{lstlisting}
  17863. \end{minipage}
  17864. \\[2ex]\hline
  17865. \begin{minipage}{0.27\textwidth}
  17866. \begin{lstlisting}
  17867. (+ |$e_1$| |$e_2$|)
  17868. \end{lstlisting}
  17869. \end{minipage}
  17870. &
  17871. $\Rightarrow$
  17872. &
  17873. \begin{minipage}{0.65\textwidth}
  17874. \begin{lstlisting}
  17875. (inject
  17876. (+ (project |$e'_1$| Integer)
  17877. (project |$e'_2$| Integer))
  17878. Integer)
  17879. \end{lstlisting}
  17880. \end{minipage}
  17881. \\[2ex]\hline
  17882. \begin{minipage}{0.27\textwidth}
  17883. \begin{lstlisting}
  17884. (lambda (|$x_1 \ldots$|) |$e$|)
  17885. \end{lstlisting}
  17886. \end{minipage}
  17887. &
  17888. $\Rightarrow$
  17889. &
  17890. \begin{minipage}{0.65\textwidth}
  17891. \begin{lstlisting}
  17892. (inject
  17893. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17894. (Any|$\ldots$|Any -> Any))
  17895. \end{lstlisting}
  17896. \end{minipage}
  17897. \\[2ex]\hline
  17898. \begin{minipage}{0.27\textwidth}
  17899. \begin{lstlisting}
  17900. (|$e_0$| |$e_1 \ldots e_n$|)
  17901. \end{lstlisting}
  17902. \end{minipage}
  17903. &
  17904. $\Rightarrow$
  17905. &
  17906. \begin{minipage}{0.65\textwidth}
  17907. \begin{lstlisting}
  17908. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17909. \end{lstlisting}
  17910. \end{minipage}
  17911. \\[2ex]\hline
  17912. \begin{minipage}{0.27\textwidth}
  17913. \begin{lstlisting}
  17914. (vector-ref |$e_1$| |$e_2$|)
  17915. \end{lstlisting}
  17916. \end{minipage}
  17917. &
  17918. $\Rightarrow$
  17919. &
  17920. \begin{minipage}{0.65\textwidth}
  17921. \begin{lstlisting}
  17922. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17923. \end{lstlisting}
  17924. \end{minipage}
  17925. \\[2ex]\hline
  17926. \begin{minipage}{0.27\textwidth}
  17927. \begin{lstlisting}
  17928. (if |$e_1$| |$e_2$| |$e_3$|)
  17929. \end{lstlisting}
  17930. \end{minipage}
  17931. &
  17932. $\Rightarrow$
  17933. &
  17934. \begin{minipage}{0.65\textwidth}
  17935. \begin{lstlisting}
  17936. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17937. \end{lstlisting}
  17938. \end{minipage}
  17939. \\[2ex]\hline
  17940. \begin{minipage}{0.27\textwidth}
  17941. \begin{lstlisting}
  17942. (eq? |$e_1$| |$e_2$|)
  17943. \end{lstlisting}
  17944. \end{minipage}
  17945. &
  17946. $\Rightarrow$
  17947. &
  17948. \begin{minipage}{0.65\textwidth}
  17949. \begin{lstlisting}
  17950. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17951. \end{lstlisting}
  17952. \end{minipage}
  17953. \\[2ex]\hline
  17954. \begin{minipage}{0.27\textwidth}
  17955. \begin{lstlisting}
  17956. (not |$e_1$|)
  17957. \end{lstlisting}
  17958. \end{minipage}
  17959. &
  17960. $\Rightarrow$
  17961. &
  17962. \begin{minipage}{0.65\textwidth}
  17963. \begin{lstlisting}
  17964. (if (eq? |$e'_1$| (inject #f Boolean))
  17965. (inject #t Boolean) (inject #f Boolean))
  17966. \end{lstlisting}
  17967. \end{minipage}
  17968. \end{tabular}
  17969. \fi}
  17970. {\if\edition\pythonEd\pythonColor
  17971. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17972. \begin{minipage}{0.23\textwidth}
  17973. \begin{lstlisting}
  17974. True
  17975. \end{lstlisting}
  17976. \end{minipage}
  17977. &
  17978. $\Rightarrow$
  17979. &
  17980. \begin{minipage}{0.7\textwidth}
  17981. \begin{lstlisting}
  17982. Inject(True, BoolType())
  17983. \end{lstlisting}
  17984. \end{minipage}
  17985. \\[2ex]\hline
  17986. \begin{minipage}{0.23\textwidth}
  17987. \begin{lstlisting}
  17988. |$e_1$| + |$e_2$|
  17989. \end{lstlisting}
  17990. \end{minipage}
  17991. &
  17992. $\Rightarrow$
  17993. &
  17994. \begin{minipage}{0.7\textwidth}
  17995. \begin{lstlisting}
  17996. Inject(Project(|$e'_1$|, IntType())
  17997. + Project(|$e'_2$|, IntType()),
  17998. IntType())
  17999. \end{lstlisting}
  18000. \end{minipage}
  18001. \\[2ex]\hline
  18002. \begin{minipage}{0.23\textwidth}
  18003. \begin{lstlisting}
  18004. lambda |$x_1 \ldots$|: |$e$|
  18005. \end{lstlisting}
  18006. \end{minipage}
  18007. &
  18008. $\Rightarrow$
  18009. &
  18010. \begin{minipage}{0.7\textwidth}
  18011. \begin{lstlisting}
  18012. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18013. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18014. \end{lstlisting}
  18015. \end{minipage}
  18016. \\[2ex]\hline
  18017. \begin{minipage}{0.23\textwidth}
  18018. \begin{lstlisting}
  18019. |$e_0$|(|$e_1 \ldots e_n$|)
  18020. \end{lstlisting}
  18021. \end{minipage}
  18022. &
  18023. $\Rightarrow$
  18024. &
  18025. \begin{minipage}{0.7\textwidth}
  18026. \begin{lstlisting}
  18027. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18028. AnyType())), |$e'_1, \ldots, e'_n$|)
  18029. \end{lstlisting}
  18030. \end{minipage}
  18031. \\[2ex]\hline
  18032. \begin{minipage}{0.23\textwidth}
  18033. \begin{lstlisting}
  18034. |$e_1$|[|$e_2$|]
  18035. \end{lstlisting}
  18036. \end{minipage}
  18037. &
  18038. $\Rightarrow$
  18039. &
  18040. \begin{minipage}{0.7\textwidth}
  18041. \begin{lstlisting}
  18042. Call(Name('any_tuple_load'),
  18043. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18044. \end{lstlisting}
  18045. \end{minipage}
  18046. %% \begin{minipage}{0.23\textwidth}
  18047. %% \begin{lstlisting}
  18048. %% |$e_2$| if |$e_1$| else |$e_3$|
  18049. %% \end{lstlisting}
  18050. %% \end{minipage}
  18051. %% &
  18052. %% $\Rightarrow$
  18053. %% &
  18054. %% \begin{minipage}{0.7\textwidth}
  18055. %% \begin{lstlisting}
  18056. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18057. %% \end{lstlisting}
  18058. %% \end{minipage}
  18059. %% \\[2ex]\hline
  18060. %% \begin{minipage}{0.23\textwidth}
  18061. %% \begin{lstlisting}
  18062. %% (eq? |$e_1$| |$e_2$|)
  18063. %% \end{lstlisting}
  18064. %% \end{minipage}
  18065. %% &
  18066. %% $\Rightarrow$
  18067. %% &
  18068. %% \begin{minipage}{0.7\textwidth}
  18069. %% \begin{lstlisting}
  18070. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18071. %% \end{lstlisting}
  18072. %% \end{minipage}
  18073. %% \\[2ex]\hline
  18074. %% \begin{minipage}{0.23\textwidth}
  18075. %% \begin{lstlisting}
  18076. %% (not |$e_1$|)
  18077. %% \end{lstlisting}
  18078. %% \end{minipage}
  18079. %% &
  18080. %% $\Rightarrow$
  18081. %% &
  18082. %% \begin{minipage}{0.7\textwidth}
  18083. %% \begin{lstlisting}
  18084. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18085. %% (inject #t Boolean) (inject #f Boolean))
  18086. %% \end{lstlisting}
  18087. %% \end{minipage}
  18088. %% \\[2ex]\hline
  18089. \\\hline
  18090. \end{tabular}
  18091. \fi}
  18092. \end{tcolorbox}
  18093. \caption{Cast insertion.}
  18094. \label{fig:compile-r7-Lany}
  18095. \end{figure}
  18096. \section{Reveal Casts}
  18097. \label{sec:reveal-casts-Lany}
  18098. % TODO: define R'_6
  18099. In the \code{reveal\_casts} pass, we recommend compiling
  18100. \code{Project} into a conditional expression that checks whether the
  18101. value's tag matches the target type; if it does, the value is
  18102. converted to a value of the target type by removing the tag; if it
  18103. does not, the program exits.
  18104. %
  18105. {\if\edition\racketEd
  18106. %
  18107. To perform these actions we need a new primitive operation,
  18108. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18109. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18110. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18111. underlying value from a tagged value. The \code{ValueOf} form
  18112. includes the type for the underlying value that is used by the type
  18113. checker.
  18114. %
  18115. \fi}
  18116. %
  18117. {\if\edition\pythonEd\pythonColor
  18118. %
  18119. To perform these actions we need two new AST classes: \code{TagOf} and
  18120. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18121. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18122. the underlying value from a tagged value. The \code{ValueOf}
  18123. operation includes the type for the underlying value that is used by
  18124. the type checker.
  18125. %
  18126. \fi}
  18127. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18128. \code{Project} can be translated as follows:
  18129. \begin{center}
  18130. \begin{minipage}{1.0\textwidth}
  18131. {\if\edition\racketEd
  18132. \begin{lstlisting}
  18133. (Project |$e$| |$\FType$|)
  18134. |$\Rightarrow$|
  18135. (Let |$\itm{tmp}$| |$e'$|
  18136. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18137. (Int |$\itm{tagof}(\FType)$|)))
  18138. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18139. (Exit)))
  18140. \end{lstlisting}
  18141. \fi}
  18142. {\if\edition\pythonEd\pythonColor
  18143. \begin{lstlisting}
  18144. Project(|$e$|, |$\FType$|)
  18145. |$\Rightarrow$|
  18146. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18147. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18148. [Constant(|$\itm{tagof}(\FType)$|)]),
  18149. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18150. Call(Name('exit'), [])))
  18151. \end{lstlisting}
  18152. \fi}
  18153. \end{minipage}
  18154. \end{center}
  18155. If the target type of the projection is a tuple or function type, then
  18156. there is a bit more work to do. For tuples, check that the length of
  18157. the tuple type matches the length of the tuple. For functions, check
  18158. that the number of parameters in the function type matches the
  18159. function's arity.
  18160. Regarding \code{Inject}, we recommend compiling it to a slightly
  18161. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18162. takes a tag instead of a type.
  18163. \begin{center}
  18164. \begin{minipage}{1.0\textwidth}
  18165. {\if\edition\racketEd
  18166. \begin{lstlisting}
  18167. (Inject |$e$| |$\FType$|)
  18168. |$\Rightarrow$|
  18169. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18170. \end{lstlisting}
  18171. \fi}
  18172. {\if\edition\pythonEd\pythonColor
  18173. \begin{lstlisting}
  18174. Inject(|$e$|, |$\FType$|)
  18175. |$\Rightarrow$|
  18176. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18177. \end{lstlisting}
  18178. \fi}
  18179. \end{minipage}
  18180. \end{center}
  18181. {\if\edition\pythonEd\pythonColor
  18182. %
  18183. The introduction of \code{make\_any} makes it difficult to use
  18184. bidirectional type checking because we no longer have an expected type
  18185. to use for type checking the expression $e'$. Thus, we run into
  18186. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18187. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18188. annotated lambda) that contains its return type and the types of its
  18189. parameters.
  18190. %
  18191. \fi}
  18192. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18193. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18194. translation of \code{Project}.}
  18195. {\if\edition\racketEd
  18196. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18197. combine the projection action with the vector operation. Also, the
  18198. read and write operations allow arbitrary expressions for the index, so
  18199. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18200. cannot guarantee that the index is within bounds. Thus, we insert code
  18201. to perform bounds checking at runtime. The translation for
  18202. \code{any-vector-ref} is as follows, and the other two operations are
  18203. translated in a similar way:
  18204. \begin{center}
  18205. \begin{minipage}{0.95\textwidth}
  18206. \begin{lstlisting}
  18207. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18208. |$\Rightarrow$|
  18209. (Let |$v$| |$e'_1$|
  18210. (Let |$i$| |$e'_2$|
  18211. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18212. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18213. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18214. (Exit))
  18215. (Exit))))
  18216. \end{lstlisting}
  18217. \end{minipage}
  18218. \end{center}
  18219. \fi}
  18220. %
  18221. {\if\edition\pythonEd\pythonColor
  18222. %
  18223. The \code{any\_tuple\_load} operation combines the projection action
  18224. with the load operation. Also, the load operation allows arbitrary
  18225. expressions for the index, so the type checker for \LangAny{}
  18226. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18227. within bounds. Thus, we insert code to perform bounds checking at
  18228. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18229. \begin{lstlisting}
  18230. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18231. |$\Rightarrow$|
  18232. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18233. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18234. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18235. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18236. Call(Name('exit'), [])),
  18237. Call(Name('exit'), [])))
  18238. \end{lstlisting}
  18239. \fi}
  18240. {\if\edition\pythonEd\pythonColor
  18241. \section{Assignment Conversion}
  18242. \label{sec:convert-assignments-Lany}
  18243. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18244. \code{AnnLambda} AST classes.
  18245. \section{Closure Conversion}
  18246. \label{sec:closure-conversion-Lany}
  18247. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18248. \code{AnnLambda} AST classes.
  18249. \fi}
  18250. \section{Remove Complex Operands}
  18251. \label{sec:rco-Lany}
  18252. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18253. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18254. %
  18255. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18256. complex expressions. Their subexpressions must be atomic.}
  18257. \section{Explicate Control and \LangCAny{}}
  18258. \label{sec:explicate-Lany}
  18259. The output of \code{explicate\_control} is the \LangCAny{} language,
  18260. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18261. %
  18262. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18263. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18264. note that the index argument of \code{vector-ref} and
  18265. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18266. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18267. %
  18268. \python{Update the auxiliary functions \code{explicate\_tail},
  18269. \code{explicate\_effect}, and \code{explicate\_pred} as
  18270. appropriate to handle the new expressions in \LangCAny{}. }
  18271. \newcommand{\CanyASTPython}{
  18272. \begin{array}{lcl}
  18273. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18274. &\MID& \key{TagOf}\LP \Atm \RP
  18275. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18276. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18277. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18278. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18279. \end{array}
  18280. }
  18281. \newcommand{\CanyASTRacket}{
  18282. \begin{array}{lcl}
  18283. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18284. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18285. &\MID& \VALUEOF{\Atm}{\FType} \\
  18286. \Tail &::= & \LP\key{Exit}\RP
  18287. \end{array}
  18288. }
  18289. \begin{figure}[tp]
  18290. \begin{tcolorbox}[colback=white]
  18291. \small
  18292. {\if\edition\racketEd
  18293. \[
  18294. \begin{array}{l}
  18295. \gray{\CvarASTRacket} \\ \hline
  18296. \gray{\CifASTRacket} \\ \hline
  18297. \gray{\CloopASTRacket} \\ \hline
  18298. \gray{\CtupASTRacket} \\ \hline
  18299. \gray{\CfunASTRacket} \\ \hline
  18300. \gray{\ClambdaASTRacket} \\ \hline
  18301. \CanyASTRacket \\
  18302. \begin{array}{lcl}
  18303. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18304. \end{array}
  18305. \end{array}
  18306. \]
  18307. \fi}
  18308. {\if\edition\pythonEd\pythonColor
  18309. \[
  18310. \begin{array}{l}
  18311. \gray{\CifASTPython} \\ \hline
  18312. \gray{\CtupASTPython} \\ \hline
  18313. \gray{\CfunASTPython} \\ \hline
  18314. \gray{\ClambdaASTPython} \\ \hline
  18315. \CanyASTPython \\
  18316. \begin{array}{lcl}
  18317. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18318. \end{array}
  18319. \end{array}
  18320. \]
  18321. \fi}
  18322. \end{tcolorbox}
  18323. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18324. \label{fig:c5-syntax}
  18325. \end{figure}
  18326. \section{Select Instructions}
  18327. \label{sec:select-Lany}
  18328. \index{subject}{select instructions}
  18329. In the \code{select\_instructions} pass, we translate the primitive
  18330. operations on the \ANYTY{} type to x86 instructions that manipulate
  18331. the three tag bits of the tagged value. In the following descriptions,
  18332. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18333. of translating $e$ into an x86 argument:
  18334. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18335. We recommend compiling the
  18336. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18337. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18338. shifts the destination to the left by the number of bits specified by its
  18339. source argument (in this case three, the length of the tag), and it
  18340. preserves the sign of the integer. We use the \key{orq} instruction to
  18341. combine the tag and the value to form the tagged value.
  18342. {\if\edition\racketEd
  18343. \begin{lstlisting}
  18344. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18345. |$\Rightarrow$|
  18346. movq |$e'$|, |\itm{lhs'}|
  18347. salq $3, |\itm{lhs'}|
  18348. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18349. \end{lstlisting}
  18350. \fi}
  18351. %
  18352. {\if\edition\pythonEd\pythonColor
  18353. \begin{lstlisting}
  18354. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18355. |$\Rightarrow$|
  18356. movq |$e'$|, |\itm{lhs'}|
  18357. salq $3, |\itm{lhs'}|
  18358. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18359. \end{lstlisting}
  18360. \fi}
  18361. %
  18362. The instruction selection\index{subject}{instruction selection} for
  18363. tuples and procedures is different because there is no need to shift
  18364. them to the left. The rightmost 3 bits are already zeros, so we simply
  18365. combine the value and the tag using \key{orq}. \\
  18366. %
  18367. {\if\edition\racketEd
  18368. \begin{center}
  18369. \begin{minipage}{\textwidth}
  18370. \begin{lstlisting}
  18371. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18372. |$\Rightarrow$|
  18373. movq |$e'$|, |\itm{lhs'}|
  18374. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18375. \end{lstlisting}
  18376. \end{minipage}
  18377. \end{center}
  18378. \fi}
  18379. %
  18380. {\if\edition\pythonEd\pythonColor
  18381. \begin{lstlisting}
  18382. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18383. |$\Rightarrow$|
  18384. movq |$e'$|, |\itm{lhs'}|
  18385. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18386. \end{lstlisting}
  18387. \fi}
  18388. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18389. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18390. operation extracts the type tag from a value of type \ANYTY{}. The
  18391. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18392. bitwise-and of the value with $111$ ($7$ decimal).
  18393. %
  18394. {\if\edition\racketEd
  18395. \begin{lstlisting}
  18396. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18397. |$\Rightarrow$|
  18398. movq |$e'$|, |\itm{lhs'}|
  18399. andq $7, |\itm{lhs'}|
  18400. \end{lstlisting}
  18401. \fi}
  18402. %
  18403. {\if\edition\pythonEd\pythonColor
  18404. \begin{lstlisting}
  18405. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18406. |$\Rightarrow$|
  18407. movq |$e'$|, |\itm{lhs'}|
  18408. andq $7, |\itm{lhs'}|
  18409. \end{lstlisting}
  18410. \fi}
  18411. \paragraph{\code{ValueOf}}
  18412. The instructions for \key{ValueOf} also differ, depending on whether
  18413. the type $T$ is a pointer (tuple or function) or not (integer or
  18414. Boolean). The following shows the instruction
  18415. selection for integers and
  18416. Booleans, in which we produce an untagged value by shifting it to the
  18417. right by 3 bits:
  18418. %
  18419. {\if\edition\racketEd
  18420. \begin{lstlisting}
  18421. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18422. |$\Rightarrow$|
  18423. movq |$e'$|, |\itm{lhs'}|
  18424. sarq $3, |\itm{lhs'}|
  18425. \end{lstlisting}
  18426. \fi}
  18427. %
  18428. {\if\edition\pythonEd\pythonColor
  18429. \begin{lstlisting}
  18430. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18431. |$\Rightarrow$|
  18432. movq |$e'$|, |\itm{lhs'}|
  18433. sarq $3, |\itm{lhs'}|
  18434. \end{lstlisting}
  18435. \fi}
  18436. %
  18437. In the case for tuples and procedures, we zero out the rightmost 3
  18438. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18439. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18440. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18441. Finally, we apply \code{andq} with the tagged value to get the desired
  18442. result.
  18443. %
  18444. {\if\edition\racketEd
  18445. \begin{lstlisting}
  18446. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18447. |$\Rightarrow$|
  18448. movq $|$-8$|, |\itm{lhs'}|
  18449. andq |$e'$|, |\itm{lhs'}|
  18450. \end{lstlisting}
  18451. \fi}
  18452. %
  18453. {\if\edition\pythonEd\pythonColor
  18454. \begin{lstlisting}
  18455. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18456. |$\Rightarrow$|
  18457. movq $|$-8$|, |\itm{lhs'}|
  18458. andq |$e'$|, |\itm{lhs'}|
  18459. \end{lstlisting}
  18460. \fi}
  18461. %% \paragraph{Type Predicates} We leave it to the reader to
  18462. %% devise a sequence of instructions to implement the type predicates
  18463. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18464. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18465. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18466. operation combines the effect of \code{ValueOf} with accessing the
  18467. length of a tuple from the tag stored at the zero index of the tuple.
  18468. {\if\edition\racketEd
  18469. \begin{lstlisting}
  18470. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18471. |$\Longrightarrow$|
  18472. movq $|$-8$|, %r11
  18473. andq |$e_1'$|, %r11
  18474. movq 0(%r11), %r11
  18475. andq $126, %r11
  18476. sarq $1, %r11
  18477. movq %r11, |$\itm{lhs'}$|
  18478. \end{lstlisting}
  18479. \fi}
  18480. {\if\edition\pythonEd\pythonColor
  18481. \begin{lstlisting}
  18482. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18483. |$\Longrightarrow$|
  18484. movq $|$-8$|, %r11
  18485. andq |$e_1'$|, %r11
  18486. movq 0(%r11), %r11
  18487. andq $126, %r11
  18488. sarq $1, %r11
  18489. movq %r11, |$\itm{lhs'}$|
  18490. \end{lstlisting}
  18491. \fi}
  18492. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18493. This operation combines the effect of \code{ValueOf} with reading an
  18494. element of the tuple (see
  18495. section~\ref{sec:select-instructions-gc}). However, the index may be
  18496. an arbitrary atom, so instead of computing the offset at compile time,
  18497. we must generate instructions to compute the offset at runtime as
  18498. follows. Note the use of the new instruction \code{imulq}.
  18499. \begin{center}
  18500. \begin{minipage}{0.96\textwidth}
  18501. {\if\edition\racketEd
  18502. \begin{lstlisting}
  18503. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18504. |$\Longrightarrow$|
  18505. movq |$\neg 111$|, %r11
  18506. andq |$e_1'$|, %r11
  18507. movq |$e_2'$|, %rax
  18508. addq $1, %rax
  18509. imulq $8, %rax
  18510. addq %rax, %r11
  18511. movq 0(%r11) |$\itm{lhs'}$|
  18512. \end{lstlisting}
  18513. \fi}
  18514. %
  18515. {\if\edition\pythonEd\pythonColor
  18516. \begin{lstlisting}
  18517. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18518. |$\Longrightarrow$|
  18519. movq $|$-8$|, %r11
  18520. andq |$e_1'$|, %r11
  18521. movq |$e_2'$|, %rax
  18522. addq $1, %rax
  18523. imulq $8, %rax
  18524. addq %rax, %r11
  18525. movq 0(%r11) |$\itm{lhs'}$|
  18526. \end{lstlisting}
  18527. \fi}
  18528. \end{minipage}
  18529. \end{center}
  18530. % $ pacify font lock
  18531. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18532. %% The code generation for
  18533. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18534. %% analogous to the above translation for reading from a tuple.
  18535. \section{Register Allocation for \LangAny{} }
  18536. \label{sec:register-allocation-Lany}
  18537. \index{subject}{register allocation}
  18538. There is an interesting interaction between tagged values and garbage
  18539. collection that has an impact on register allocation. A variable of
  18540. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18541. that needs to be inspected and copied during garbage collection. Thus,
  18542. we need to treat variables of type \ANYTY{} in a similar way to
  18543. variables of tuple type for purposes of register allocation,
  18544. with particular attention to the following:
  18545. \begin{itemize}
  18546. \item If a variable of type \ANYTY{} is live during a function call,
  18547. then it must be spilled. This can be accomplished by changing
  18548. \code{build\_interference} to mark all variables of type \ANYTY{}
  18549. that are live after a \code{callq} to be interfering with all the
  18550. registers.
  18551. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18552. the root stack instead of the normal procedure call stack.
  18553. \end{itemize}
  18554. Another concern regarding the root stack is that the garbage collector
  18555. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18556. tagged value that points to a tuple, and (3) a tagged value that is
  18557. not a tuple. We enable this differentiation by choosing not to use the
  18558. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18559. reserved for identifying plain old pointers to tuples. That way, if
  18560. one of the first three bits is set, then we have a tagged value and
  18561. inspecting the tag can differentiate between tuples ($010$) and the
  18562. other kinds of values.
  18563. %% \begin{exercise}\normalfont
  18564. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18565. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18566. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18567. %% compiler on these new programs and all of your previously created test
  18568. %% programs.
  18569. %% \end{exercise}
  18570. \begin{exercise}\normalfont\normalsize
  18571. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18572. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18573. by removing type annotations. Add five more test programs that
  18574. specifically rely on the language being dynamically typed. That is,
  18575. they should not be legal programs in a statically typed language, but
  18576. nevertheless they should be valid \LangDyn{} programs that run to
  18577. completion without error.
  18578. \end{exercise}
  18579. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18580. for the compilation of \LangDyn{}.
  18581. \begin{figure}[bthp]
  18582. \begin{tcolorbox}[colback=white]
  18583. {\if\edition\racketEd
  18584. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18585. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18586. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18587. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18588. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18589. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18590. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18591. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18592. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18593. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18594. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18595. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18596. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18597. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18598. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18599. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18600. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18601. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18602. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18603. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18604. \path[->,bend left=15] (Lfun) edge [above] node
  18605. {\ttfamily\footnotesize shrink} (Lfun-2);
  18606. \path[->,bend left=15] (Lfun-2) edge [above] node
  18607. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18608. \path[->,bend left=15] (Lfun-3) edge [above] node
  18609. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18610. \path[->,bend left=15] (Lfun-4) edge [left] node
  18611. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18612. \path[->,bend left=15] (Lfun-5) edge [below] node
  18613. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18614. \path[->,bend left=15] (Lfun-6) edge [below] node
  18615. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18616. \path[->,bend right=15] (Lfun-7) edge [above] node
  18617. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18618. \path[->,bend right=15] (F1-2) edge [right] node
  18619. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18620. \path[->,bend right=15] (F1-3) edge [below] node
  18621. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18622. \path[->,bend right=15] (F1-4) edge [below] node
  18623. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18624. \path[->,bend left=15] (F1-5) edge [above] node
  18625. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18626. \path[->,bend left=10] (F1-6) edge [below] node
  18627. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18628. \path[->,bend left=15] (C3-2) edge [right] node
  18629. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18630. \path[->,bend right=15] (x86-2) edge [right] node
  18631. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18632. \path[->,bend right=15] (x86-2-1) edge [below] node
  18633. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18634. \path[->,bend right=15] (x86-2-2) edge [right] node
  18635. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18636. \path[->,bend left=15] (x86-3) edge [above] node
  18637. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18638. \path[->,bend left=15] (x86-4) edge [right] node
  18639. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18640. \end{tikzpicture}
  18641. \fi}
  18642. {\if\edition\pythonEd\pythonColor
  18643. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18644. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18645. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18646. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18647. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18648. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18649. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18650. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18651. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18652. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18653. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18654. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18655. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18656. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18657. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18658. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18659. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18660. \path[->,bend left=15] (Lfun) edge [above] node
  18661. {\ttfamily\footnotesize shrink} (Lfun-2);
  18662. \path[->,bend left=15] (Lfun-2) edge [above] node
  18663. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18664. \path[->,bend left=15] (Lfun-3) edge [above] node
  18665. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18666. \path[->,bend left=15] (Lfun-4) edge [left] node
  18667. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18668. \path[->,bend left=15] (Lfun-5) edge [below] node
  18669. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18670. \path[->,bend right=15] (Lfun-6) edge [above] node
  18671. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18672. \path[->,bend right=15] (Lfun-7) edge [above] node
  18673. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18674. \path[->,bend right=15] (F1-2) edge [right] node
  18675. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18676. \path[->,bend right=15] (F1-3) edge [below] node
  18677. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18678. \path[->,bend left=15] (F1-5) edge [above] node
  18679. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18680. \path[->,bend left=10] (F1-6) edge [below] node
  18681. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18682. \path[->,bend right=15] (C3-2) edge [right] node
  18683. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18684. \path[->,bend right=15] (x86-2) edge [below] node
  18685. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18686. \path[->,bend right=15] (x86-3) edge [below] node
  18687. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18688. \path[->,bend left=15] (x86-4) edge [above] node
  18689. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18690. \end{tikzpicture}
  18691. \fi}
  18692. \end{tcolorbox}
  18693. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18694. \label{fig:Ldyn-passes}
  18695. \end{figure}
  18696. % Further Reading
  18697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18698. %% {\if\edition\pythonEd\pythonColor
  18699. %% \chapter{Objects}
  18700. %% \label{ch:Lobject}
  18701. %% \index{subject}{objects}
  18702. %% \index{subject}{classes}
  18703. %% \setcounter{footnote}{0}
  18704. %% \fi}
  18705. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18706. \chapter{Gradual Typing}
  18707. \label{ch:Lgrad}
  18708. \index{subject}{gradual typing}
  18709. \setcounter{footnote}{0}
  18710. This chapter studies the language \LangGrad{}, in which the programmer
  18711. can choose between static and dynamic type checking in different parts
  18712. of a program, thereby mixing the statically typed \LangLam{} language
  18713. with the dynamically typed \LangDyn{}. There are several approaches to
  18714. mixing static and dynamic typing, including multilanguage
  18715. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18716. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18717. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18718. programmer controls the amount of static versus dynamic checking by
  18719. adding or removing type annotations on parameters and
  18720. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18721. The definition of the concrete syntax of \LangGrad{} is shown in
  18722. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18723. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18724. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18725. annotations are optional, which is specified in the grammar using the
  18726. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18727. annotations are not optional, but we use the \CANYTY{} type when a type
  18728. annotation is absent.
  18729. %
  18730. Both the type checker and the interpreter for \LangGrad{} require some
  18731. interesting changes to enable gradual typing, which we discuss in the
  18732. next two sections.
  18733. \newcommand{\LgradGrammarRacket}{
  18734. \begin{array}{lcl}
  18735. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18736. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18737. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18738. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18739. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18740. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18741. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18742. \end{array}
  18743. }
  18744. \newcommand{\LgradASTRacket}{
  18745. \begin{array}{lcl}
  18746. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18747. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18748. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18749. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18750. \itm{op} &::=& \code{procedure-arity} \\
  18751. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18752. \end{array}
  18753. }
  18754. \newcommand{\LgradGrammarPython}{
  18755. \begin{array}{lcl}
  18756. \Type &::=& \key{Any}
  18757. \MID \key{int}
  18758. \MID \key{bool}
  18759. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18760. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18761. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18762. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18763. \MID \CARITY{\Exp} \\
  18764. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18765. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18766. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18767. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18768. \end{array}
  18769. }
  18770. \newcommand{\LgradASTPython}{
  18771. \begin{array}{lcl}
  18772. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18773. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18774. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18775. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18776. &\MID& \ARITY{\Exp} \\
  18777. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18778. \MID \RETURN{\Exp} \\
  18779. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18780. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18781. \end{array}
  18782. }
  18783. \begin{figure}[tbp]
  18784. \centering
  18785. \begin{tcolorbox}[colback=white]
  18786. \vspace{-5pt}
  18787. \small
  18788. {\if\edition\racketEd
  18789. \[
  18790. \begin{array}{l}
  18791. \gray{\LintGrammarRacket{}} \\ \hline
  18792. \gray{\LvarGrammarRacket{}} \\ \hline
  18793. \gray{\LifGrammarRacket{}} \\ \hline
  18794. \gray{\LwhileGrammarRacket} \\ \hline
  18795. \gray{\LtupGrammarRacket} \\ \hline
  18796. \LgradGrammarRacket \\
  18797. \begin{array}{lcl}
  18798. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18799. \end{array}
  18800. \end{array}
  18801. \]
  18802. \fi}
  18803. {\if\edition\pythonEd\pythonColor
  18804. \[
  18805. \begin{array}{l}
  18806. \gray{\LintGrammarPython{}} \\ \hline
  18807. \gray{\LvarGrammarPython{}} \\ \hline
  18808. \gray{\LifGrammarPython{}} \\ \hline
  18809. \gray{\LwhileGrammarPython} \\ \hline
  18810. \gray{\LtupGrammarPython} \\ \hline
  18811. \LgradGrammarPython \\
  18812. \begin{array}{lcl}
  18813. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18814. \end{array}
  18815. \end{array}
  18816. \]
  18817. \fi}
  18818. \end{tcolorbox}
  18819. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18820. \label{fig:Lgrad-concrete-syntax}
  18821. \end{figure}
  18822. \begin{figure}[tbp]
  18823. \centering
  18824. \begin{tcolorbox}[colback=white]
  18825. \small
  18826. {\if\edition\racketEd
  18827. \[
  18828. \begin{array}{l}
  18829. \gray{\LintOpAST} \\ \hline
  18830. \gray{\LvarASTRacket{}} \\ \hline
  18831. \gray{\LifASTRacket{}} \\ \hline
  18832. \gray{\LwhileASTRacket{}} \\ \hline
  18833. \gray{\LtupASTRacket{}} \\ \hline
  18834. \LgradASTRacket \\
  18835. \begin{array}{lcl}
  18836. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18837. \end{array}
  18838. \end{array}
  18839. \]
  18840. \fi}
  18841. {\if\edition\pythonEd\pythonColor
  18842. \[
  18843. \begin{array}{l}
  18844. \gray{\LintASTPython{}} \\ \hline
  18845. \gray{\LvarASTPython{}} \\ \hline
  18846. \gray{\LifASTPython{}} \\ \hline
  18847. \gray{\LwhileASTPython} \\ \hline
  18848. \gray{\LtupASTPython} \\ \hline
  18849. \LgradASTPython \\
  18850. \begin{array}{lcl}
  18851. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18852. \end{array}
  18853. \end{array}
  18854. \]
  18855. \fi}
  18856. \end{tcolorbox}
  18857. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18858. \label{fig:Lgrad-syntax}
  18859. \end{figure}
  18860. % TODO: more road map -Jeremy
  18861. %\clearpage
  18862. \section{Type Checking \LangGrad{}}
  18863. \label{sec:gradual-type-check}
  18864. We begin by discussing the type checking of a partially typed variant
  18865. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18866. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18867. statically typed, so there is nothing special happening there with
  18868. respect to type checking. On the other hand, the \code{inc} function
  18869. does not have type annotations, so the type checker assigns the type
  18870. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18871. \code{+} operator inside \code{inc}. It expects both arguments to have
  18872. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18873. a gradually typed language, such differences are allowed so long as
  18874. the types are \emph{consistent}; that is, they are equal except in
  18875. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18876. is consistent with every other type. Figure~\ref{fig:consistent}
  18877. shows the definition of the
  18878. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18879. %
  18880. So the type checker allows the \code{+} operator to be applied
  18881. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18882. %
  18883. Next consider the call to the \code{map} function shown in
  18884. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18885. tuple. The \code{inc} function has type
  18886. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18887. but parameter \code{f} of \code{map} has type
  18888. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18889. The type checker for \LangGrad{} accepts this call because the two types are
  18890. consistent.
  18891. \begin{figure}[hbtp]
  18892. % gradual_test_9.rkt
  18893. \begin{tcolorbox}[colback=white]
  18894. {\if\edition\racketEd
  18895. \begin{lstlisting}
  18896. (define (map [f : (Integer -> Integer)]
  18897. [v : (Vector Integer Integer)])
  18898. : (Vector Integer Integer)
  18899. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18900. (define (inc x) (+ x 1))
  18901. (vector-ref (map inc (vector 0 41)) 1)
  18902. \end{lstlisting}
  18903. \fi}
  18904. {\if\edition\pythonEd\pythonColor
  18905. \begin{lstlisting}
  18906. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18907. return f(v[0]), f(v[1])
  18908. def inc(x):
  18909. return x + 1
  18910. t = map(inc, (0, 41))
  18911. print(t[1])
  18912. \end{lstlisting}
  18913. \fi}
  18914. \end{tcolorbox}
  18915. \caption{A partially typed version of the \code{map} example.}
  18916. \label{fig:gradual-map}
  18917. \end{figure}
  18918. \begin{figure}[tbp]
  18919. \begin{tcolorbox}[colback=white]
  18920. {\if\edition\racketEd
  18921. \begin{lstlisting}
  18922. (define/public (consistent? t1 t2)
  18923. (match* (t1 t2)
  18924. [('Integer 'Integer) #t]
  18925. [('Boolean 'Boolean) #t]
  18926. [('Void 'Void) #t]
  18927. [('Any t2) #t]
  18928. [(t1 'Any) #t]
  18929. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18930. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18931. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18932. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18933. (consistent? rt1 rt2))]
  18934. [(other wise) #f]))
  18935. \end{lstlisting}
  18936. \fi}
  18937. {\if\edition\pythonEd\pythonColor
  18938. \begin{lstlisting}
  18939. def consistent(self, t1, t2):
  18940. match (t1, t2):
  18941. case (AnyType(), _):
  18942. return True
  18943. case (_, AnyType()):
  18944. return True
  18945. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18946. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18947. case (TupleType(ts1), TupleType(ts2)):
  18948. return all(map(self.consistent, ts1, ts2))
  18949. case (_, _):
  18950. return t1 == t2
  18951. \end{lstlisting}
  18952. \fi}
  18953. \vspace{-5pt}
  18954. \end{tcolorbox}
  18955. \caption{The consistency method on types.}
  18956. \label{fig:consistent}
  18957. \end{figure}
  18958. It is also helpful to consider how gradual typing handles programs with an
  18959. error, such as applying \code{map} to a function that sometimes
  18960. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18961. type checker for \LangGrad{} accepts this program because the type of
  18962. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18963. \code{map}; that is,
  18964. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18965. is consistent with
  18966. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18967. One might say that a gradual type checker is optimistic in that it
  18968. accepts programs that might execute without a runtime type error.
  18969. %
  18970. The definition of the type checker for \LangGrad{} is shown in
  18971. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18972. and \ref{fig:type-check-Lgradual-3}.
  18973. %% \begin{figure}[tp]
  18974. %% \centering
  18975. %% \fbox{
  18976. %% \begin{minipage}{0.96\textwidth}
  18977. %% \small
  18978. %% \[
  18979. %% \begin{array}{lcl}
  18980. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18981. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18982. %% \end{array}
  18983. %% \]
  18984. %% \end{minipage}
  18985. %% }
  18986. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18987. %% \label{fig:Lgrad-prime-syntax}
  18988. %% \end{figure}
  18989. \begin{figure}[tbp]
  18990. \begin{tcolorbox}[colback=white]
  18991. {\if\edition\racketEd
  18992. \begin{lstlisting}
  18993. (define (map [f : (Integer -> Integer)]
  18994. [v : (Vector Integer Integer)])
  18995. : (Vector Integer Integer)
  18996. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18997. (define (inc x) (+ x 1))
  18998. (define (true) #t)
  18999. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19000. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19001. \end{lstlisting}
  19002. \fi}
  19003. {\if\edition\pythonEd\pythonColor
  19004. \begin{lstlisting}
  19005. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19006. return f(v[0]), f(v[1])
  19007. def inc(x):
  19008. return x + 1
  19009. def true():
  19010. return True
  19011. def maybe_inc(x):
  19012. return inc(x) if input_int() == 0 else true()
  19013. t = map(maybe_inc, (0, 41))
  19014. print(t[1])
  19015. \end{lstlisting}
  19016. \fi}
  19017. \vspace{-5pt}
  19018. \end{tcolorbox}
  19019. \caption{A variant of the \code{map} example with an error.}
  19020. \label{fig:map-maybe_inc}
  19021. \end{figure}
  19022. Running this program with input \code{1} triggers an
  19023. error when the \code{maybe\_inc} function returns
  19024. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19025. performs checking at runtime to ensure the integrity of the static
  19026. types, such as the
  19027. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19028. annotation on
  19029. parameter \code{f} of \code{map}.
  19030. Here we give a preview of how the runtime checking is accomplished;
  19031. the following sections provide the details.
  19032. The runtime checking is carried out by a new \code{Cast} AST node that
  19033. is generated in a new pass named \code{cast\_insert}. The output of
  19034. \code{cast\_insert} is a program in the \LangCast{} language, which
  19035. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19036. %
  19037. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19038. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19039. inserted every time the type checker encounters two types that are
  19040. consistent but not equal. In the \code{inc} function, \code{x} is
  19041. cast to \INTTY{} and the result of the \code{+} is cast to
  19042. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19043. is cast from
  19044. \racket{\code{(Any -> Any)}}
  19045. \python{\code{Callable[[Any], Any]}}
  19046. to
  19047. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19048. %
  19049. In the next section we see how to interpret the \code{Cast} node.
  19050. \begin{figure}[btp]
  19051. \begin{tcolorbox}[colback=white]
  19052. {\if\edition\racketEd
  19053. \begin{lstlisting}
  19054. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19055. : (Vector Integer Integer)
  19056. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19057. (define (inc [x : Any]) : Any
  19058. (cast (+ (cast x Any Integer) 1) Integer Any))
  19059. (define (true) : Any (cast #t Boolean Any))
  19060. (define (maybe_inc [x : Any]) : Any
  19061. (if (eq? 0 (read)) (inc x) (true)))
  19062. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19063. (vector 0 41)) 0)
  19064. \end{lstlisting}
  19065. \fi}
  19066. {\if\edition\pythonEd\pythonColor
  19067. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19068. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19069. return f(v[0]), f(v[1])
  19070. def inc(x : Any) -> Any:
  19071. return Cast(Cast(x, Any, int) + 1, int, Any)
  19072. def true() -> Any:
  19073. return Cast(True, bool, Any)
  19074. def maybe_inc(x : Any) -> Any:
  19075. return inc(x) if input_int() == 0 else true()
  19076. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19077. (0, 41))
  19078. print(t[1])
  19079. \end{lstlisting}
  19080. \fi}
  19081. \vspace{-5pt}
  19082. \end{tcolorbox}
  19083. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19084. and \code{maybe\_inc} example.}
  19085. \label{fig:map-cast}
  19086. \end{figure}
  19087. {\if\edition\pythonEd\pythonColor
  19088. \begin{figure}[tbp]
  19089. \begin{tcolorbox}[colback=white]
  19090. \begin{lstlisting}
  19091. class TypeCheckLgrad(TypeCheckLlambda):
  19092. def type_check_exp(self, e, env) -> Type:
  19093. match e:
  19094. case Name(id):
  19095. return env[id]
  19096. case Constant(value) if isinstance(value, bool):
  19097. return BoolType()
  19098. case Constant(value) if isinstance(value, int):
  19099. return IntType()
  19100. case Call(Name('input_int'), []):
  19101. return IntType()
  19102. case BinOp(left, op, right):
  19103. left_type = self.type_check_exp(left, env)
  19104. self.check_consistent(left_type, IntType(), left)
  19105. right_type = self.type_check_exp(right, env)
  19106. self.check_consistent(right_type, IntType(), right)
  19107. return IntType()
  19108. case IfExp(test, body, orelse):
  19109. test_t = self.type_check_exp(test, env)
  19110. self.check_consistent(test_t, BoolType(), test)
  19111. body_t = self.type_check_exp(body, env)
  19112. orelse_t = self.type_check_exp(orelse, env)
  19113. self.check_consistent(body_t, orelse_t, e)
  19114. return self.join_types(body_t, orelse_t)
  19115. case Call(func, args):
  19116. func_t = self.type_check_exp(func, env)
  19117. args_t = [self.type_check_exp(arg, env) for arg in args]
  19118. match func_t:
  19119. case FunctionType(params_t, return_t) \
  19120. if len(params_t) == len(args_t):
  19121. for (arg_t, param_t) in zip(args_t, params_t):
  19122. self.check_consistent(param_t, arg_t, e)
  19123. return return_t
  19124. case AnyType():
  19125. return AnyType()
  19126. case _:
  19127. raise Exception('type_check_exp: in call, unexpected '
  19128. + repr(func_t))
  19129. ...
  19130. case _:
  19131. raise Exception('type_check_exp: unexpected ' + repr(e))
  19132. \end{lstlisting}
  19133. \end{tcolorbox}
  19134. \caption{Type checking expressions in the \LangGrad{} language.}
  19135. \label{fig:type-check-Lgradual-1}
  19136. \end{figure}
  19137. \begin{figure}[tbp]
  19138. \begin{tcolorbox}[colback=white]
  19139. \begin{lstlisting}
  19140. def check_exp(self, e, expected_ty, env):
  19141. match e:
  19142. case Lambda(params, body):
  19143. match expected_ty:
  19144. case FunctionType(params_t, return_t):
  19145. new_env = env.copy().update(zip(params, params_t))
  19146. e.has_type = expected_ty
  19147. body_ty = self.type_check_exp(body, new_env)
  19148. self.check_consistent(body_ty, return_t)
  19149. case AnyType():
  19150. new_env = env.copy().update((p, AnyType()) for p in params)
  19151. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19152. body_ty = self.type_check_exp(body, new_env)
  19153. case _:
  19154. raise Exception('lambda is not of type ' + str(expected_ty))
  19155. case _:
  19156. e_ty = self.type_check_exp(e, env)
  19157. self.check_consistent(e_ty, expected_ty, e)
  19158. \end{lstlisting}
  19159. \end{tcolorbox}
  19160. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19161. \label{fig:type-check-Lgradual-2}
  19162. \end{figure}
  19163. \begin{figure}[tbp]
  19164. \begin{tcolorbox}[colback=white]
  19165. \begin{lstlisting}
  19166. def type_check_stmt(self, s, env, return_type):
  19167. match s:
  19168. case Assign([Name(id)], value):
  19169. value_ty = self.type_check_exp(value, env)
  19170. if id in env:
  19171. self.check_consistent(env[id], value_ty, value)
  19172. else:
  19173. env[id] = value_ty
  19174. ...
  19175. case _:
  19176. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19177. def type_check_stmts(self, ss, env, return_type):
  19178. for s in ss:
  19179. self.type_check_stmt(s, env, return_type)
  19180. \end{lstlisting}
  19181. \end{tcolorbox}
  19182. \caption{Type checking statements in the \LangGrad{} language.}
  19183. \label{fig:type-check-Lgradual-3}
  19184. \end{figure}
  19185. \clearpage
  19186. \begin{figure}[tbp]
  19187. \begin{tcolorbox}[colback=white]
  19188. \begin{lstlisting}
  19189. def join_types(self, t1, t2):
  19190. match (t1, t2):
  19191. case (AnyType(), _):
  19192. return t2
  19193. case (_, AnyType()):
  19194. return t1
  19195. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19196. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19197. self.join_types(rt1,rt2))
  19198. case (TupleType(ts1), TupleType(ts2)):
  19199. return TupleType(list(map(self.join_types, ts1, ts2)))
  19200. case (_, _):
  19201. return t1
  19202. def check_consistent(self, t1, t2, e):
  19203. if not self.consistent(t1, t2):
  19204. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19205. + repr(t2) + ' in ' + repr(e))
  19206. \end{lstlisting}
  19207. \end{tcolorbox}
  19208. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19209. \label{fig:type-check-Lgradual-aux}
  19210. \end{figure}
  19211. \fi}
  19212. {\if\edition\racketEd
  19213. \begin{figure}[tbp]
  19214. \begin{tcolorbox}[colback=white]
  19215. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19216. (define/override (type-check-exp env)
  19217. (lambda (e)
  19218. (define recur (type-check-exp env))
  19219. (match e
  19220. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19221. (define-values (new-es ts)
  19222. (for/lists (exprs types) ([e es])
  19223. (recur e)))
  19224. (define t-ret (type-check-op op ts e))
  19225. (values (Prim op new-es) t-ret)]
  19226. [(Prim 'eq? (list e1 e2))
  19227. (define-values (e1^ t1) (recur e1))
  19228. (define-values (e2^ t2) (recur e2))
  19229. (check-consistent? t1 t2 e)
  19230. (define T (meet t1 t2))
  19231. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19232. [(Prim 'and (list e1 e2))
  19233. (recur (If e1 e2 (Bool #f)))]
  19234. [(Prim 'or (list e1 e2))
  19235. (define tmp (gensym 'tmp))
  19236. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19237. [(If e1 e2 e3)
  19238. (define-values (e1^ T1) (recur e1))
  19239. (define-values (e2^ T2) (recur e2))
  19240. (define-values (e3^ T3) (recur e3))
  19241. (check-consistent? T1 'Boolean e)
  19242. (check-consistent? T2 T3 e)
  19243. (define Tif (meet T2 T3))
  19244. (values (If e1^ e2^ e3^) Tif)]
  19245. [(SetBang x e1)
  19246. (define-values (e1^ T1) (recur e1))
  19247. (define varT (dict-ref env x))
  19248. (check-consistent? T1 varT e)
  19249. (values (SetBang x e1^) 'Void)]
  19250. [(WhileLoop e1 e2)
  19251. (define-values (e1^ T1) (recur e1))
  19252. (check-consistent? T1 'Boolean e)
  19253. (define-values (e2^ T2) ((type-check-exp env) e2))
  19254. (values (WhileLoop e1^ e2^) 'Void)]
  19255. [(Prim 'vector-length (list e1))
  19256. (define-values (e1^ t) (recur e1))
  19257. (match t
  19258. [`(Vector ,ts ...)
  19259. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19260. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19261. \end{lstlisting}
  19262. \end{tcolorbox}
  19263. \caption{Type checker for the \LangGrad{} language, part 1.}
  19264. \label{fig:type-check-Lgradual-1}
  19265. \end{figure}
  19266. \begin{figure}[tbp]
  19267. \begin{tcolorbox}[colback=white]
  19268. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19269. [(Prim 'vector-ref (list e1 e2))
  19270. (define-values (e1^ t1) (recur e1))
  19271. (define-values (e2^ t2) (recur e2))
  19272. (check-consistent? t2 'Integer e)
  19273. (match t1
  19274. [`(Vector ,ts ...)
  19275. (match e2^
  19276. [(Int i)
  19277. (unless (and (0 . <= . i) (i . < . (length ts)))
  19278. (error 'type-check "invalid index ~a in ~a" i e))
  19279. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19280. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19281. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19282. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19283. [(Prim 'vector-set! (list e1 e2 e3) )
  19284. (define-values (e1^ t1) (recur e1))
  19285. (define-values (e2^ t2) (recur e2))
  19286. (define-values (e3^ t3) (recur e3))
  19287. (check-consistent? t2 'Integer e)
  19288. (match t1
  19289. [`(Vector ,ts ...)
  19290. (match e2^
  19291. [(Int i)
  19292. (unless (and (0 . <= . i) (i . < . (length ts)))
  19293. (error 'type-check "invalid index ~a in ~a" i e))
  19294. (check-consistent? (list-ref ts i) t3 e)
  19295. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19296. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19297. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19298. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19299. [(Apply e1 e2s)
  19300. (define-values (e1^ T1) (recur e1))
  19301. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19302. (match T1
  19303. [`(,T1ps ... -> ,T1rt)
  19304. (for ([T2 T2s] [Tp T1ps])
  19305. (check-consistent? T2 Tp e))
  19306. (values (Apply e1^ e2s^) T1rt)]
  19307. [`Any (values (Apply e1^ e2s^) 'Any)]
  19308. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19309. [(Lambda params Tr e1)
  19310. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19311. (match p
  19312. [`[,x : ,T] (values x T)]
  19313. [(? symbol? x) (values x 'Any)])))
  19314. (define-values (e1^ T1)
  19315. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19316. (check-consistent? Tr T1 e)
  19317. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19318. `(,@Ts -> ,Tr))]
  19319. [else ((super type-check-exp env) e)]
  19320. )))
  19321. \end{lstlisting}
  19322. \end{tcolorbox}
  19323. \caption{Type checker for the \LangGrad{} language, part 2.}
  19324. \label{fig:type-check-Lgradual-2}
  19325. \end{figure}
  19326. \begin{figure}[tbp]
  19327. \begin{tcolorbox}[colback=white]
  19328. \begin{lstlisting}
  19329. (define/override (type-check-def env)
  19330. (lambda (e)
  19331. (match e
  19332. [(Def f params rt info body)
  19333. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19334. (match p
  19335. [`[,x : ,T] (values x T)]
  19336. [(? symbol? x) (values x 'Any)])))
  19337. (define new-env (append (map cons xs ps) env))
  19338. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19339. (check-consistent? ty^ rt e)
  19340. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19341. [else (error 'type-check "ill-formed function definition ~a" e)]
  19342. )))
  19343. (define/override (type-check-program e)
  19344. (match e
  19345. [(Program info body)
  19346. (define-values (body^ ty) ((type-check-exp '()) body))
  19347. (check-consistent? ty 'Integer e)
  19348. (ProgramDefsExp info '() body^)]
  19349. [(ProgramDefsExp info ds body)
  19350. (define new-env (for/list ([d ds])
  19351. (cons (Def-name d) (fun-def-type d))))
  19352. (define ds^ (for/list ([d ds])
  19353. ((type-check-def new-env) d)))
  19354. (define-values (body^ ty) ((type-check-exp new-env) body))
  19355. (check-consistent? ty 'Integer e)
  19356. (ProgramDefsExp info ds^ body^)]
  19357. [else (super type-check-program e)]))
  19358. \end{lstlisting}
  19359. \end{tcolorbox}
  19360. \caption{Type checker for the \LangGrad{} language, part 3.}
  19361. \label{fig:type-check-Lgradual-3}
  19362. \end{figure}
  19363. \begin{figure}[tbp]
  19364. \begin{tcolorbox}[colback=white]
  19365. \begin{lstlisting}
  19366. (define/public (join t1 t2)
  19367. (match* (t1 t2)
  19368. [('Integer 'Integer) 'Integer]
  19369. [('Boolean 'Boolean) 'Boolean]
  19370. [('Void 'Void) 'Void]
  19371. [('Any t2) t2]
  19372. [(t1 'Any) t1]
  19373. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19374. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19375. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19376. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19377. -> ,(join rt1 rt2))]))
  19378. (define/public (meet t1 t2)
  19379. (match* (t1 t2)
  19380. [('Integer 'Integer) 'Integer]
  19381. [('Boolean 'Boolean) 'Boolean]
  19382. [('Void 'Void) 'Void]
  19383. [('Any t2) 'Any]
  19384. [(t1 'Any) 'Any]
  19385. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19386. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19387. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19388. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19389. -> ,(meet rt1 rt2))]))
  19390. (define/public (check-consistent? t1 t2 e)
  19391. (unless (consistent? t1 t2)
  19392. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19393. (define explicit-prim-ops
  19394. (set-union
  19395. (type-predicates)
  19396. (set 'procedure-arity 'eq? 'not 'and 'or
  19397. 'vector 'vector-length 'vector-ref 'vector-set!
  19398. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19399. (define/override (fun-def-type d)
  19400. (match d
  19401. [(Def f params rt info body)
  19402. (define ps
  19403. (for/list ([p params])
  19404. (match p
  19405. [`[,x : ,T] T]
  19406. [(? symbol?) 'Any]
  19407. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19408. `(,@ps -> ,rt)]
  19409. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19410. \end{lstlisting}
  19411. \end{tcolorbox}
  19412. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19413. \label{fig:type-check-Lgradual-aux}
  19414. \end{figure}
  19415. \fi}
  19416. \section{Interpreting \LangCast{} }
  19417. \label{sec:interp-casts}
  19418. The runtime behavior of casts involving simple types such as
  19419. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19420. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19421. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19422. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19423. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19424. operator, by checking the value's tag and either retrieving
  19425. the underlying integer or signaling an error if the tag is not the
  19426. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19427. %
  19428. Things get more interesting with casts involving
  19429. \racket{function and tuple types}\python{function, tuple, and array types}.
  19430. Consider the cast of the function \code{maybe\_inc} from
  19431. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19432. to
  19433. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19434. shown in figure~\ref{fig:map-maybe_inc}.
  19435. When the \code{maybe\_inc} function flows through
  19436. this cast at runtime, we don't know whether it will return
  19437. an integer, because that depends on the input from the user.
  19438. The \LangCast{} interpreter therefore delays the checking
  19439. of the cast until the function is applied. To do so it
  19440. wraps \code{maybe\_inc} in a new function that casts its parameter
  19441. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19442. casts the return value from \CANYTY{} to \INTTY{}.
  19443. {\if\edition\pythonEd\pythonColor
  19444. %
  19445. There are further complications regarding casts on mutable data,
  19446. such as the \code{list} type introduced in
  19447. the challenge assignment of section~\ref{sec:arrays}.
  19448. %
  19449. \fi}
  19450. %
  19451. Consider the example presented in figure~\ref{fig:map-bang} that
  19452. defines a partially typed version of \code{map} whose parameter
  19453. \code{v} has type
  19454. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19455. and that updates \code{v} in place
  19456. instead of returning a new tuple. We name this function
  19457. \code{map\_inplace}. We apply \code{map\_inplace} to
  19458. \racket{a tuple}\python{an array} of integers, so the type checker
  19459. inserts a cast from
  19460. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19461. to
  19462. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19463. A naive way for the \LangCast{} interpreter to cast between
  19464. \racket{tuple}\python{array} types would be to build a new
  19465. \racket{tuple}\python{array} whose elements are the result
  19466. of casting each of the original elements to the target
  19467. type. However, this approach is not valid for mutable data structures.
  19468. In the example of figure~\ref{fig:map-bang},
  19469. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19470. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19471. the original one.
  19472. Instead the interpreter needs to create a new kind of value, a
  19473. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19474. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19475. and then applies a
  19476. cast to the resulting value. On a write, the proxy casts the argument
  19477. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19478. \racket{
  19479. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19480. \code{0} from \INTTY{} to \CANYTY{}.
  19481. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19482. from \CANYTY{} to \INTTY{}.
  19483. }
  19484. \python{
  19485. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19486. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19487. For the subscript on the left of the assignment,
  19488. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19489. }
  19490. Finally we consider casts between the \CANYTY{} type and higher-order types
  19491. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19492. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19493. have a type annotation, so it is given type \CANYTY{}. In the call to
  19494. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19495. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19496. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19497. \code{Inject}, but that doesn't work because
  19498. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19499. a flat type. Instead, we must first cast to
  19500. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19501. and then inject to \CANYTY{}.
  19502. \begin{figure}[tbp]
  19503. \begin{tcolorbox}[colback=white]
  19504. % gradual_test_11.rkt
  19505. {\if\edition\racketEd
  19506. \begin{lstlisting}
  19507. (define (map_inplace [f : (Any -> Any)]
  19508. [v : (Vector Any Any)]) : Void
  19509. (begin
  19510. (vector-set! v 0 (f (vector-ref v 0)))
  19511. (vector-set! v 1 (f (vector-ref v 1)))))
  19512. (define (inc x) (+ x 1))
  19513. (let ([v (vector 0 41)])
  19514. (begin (map_inplace inc v) (vector-ref v 1)))
  19515. \end{lstlisting}
  19516. \fi}
  19517. {\if\edition\pythonEd\pythonColor
  19518. \begin{lstlisting}
  19519. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19520. i = 0
  19521. while i != len(v):
  19522. v[i] = f(v[i])
  19523. i = i + 1
  19524. def inc(x : int) -> int:
  19525. return x + 1
  19526. v = [0, 41]
  19527. map_inplace(inc, v)
  19528. print(v[1])
  19529. \end{lstlisting}
  19530. \fi}
  19531. \end{tcolorbox}
  19532. \caption{An example involving casts on arrays.}
  19533. \label{fig:map-bang}
  19534. \end{figure}
  19535. \begin{figure}[btp]
  19536. \begin{tcolorbox}[colback=white]
  19537. {\if\edition\racketEd
  19538. \begin{lstlisting}
  19539. (define (map_inplace [f : (Any -> Any)] v) : Void
  19540. (begin
  19541. (vector-set! v 0 (f (vector-ref v 0)))
  19542. (vector-set! v 1 (f (vector-ref v 1)))))
  19543. (define (inc x) (+ x 1))
  19544. (let ([v (vector 0 41)])
  19545. (begin (map_inplace inc v) (vector-ref v 1)))
  19546. \end{lstlisting}
  19547. \fi}
  19548. {\if\edition\pythonEd\pythonColor
  19549. \begin{lstlisting}
  19550. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19551. i = 0
  19552. while i != len(v):
  19553. v[i] = f(v[i])
  19554. i = i + 1
  19555. def inc(x):
  19556. return x + 1
  19557. v = [0, 41]
  19558. map_inplace(inc, v)
  19559. print(v[1])
  19560. \end{lstlisting}
  19561. \fi}
  19562. \end{tcolorbox}
  19563. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19564. \label{fig:map-any}
  19565. \end{figure}
  19566. \begin{figure}[tbp]
  19567. \begin{tcolorbox}[colback=white]
  19568. {\if\edition\racketEd
  19569. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19570. (define/public (apply_cast v s t)
  19571. (match* (s t)
  19572. [(t1 t2) #:when (equal? t1 t2) v]
  19573. [('Any t2)
  19574. (match t2
  19575. [`(,ts ... -> ,rt)
  19576. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19577. (define v^ (apply-project v any->any))
  19578. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19579. [`(Vector ,ts ...)
  19580. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19581. (define v^ (apply-project v vec-any))
  19582. (apply_cast v^ vec-any `(Vector ,@ts))]
  19583. [else (apply-project v t2)])]
  19584. [(t1 'Any)
  19585. (match t1
  19586. [`(,ts ... -> ,rt)
  19587. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19588. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19589. (apply-inject v^ (any-tag any->any))]
  19590. [`(Vector ,ts ...)
  19591. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19592. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19593. (apply-inject v^ (any-tag vec-any))]
  19594. [else (apply-inject v (any-tag t1))])]
  19595. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19596. (define x (gensym 'x))
  19597. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19598. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19599. (define cast-writes
  19600. (for/list ([t1 ts1] [t2 ts2])
  19601. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19602. `(vector-proxy ,(vector v (apply vector cast-reads)
  19603. (apply vector cast-writes)))]
  19604. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19605. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19606. `(function ,xs ,(Cast
  19607. (Apply (Value v)
  19608. (for/list ([x xs][t1 ts1][t2 ts2])
  19609. (Cast (Var x) t2 t1)))
  19610. rt1 rt2) ())]
  19611. ))
  19612. \end{lstlisting}
  19613. \fi}
  19614. {\if\edition\pythonEd\pythonColor
  19615. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19616. def apply_cast(self, value, src, tgt):
  19617. match (src, tgt):
  19618. case (AnyType(), FunctionType(ps2, rt2)):
  19619. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19620. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19621. case (AnyType(), TupleType(ts2)):
  19622. anytup = TupleType([AnyType() for t1 in ts2])
  19623. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19624. case (AnyType(), ListType(t2)):
  19625. anylist = ListType([AnyType() for t1 in ts2])
  19626. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19627. case (AnyType(), AnyType()):
  19628. return value
  19629. case (AnyType(), _):
  19630. return self.apply_project(value, tgt)
  19631. case (FunctionType(ps1,rt1), AnyType()):
  19632. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19633. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19634. case (TupleType(ts1), AnyType()):
  19635. anytup = TupleType([AnyType() for t1 in ts1])
  19636. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19637. case (ListType(t1), AnyType()):
  19638. anylist = ListType(AnyType())
  19639. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19640. case (_, AnyType()):
  19641. return self.apply_inject(value, src)
  19642. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19643. params = [generate_name('x') for p in ps2]
  19644. args = [Cast(Name(x), t2, t1)
  19645. for (x,t1,t2) in zip(params, ps1, ps2)]
  19646. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19647. return Function('cast', params, [Return(body)], {})
  19648. case (TupleType(ts1), TupleType(ts2)):
  19649. x = generate_name('x')
  19650. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19651. for (t1,t2) in zip(ts1,ts2)]
  19652. return ProxiedTuple(value, reads)
  19653. case (ListType(t1), ListType(t2)):
  19654. x = generate_name('x')
  19655. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19656. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19657. return ProxiedList(value, read, write)
  19658. case (t1, t2) if t1 == t2:
  19659. return value
  19660. case (t1, t2):
  19661. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19662. def apply_inject(self, value, src):
  19663. return Tagged(value, self.type_to_tag(src))
  19664. def apply_project(self, value, tgt):
  19665. match value:
  19666. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19667. return val
  19668. case _:
  19669. raise Exception('apply_project, unexpected ' + repr(value))
  19670. \end{lstlisting}
  19671. \fi}
  19672. \end{tcolorbox}
  19673. \caption{The \code{apply\_cast} auxiliary method.}
  19674. \label{fig:apply_cast}
  19675. \end{figure}
  19676. The \LangCast{} interpreter uses an auxiliary function named
  19677. \code{apply\_cast} to cast a value from a source type to a target type,
  19678. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19679. the kinds of casts that we've discussed in this section.
  19680. %
  19681. The definition of the interpreter for \LangCast{} is shown in
  19682. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19683. dispatching to \code{apply\_cast}.
  19684. \racket{To handle the addition of tuple
  19685. proxies, we update the tuple primitives in \code{interp-op} using the
  19686. functions given in figure~\ref{fig:guarded-tuple}.}
  19687. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19688. \begin{figure}[tbp]
  19689. \begin{tcolorbox}[colback=white]
  19690. {\if\edition\racketEd
  19691. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19692. (define interp-Lcast-class
  19693. (class interp-Llambda-class
  19694. (super-new)
  19695. (inherit apply-fun apply-inject apply-project)
  19696. (define/override (interp-op op)
  19697. (match op
  19698. ['vector-length guarded-vector-length]
  19699. ['vector-ref guarded-vector-ref]
  19700. ['vector-set! guarded-vector-set!]
  19701. ['any-vector-ref (lambda (v i)
  19702. (match v [`(tagged ,v^ ,tg)
  19703. (guarded-vector-ref v^ i)]))]
  19704. ['any-vector-set! (lambda (v i a)
  19705. (match v [`(tagged ,v^ ,tg)
  19706. (guarded-vector-set! v^ i a)]))]
  19707. ['any-vector-length (lambda (v)
  19708. (match v [`(tagged ,v^ ,tg)
  19709. (guarded-vector-length v^)]))]
  19710. [else (super interp-op op)]
  19711. ))
  19712. (define/override ((interp-exp env) e)
  19713. (define (recur e) ((interp-exp env) e))
  19714. (match e
  19715. [(Value v) v]
  19716. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19717. [else ((super interp-exp env) e)]))
  19718. ))
  19719. (define (interp-Lcast p)
  19720. (send (new interp-Lcast-class) interp-program p))
  19721. \end{lstlisting}
  19722. \fi}
  19723. {\if\edition\pythonEd\pythonColor
  19724. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19725. class InterpLcast(InterpLany):
  19726. def interp_exp(self, e, env):
  19727. match e:
  19728. case Cast(value, src, tgt):
  19729. v = self.interp_exp(value, env)
  19730. return self.apply_cast(v, src, tgt)
  19731. case ValueExp(value):
  19732. return value
  19733. ...
  19734. case _:
  19735. return super().interp_exp(e, env)
  19736. \end{lstlisting}
  19737. \fi}
  19738. \end{tcolorbox}
  19739. \caption{The interpreter for \LangCast{}.}
  19740. \label{fig:interp-Lcast}
  19741. \end{figure}
  19742. {\if\edition\racketEd
  19743. \begin{figure}[tbp]
  19744. \begin{tcolorbox}[colback=white]
  19745. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19746. (define (guarded-vector-ref vec i)
  19747. (match vec
  19748. [`(vector-proxy ,proxy)
  19749. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19750. (define rd (vector-ref (vector-ref proxy 1) i))
  19751. (apply-fun rd (list val) 'guarded-vector-ref)]
  19752. [else (vector-ref vec i)]))
  19753. (define (guarded-vector-set! vec i arg)
  19754. (match vec
  19755. [`(vector-proxy ,proxy)
  19756. (define wr (vector-ref (vector-ref proxy 2) i))
  19757. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19758. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19759. [else (vector-set! vec i arg)]))
  19760. (define (guarded-vector-length vec)
  19761. (match vec
  19762. [`(vector-proxy ,proxy)
  19763. (guarded-vector-length (vector-ref proxy 0))]
  19764. [else (vector-length vec)]))
  19765. \end{lstlisting}
  19766. %% {\if\edition\pythonEd\pythonColor
  19767. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19768. %% UNDER CONSTRUCTION
  19769. %% \end{lstlisting}
  19770. %% \fi}
  19771. \end{tcolorbox}
  19772. \caption{The \code{guarded-vector} auxiliary functions.}
  19773. \label{fig:guarded-tuple}
  19774. \end{figure}
  19775. \fi}
  19776. {\if\edition\pythonEd\pythonColor
  19777. \section{Overload Resolution }
  19778. \label{sec:gradual-resolution}
  19779. Recall that when we added support for arrays in
  19780. section~\ref{sec:arrays}, the syntax for the array operations were the
  19781. same as for tuple operations (for example, accessing an element and
  19782. getting the length). So we performed overload resolution, with a pass
  19783. named \code{resolve}, to separate the array and tuple operations. In
  19784. particular, we introduced the primitives \code{array\_load},
  19785. \code{array\_store}, and \code{array\_len}.
  19786. For gradual typing, we further overload these operators to work on
  19787. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19788. updated with new cases for the \CANYTY{} type, translating the element
  19789. access and length operations to the primitives \code{any\_load},
  19790. \code{any\_store}, and \code{any\_len}.
  19791. \fi}
  19792. \section{Cast Insertion }
  19793. \label{sec:gradual-insert-casts}
  19794. In our discussion of type checking of \LangGrad{}, we mentioned how
  19795. the runtime aspect of type checking is carried out by the \code{Cast}
  19796. AST node, which is added to the program by a new pass named
  19797. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19798. language. We now discuss the details of this pass.
  19799. The \code{cast\_insert} pass is closely related to the type checker
  19800. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19801. In particular, the type checker allows implicit casts between
  19802. consistent types. The job of the \code{cast\_insert} pass is to make
  19803. those casts explicit. It does so by inserting
  19804. \code{Cast} nodes into the AST.
  19805. %
  19806. For the most part, the implicit casts occur in places where the type
  19807. checker checks two types for consistency. Consider the case for
  19808. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19809. checker requires that the type of the left operand is consistent with
  19810. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19811. \code{Cast} around the left operand, converting from its type to
  19812. \INTTY{}. The story is similar for the right operand. It is not always
  19813. necessary to insert a cast, for example, if the left operand already has type
  19814. \INTTY{} then there is no need for a \code{Cast}.
  19815. Some of the implicit casts are not as straightforward. One such case
  19816. arises with the
  19817. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19818. see that the type checker requires that the two branches have
  19819. consistent types and that type of the conditional expression is the
  19820. meet of the branches' types. In the target language \LangCast{}, both
  19821. branches will need to have the same type, and that type
  19822. will be the type of the conditional expression. Thus, each branch requires
  19823. a \code{Cast} to convert from its type to the meet of the branches' types.
  19824. The case for the function call exhibits another interesting situation. If
  19825. the function expression is of type \CANYTY{}, then it needs to be cast
  19826. to a function type so that it can be used in a function call in
  19827. \LangCast{}. Which function type should it be cast to? The parameter
  19828. and return types are unknown, so we can simply use \CANYTY{} for all
  19829. of them. Furthermore, in \LangCast{} the argument types will need to
  19830. exactly match the parameter types, so we must cast all the arguments
  19831. to type \CANYTY{} (if they are not already of that type).
  19832. {\if\edition\racketEd
  19833. %
  19834. Likewise, the cases for the tuple operators \code{vector-length},
  19835. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19836. where the tuple expression is of type \CANYTY{}. Instead of
  19837. handling these situations with casts, we recommend translating
  19838. the special-purpose variants of the tuple operators that handle
  19839. tuples of type \CANYTY{}: \code{any-vector-length},
  19840. \code{any-vector-ref}, and \code{any-vector-set!}.
  19841. %
  19842. \fi}
  19843. \section{Lower Casts }
  19844. \label{sec:lower_casts}
  19845. The next step in the journey toward x86 is the \code{lower\_casts}
  19846. pass that translates the casts in \LangCast{} to the lower-level
  19847. \code{Inject} and \code{Project} operators and new operators for
  19848. proxies, extending the \LangLam{} language to \LangProxy{}.
  19849. The \LangProxy{} language can also be described as an extension of
  19850. \LangAny{}, with the addition of proxies. We recommend creating an
  19851. auxiliary function named \code{lower\_cast} that takes an expression
  19852. (in \LangCast{}), a source type, and a target type and translates it
  19853. to an expression in \LangProxy{}.
  19854. The \code{lower\_cast} function can follow a code structure similar to
  19855. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19856. the interpreter for \LangCast{}, because it must handle the same cases
  19857. as \code{apply\_cast} and it needs to mimic the behavior of
  19858. \code{apply\_cast}. The most interesting cases concern
  19859. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19860. {\if\edition\racketEd
  19861. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19862. type to another tuple type is accomplished by creating a proxy that
  19863. intercepts the operations on the underlying tuple. Here we make the
  19864. creation of the proxy explicit with the \code{vector-proxy} AST
  19865. node. It takes three arguments: the first is an expression for the
  19866. tuple, the second is a tuple of functions for casting an element that is
  19867. being read from the tuple, and the third is a tuple of functions for
  19868. casting an element that is being written to the array. You can create
  19869. the functions for reading and writing using lambda expressions. Also,
  19870. as we show in the next section, we need to differentiate these tuples
  19871. of functions from the user-created ones, so we recommend using a new
  19872. AST node named \code{raw-vector} instead of \code{vector}.
  19873. %
  19874. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19875. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19876. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19877. \fi}
  19878. {\if\edition\pythonEd\pythonColor
  19879. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19880. type to another array type is accomplished by creating a proxy that
  19881. intercepts the operations on the underlying array. Here we make the
  19882. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19883. takes fives arguments: the first is an expression for the array, the
  19884. second is a function for casting an element that is being read from
  19885. the array, the third is a function for casting an element that is
  19886. being written to the array, the fourth is the type of the underlying
  19887. array, and the fifth is the type of the proxied array. You can create
  19888. the functions for reading and writing using lambda expressions.
  19889. A cast between two tuple types can be handled in a similar manner. We
  19890. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19891. immutable, so there is no need for a function to cast the value during
  19892. a write. Because there is a separate element type for each slot in
  19893. the tuple, we need more than one function for casting during a read:
  19894. we need a tuple of functions.
  19895. %
  19896. Also, as we show in the next section, we need to differentiate these
  19897. tuples from the user-created ones, so we recommend using a new AST
  19898. node named \code{RawTuple} instead of \code{Tuple} to create the
  19899. tuples of functions.
  19900. %
  19901. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19902. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19903. that involves casting an array of integers to an array of \CANYTY{}.
  19904. \fi}
  19905. \begin{figure}[tbp]
  19906. \begin{tcolorbox}[colback=white]
  19907. {\if\edition\racketEd
  19908. \begin{lstlisting}
  19909. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19910. (begin
  19911. (vector-set! v 0 (f (vector-ref v 0)))
  19912. (vector-set! v 1 (f (vector-ref v 1)))))
  19913. (define (inc [x : Any]) : Any
  19914. (inject (+ (project x Integer) 1) Integer))
  19915. (let ([v (vector 0 41)])
  19916. (begin
  19917. (map_inplace inc (vector-proxy v
  19918. (raw-vector (lambda: ([x9 : Integer]) : Any
  19919. (inject x9 Integer))
  19920. (lambda: ([x9 : Integer]) : Any
  19921. (inject x9 Integer)))
  19922. (raw-vector (lambda: ([x9 : Any]) : Integer
  19923. (project x9 Integer))
  19924. (lambda: ([x9 : Any]) : Integer
  19925. (project x9 Integer)))))
  19926. (vector-ref v 1)))
  19927. \end{lstlisting}
  19928. \fi}
  19929. {\if\edition\pythonEd\pythonColor
  19930. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19931. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19932. i = 0
  19933. while i != array_len(v):
  19934. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19935. i = (i + 1)
  19936. def inc(x : int) -> int:
  19937. return (x + 1)
  19938. def main() -> int:
  19939. v = [0, 41]
  19940. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19941. print(array_load(v, 1))
  19942. return 0
  19943. \end{lstlisting}
  19944. \fi}
  19945. \end{tcolorbox}
  19946. \caption{Output of \code{lower\_casts} on the example shown in
  19947. figure~\ref{fig:map-bang}.}
  19948. \label{fig:map-bang-lower-cast}
  19949. \end{figure}
  19950. A cast from one function type to another function type is accomplished
  19951. by generating a \code{lambda} whose parameter and return types match
  19952. the target function type. The body of the \code{lambda} should cast
  19953. the parameters from the target type to the source type. (Yes,
  19954. backward! Functions are contravariant\index{subject}{contravariant}
  19955. in the parameters.) Afterward, call the underlying function and then
  19956. cast the result from the source return type to the target return type.
  19957. Figure~\ref{fig:map-lower-cast} shows the output of the
  19958. \code{lower\_casts} pass on the \code{map} example given in
  19959. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19960. call to \code{map} is wrapped in a \code{lambda}.
  19961. \begin{figure}[tbp]
  19962. \begin{tcolorbox}[colback=white]
  19963. {\if\edition\racketEd
  19964. \begin{lstlisting}
  19965. (define (map [f : (Integer -> Integer)]
  19966. [v : (Vector Integer Integer)])
  19967. : (Vector Integer Integer)
  19968. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19969. (define (inc [x : Any]) : Any
  19970. (inject (+ (project x Integer) 1) Integer))
  19971. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19972. (project (inc (inject x9 Integer)) Integer))
  19973. (vector 0 41)) 1)
  19974. \end{lstlisting}
  19975. \fi}
  19976. {\if\edition\pythonEd\pythonColor
  19977. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19978. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19979. return (f(v[0]), f(v[1]),)
  19980. def inc(x : any) -> any:
  19981. return inject((project(x, int) + 1), int)
  19982. def main() -> int:
  19983. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19984. print(t[1])
  19985. return 0
  19986. \end{lstlisting}
  19987. \fi}
  19988. \end{tcolorbox}
  19989. \caption{Output of \code{lower\_casts} on the example shown in
  19990. figure~\ref{fig:gradual-map}.}
  19991. \label{fig:map-lower-cast}
  19992. \end{figure}
  19993. %\pagebreak
  19994. \section{Differentiate Proxies }
  19995. \label{sec:differentiate-proxies}
  19996. So far, the responsibility of differentiating tuples and tuple proxies
  19997. has been the job of the interpreter.
  19998. %
  19999. \racket{For example, the interpreter for \LangCast{} implements
  20000. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20001. figure~\ref{fig:guarded-tuple}.}
  20002. %
  20003. In the \code{differentiate\_proxies} pass we shift this responsibility
  20004. to the generated code.
  20005. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20006. we used the type \TUPLETYPENAME{} for both
  20007. real tuples and tuple proxies.
  20008. \python{Similarly, we use the type \code{list} for both arrays and
  20009. array proxies.}
  20010. In \LangPVec{} we return the
  20011. \TUPLETYPENAME{} type to its original
  20012. meaning, as the type of just tuples, and we introduce a new type,
  20013. \PTUPLETYNAME{}, whose values
  20014. can be either real tuples or tuple
  20015. proxies.
  20016. %
  20017. {\if\edition\pythonEd\pythonColor
  20018. Likewise, we return the
  20019. \ARRAYTYPENAME{} type to its original
  20020. meaning, as the type of arrays, and we introduce a new type,
  20021. \PARRAYTYNAME{}, whose values
  20022. can be either arrays or array proxies.
  20023. These new types come with a suite of new primitive operations.
  20024. \fi}
  20025. {\if\edition\racketEd
  20026. A tuple proxy is represented by a tuple containing three things: (1) the
  20027. underlying tuple, (2) a tuple of functions for casting elements that
  20028. are read from the tuple, and (3) a tuple of functions for casting
  20029. values to be written to the tuple. So, we define the following
  20030. abbreviation for the type of a tuple proxy:
  20031. \[
  20032. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20033. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20034. \]
  20035. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20036. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20037. %
  20038. Next we describe each of the new primitive operations.
  20039. \begin{description}
  20040. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20041. (\key{PVector} $T \ldots$)]\ \\
  20042. %
  20043. This operation brands a vector as a value of the \code{PVector} type.
  20044. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20045. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20046. %
  20047. This operation brands a vector proxy as value of the \code{PVector} type.
  20048. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20049. \BOOLTY{}] \ \\
  20050. %
  20051. This returns true if the value is a tuple proxy and false if it is a
  20052. real tuple.
  20053. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20054. (\key{Vector} $T \ldots$)]\ \\
  20055. %
  20056. Assuming that the input is a tuple, this operation returns the
  20057. tuple.
  20058. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20059. $\to$ \INTTY{}]\ \\
  20060. %
  20061. Given a tuple proxy, this operation returns the length of the tuple.
  20062. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20063. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20064. %
  20065. Given a tuple proxy, this operation returns the $i$th element of the
  20066. tuple.
  20067. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20068. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20069. Given a tuple proxy, this operation writes a value to the $i$th element
  20070. of the tuple.
  20071. \end{description}
  20072. \fi}
  20073. {\if\edition\pythonEd\pythonColor
  20074. %
  20075. A tuple proxy is represented by a tuple containing (1) the underlying
  20076. tuple and (2) a tuple of functions for casting elements that are read
  20077. from the tuple. The \LangPVec{} language includes the following AST
  20078. classes and primitive functions.
  20079. \begin{description}
  20080. \item[\code{InjectTuple}] \ \\
  20081. %
  20082. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20083. \item[\code{InjectTupleProxy}]\ \\
  20084. %
  20085. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20086. \item[\code{is\_tuple\_proxy}]\ \\
  20087. %
  20088. This primitive returns true if the value is a tuple proxy and false
  20089. if it is a tuple.
  20090. \item[\code{project\_tuple}]\ \\
  20091. %
  20092. Converts a tuple that is branded as \PTUPLETYNAME{}
  20093. back to a tuple.
  20094. \item[\code{proxy\_tuple\_len}]\ \\
  20095. %
  20096. Given a tuple proxy, returns the length of the underlying tuple.
  20097. \item[\code{proxy\_tuple\_load}]\ \\
  20098. %
  20099. Given a tuple proxy, returns the $i$th element of the underlying
  20100. tuple.
  20101. \end{description}
  20102. An array proxy is represented by a tuple containing (1) the underlying
  20103. array, (2) a function for casting elements that are read from the
  20104. array, and (3) a function for casting elements that are written to the
  20105. array. The \LangPVec{} language includes the following AST classes
  20106. and primitive functions.
  20107. \begin{description}
  20108. \item[\code{InjectList}]\ \\
  20109. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20110. \item[\code{InjectListProxy}]\ \\
  20111. %
  20112. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20113. \item[\code{is\_array\_proxy}]\ \\
  20114. %
  20115. Returns true if the value is an array proxy and false if it is an
  20116. array.
  20117. \item[\code{project\_array}]\ \\
  20118. %
  20119. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20120. array.
  20121. \item[\code{proxy\_array\_len}]\ \\
  20122. %
  20123. Given an array proxy, returns the length of the underlying array.
  20124. \item[\code{proxy\_array\_load}]\ \\
  20125. %
  20126. Given an array proxy, returns the $i$th element of the underlying
  20127. array.
  20128. \item[\code{proxy\_array\_store}]\ \\
  20129. %
  20130. Given an array proxy, writes a value to the $i$th element of the
  20131. underlying array.
  20132. \end{description}
  20133. \fi}
  20134. Now we discuss the translation that differentiates tuples and arrays
  20135. from proxies. First, every type annotation in the program is
  20136. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20137. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20138. places. For example, we wrap every tuple creation with an
  20139. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20140. %
  20141. {\if\edition\racketEd
  20142. \begin{minipage}{0.96\textwidth}
  20143. \begin{lstlisting}
  20144. (vector |$e_1 \ldots e_n$|)
  20145. |$\Rightarrow$|
  20146. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20147. \end{lstlisting}
  20148. \end{minipage}
  20149. \fi}
  20150. {\if\edition\pythonEd\pythonColor
  20151. \begin{lstlisting}
  20152. Tuple(|$e_1, \ldots, e_n$|)
  20153. |$\Rightarrow$|
  20154. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20155. \end{lstlisting}
  20156. \fi}
  20157. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20158. AST node that we introduced in the previous
  20159. section does not get injected.
  20160. {\if\edition\racketEd
  20161. \begin{lstlisting}
  20162. (raw-vector |$e_1 \ldots e_n$|)
  20163. |$\Rightarrow$|
  20164. (vector |$e'_1 \ldots e'_n$|)
  20165. \end{lstlisting}
  20166. \fi}
  20167. {\if\edition\pythonEd\pythonColor
  20168. \begin{lstlisting}
  20169. RawTuple(|$e_1, \ldots, e_n$|)
  20170. |$\Rightarrow$|
  20171. Tuple(|$e'_1, \ldots, e'_n$|)
  20172. \end{lstlisting}
  20173. \fi}
  20174. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20175. translates as follows:
  20176. %
  20177. {\if\edition\racketEd
  20178. \begin{lstlisting}
  20179. (vector-proxy |$e_1~e_2~e_3$|)
  20180. |$\Rightarrow$|
  20181. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20182. \end{lstlisting}
  20183. \fi}
  20184. {\if\edition\pythonEd\pythonColor
  20185. \begin{lstlisting}
  20186. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20187. |$\Rightarrow$|
  20188. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20189. \end{lstlisting}
  20190. \fi}
  20191. We translate the element access operations into conditional
  20192. expressions that check whether the value is a proxy and then dispatch
  20193. to either the appropriate proxy tuple operation or the regular tuple
  20194. operation.
  20195. {\if\edition\racketEd
  20196. \begin{lstlisting}
  20197. (vector-ref |$e_1$| |$i$|)
  20198. |$\Rightarrow$|
  20199. (let ([|$v~e_1$|])
  20200. (if (proxy? |$v$|)
  20201. (proxy-vector-ref |$v$| |$i$|)
  20202. (vector-ref (project-vector |$v$|) |$i$|)
  20203. \end{lstlisting}
  20204. \fi}
  20205. %
  20206. Note that in the branch for a tuple, we must apply
  20207. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20208. from the tuple.
  20209. The translation of array operations is similar to the ones for tuples.
  20210. \section{Reveal Casts }
  20211. \label{sec:reveal-casts-gradual}
  20212. {\if\edition\racketEd
  20213. Recall that the \code{reveal\_casts} pass
  20214. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20215. \code{Inject} and \code{Project} into lower-level operations.
  20216. %
  20217. In particular, \code{Project} turns into a conditional expression that
  20218. inspects the tag and retrieves the underlying value. Here we need to
  20219. augment the translation of \code{Project} to handle the situation in which
  20220. the target type is \code{PVector}. Instead of using
  20221. \code{vector-length} we need to use \code{proxy-vector-length}.
  20222. \begin{lstlisting}
  20223. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20224. |$\Rightarrow$|
  20225. (let |$\itm{tmp}$| |$e'$|
  20226. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20227. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20228. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20229. (exit)))
  20230. \end{lstlisting}
  20231. \fi}
  20232. %
  20233. {\if\edition\pythonEd\pythonColor
  20234. Recall that the $\itm{tagof}$ function determines the bits used to
  20235. identify values of different types, and it is used in the \code{reveal\_casts}
  20236. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20237. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20238. decimal), just like the tuple and array types.
  20239. \fi}
  20240. %
  20241. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20242. \pagebreak
  20243. \section{Closure Conversion }
  20244. \label{sec:closure-conversion-gradual}
  20245. The auxiliary function that translates type annotations needs to be
  20246. updated to handle the \PTUPLETYNAME{}
  20247. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20248. %
  20249. Otherwise, the only other changes are adding cases that copy the new
  20250. AST nodes.
  20251. \section{Select Instructions }
  20252. \label{sec:select-instructions-gradual}
  20253. \index{subject}{select instructions}
  20254. Recall that the \code{select\_instructions} pass is responsible for
  20255. lowering the primitive operations into x86 instructions. So, we need
  20256. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20257. to x86. To do so, the first question we need to answer is how to
  20258. differentiate between tuple and tuple proxies\python{, and likewise for
  20259. arrays and array proxies}. We need just one bit to accomplish this;
  20260. we use the bit in position $63$ of the 64-bit tag at the front of
  20261. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20262. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20263. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20264. it that way.
  20265. {\if\edition\racketEd
  20266. \begin{lstlisting}
  20267. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20268. |$\Rightarrow$|
  20269. movq |$e'_1$|, |$\itm{lhs'}$|
  20270. \end{lstlisting}
  20271. \fi}
  20272. {\if\edition\pythonEd\pythonColor
  20273. \begin{lstlisting}
  20274. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20275. |$\Rightarrow$|
  20276. movq |$e'_1$|, |$\itm{lhs'}$|
  20277. \end{lstlisting}
  20278. \fi}
  20279. \python{The translation for \code{InjectList} is also a move instruction.}
  20280. \noindent On the other hand,
  20281. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20282. $63$ to $1$.
  20283. %
  20284. {\if\edition\racketEd
  20285. \begin{lstlisting}
  20286. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20287. |$\Rightarrow$|
  20288. movq |$e'_1$|, %r11
  20289. movq |$(1 << 63)$|, %rax
  20290. orq 0(%r11), %rax
  20291. movq %rax, 0(%r11)
  20292. movq %r11, |$\itm{lhs'}$|
  20293. \end{lstlisting}
  20294. \fi}
  20295. {\if\edition\pythonEd\pythonColor
  20296. \begin{lstlisting}
  20297. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20298. |$\Rightarrow$|
  20299. movq |$e'_1$|, %r11
  20300. movq |$(1 << 63)$|, %rax
  20301. orq 0(%r11), %rax
  20302. movq %rax, 0(%r11)
  20303. movq %r11, |$\itm{lhs'}$|
  20304. \end{lstlisting}
  20305. \fi}
  20306. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20307. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20308. The \racket{\code{proxy?} operation consumes}%
  20309. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20310. consume}
  20311. the information so carefully stashed away by the injections. It
  20312. isolates bit $63$ to tell whether the value is a proxy.
  20313. %
  20314. {\if\edition\racketEd
  20315. \begin{lstlisting}
  20316. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20317. |$\Rightarrow$|
  20318. movq |$e_1'$|, %r11
  20319. movq 0(%r11), %rax
  20320. sarq $63, %rax
  20321. andq $1, %rax
  20322. movq %rax, |$\itm{lhs'}$|
  20323. \end{lstlisting}
  20324. \fi}%
  20325. %
  20326. {\if\edition\pythonEd\pythonColor
  20327. \begin{lstlisting}
  20328. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20329. |$\Rightarrow$|
  20330. movq |$e_1'$|, %r11
  20331. movq 0(%r11), %rax
  20332. sarq $63, %rax
  20333. andq $1, %rax
  20334. movq %rax, |$\itm{lhs'}$|
  20335. \end{lstlisting}
  20336. \fi}%
  20337. %
  20338. The \racket{\code{project-vector} operation is}
  20339. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20340. straightforward to translate, so we leave that to the reader.
  20341. Regarding the element access operations for tuples\python{ and arrays}, the
  20342. runtime provides procedures that implement them (they are recursive
  20343. functions!), so here we simply need to translate these tuple
  20344. operations into the appropriate function call. For example, here is
  20345. the translation for
  20346. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20347. {\if\edition\racketEd
  20348. \begin{minipage}{0.96\textwidth}
  20349. \begin{lstlisting}
  20350. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20351. |$\Rightarrow$|
  20352. movq |$e_1'$|, %rdi
  20353. movq |$e_2'$|, %rsi
  20354. callq proxy_vector_ref
  20355. movq %rax, |$\itm{lhs'}$|
  20356. \end{lstlisting}
  20357. \end{minipage}
  20358. \fi}
  20359. {\if\edition\pythonEd\pythonColor
  20360. \begin{lstlisting}
  20361. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20362. |$\Rightarrow$|
  20363. movq |$e_1'$|, %rdi
  20364. movq |$e_2'$|, %rsi
  20365. callq proxy_vector_ref
  20366. movq %rax, |$\itm{lhs'}$|
  20367. \end{lstlisting}
  20368. \fi}
  20369. {\if\edition\pythonEd\pythonColor
  20370. % TODO: revisit the names vecof for python -Jeremy
  20371. We translate
  20372. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20373. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20374. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20375. \fi}
  20376. We have another batch of operations to deal with: those for the
  20377. \CANYTY{} type. Recall that we generate an
  20378. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20379. there is a element access on something of type \CANYTY{}, and
  20380. similarly for
  20381. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20382. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20383. section~\ref{sec:select-Lany} we selected instructions for these
  20384. operations on the basis of the idea that the underlying value was a tuple or
  20385. array. But in the current setting, the underlying value is of type
  20386. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20387. functions to deal with this:
  20388. \code{proxy\_vector\_ref},
  20389. \code{proxy\_vector\_set}, and
  20390. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20391. to determine whether the value is a proxy, and then
  20392. dispatches to the the appropriate code.
  20393. %
  20394. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20395. can be translated as follows.
  20396. We begin by projecting the underlying value out of the tagged value and
  20397. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20398. {\if\edition\racketEd
  20399. \begin{lstlisting}
  20400. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20401. |$\Rightarrow$|
  20402. movq |$\neg 111$|, %rdi
  20403. andq |$e_1'$|, %rdi
  20404. movq |$e_2'$|, %rsi
  20405. callq proxy_vector_ref
  20406. movq %rax, |$\itm{lhs'}$|
  20407. \end{lstlisting}
  20408. \fi}
  20409. {\if\edition\pythonEd\pythonColor
  20410. \begin{lstlisting}
  20411. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20412. |$\Rightarrow$|
  20413. movq |$\neg 111$|, %rdi
  20414. andq |$e_1'$|, %rdi
  20415. movq |$e_2'$|, %rsi
  20416. callq proxy_vector_ref
  20417. movq %rax, |$\itm{lhs'}$|
  20418. \end{lstlisting}
  20419. \fi}
  20420. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20421. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20422. are translated in a similar way. Alternatively, you could generate
  20423. instructions to open-code
  20424. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20425. and \code{proxy\_vector\_length} functions.
  20426. \begin{exercise}\normalfont\normalsize
  20427. Implement a compiler for the gradually typed \LangGrad{} language by
  20428. extending and adapting your compiler for \LangLam{}. Create ten new
  20429. partially typed test programs. In addition to testing with these
  20430. new programs, test your compiler on all the tests for \LangLam{}
  20431. and for \LangDyn{}.
  20432. %
  20433. \racket{Sometimes you may get a type-checking error on the
  20434. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20435. the \CANYTY{} type around each subexpression that has caused a type
  20436. error. Although \LangDyn{} does not have explicit casts, you can
  20437. induce one by wrapping the subexpression \code{e} with a call to
  20438. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20439. %
  20440. \python{Sometimes you may get a type-checking error on the
  20441. \LangDyn{} programs, but you can adapt them by inserting a
  20442. temporary variable of type \CANYTY{} that is initialized with the
  20443. troublesome expression.}
  20444. \end{exercise}
  20445. \begin{figure}[t]
  20446. \begin{tcolorbox}[colback=white]
  20447. {\if\edition\racketEd
  20448. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20449. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20450. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20451. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20452. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20453. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20454. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20455. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20456. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20457. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20458. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20459. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20460. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20461. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20462. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20463. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20464. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20465. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20466. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20467. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20468. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20469. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20470. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20471. \path[->,bend left=15] (Lgradual) edge [above] node
  20472. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20473. \path[->,bend left=15] (Lgradual2) edge [above] node
  20474. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20475. \path[->,bend left=15] (Lgradual3) edge [above] node
  20476. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20477. \path[->,bend left=15] (Lgradual4) edge [left] node
  20478. {\ttfamily\footnotesize shrink} (Lgradualr);
  20479. \path[->,bend left=15] (Lgradualr) edge [above] node
  20480. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20481. \path[->,bend right=15] (Lgradualp) edge [above] node
  20482. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20483. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20484. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20485. \path[->,bend right=15] (Llambdapp) edge [above] node
  20486. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20487. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20488. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20489. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20490. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20491. \path[->,bend left=15] (F1-2) edge [above] node
  20492. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20493. \path[->,bend left=15] (F1-3) edge [left] node
  20494. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20495. \path[->,bend left=15] (F1-4) edge [below] node
  20496. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20497. \path[->,bend right=15] (F1-5) edge [above] node
  20498. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20499. \path[->,bend right=15] (F1-6) edge [above] node
  20500. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20501. \path[->,bend right=15] (C3-2) edge [right] node
  20502. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20503. \path[->,bend right=15] (x86-2) edge [right] node
  20504. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20505. \path[->,bend right=15] (x86-2-1) edge [below] node
  20506. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20507. \path[->,bend right=15] (x86-2-2) edge [right] node
  20508. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20509. \path[->,bend left=15] (x86-3) edge [above] node
  20510. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20511. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20512. \end{tikzpicture}
  20513. \fi}
  20514. {\if\edition\pythonEd\pythonColor
  20515. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20516. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20517. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20518. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20519. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20520. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20521. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20522. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20523. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20524. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20525. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20526. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20527. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20528. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20529. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20530. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20531. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20532. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20533. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20534. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20535. \path[->,bend left=15] (Lgradual) edge [above] node
  20536. {\ttfamily\footnotesize shrink} (Lgradual2);
  20537. \path[->,bend left=15] (Lgradual2) edge [above] node
  20538. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20539. \path[->,bend left=15] (Lgradual3) edge [above] node
  20540. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20541. \path[->,bend left=15] (Lgradual4) edge [left] node
  20542. {\ttfamily\footnotesize resolve} (Lgradualr);
  20543. \path[->,bend left=15] (Lgradualr) edge [below] node
  20544. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20545. \path[->,bend right=15] (Lgradualp) edge [above] node
  20546. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20547. \path[->,bend right=15] (Llambdapp) edge [above] node
  20548. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20549. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20550. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20551. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20552. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20553. \path[->,bend left=15] (F1-1) edge [above] node
  20554. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20555. \path[->,bend left=15] (F1-2) edge [above] node
  20556. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20557. \path[->,bend left=15] (F1-3) edge [right] node
  20558. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20559. \path[->,bend right=15] (F1-5) edge [above] node
  20560. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20561. \path[->,bend right=15] (F1-6) edge [above] node
  20562. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20563. \path[->,bend right=15] (C3-2) edge [right] node
  20564. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20565. \path[->,bend right=15] (x86-2) edge [below] node
  20566. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20567. \path[->,bend right=15] (x86-3) edge [below] node
  20568. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20569. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20570. \end{tikzpicture}
  20571. \fi}
  20572. \end{tcolorbox}
  20573. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20574. \label{fig:Lgradual-passes}
  20575. \end{figure}
  20576. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20577. needed for the compilation of \LangGrad{}.
  20578. \section{Further Reading}
  20579. This chapter just scratches the surface of gradual typing. The basic
  20580. approach described here is missing two key ingredients that one would
  20581. want in an implementation of gradual typing: blame
  20582. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20583. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20584. problem addressed by blame tracking is that when a cast on a
  20585. higher-order value fails, it often does so at a point in the program
  20586. that is far removed from the original cast. Blame tracking is a
  20587. technique for propagating extra information through casts and proxies
  20588. so that when a cast fails, the error message can point back to the
  20589. original location of the cast in the source program.
  20590. The problem addressed by space-efficient casts also relates to
  20591. higher-order casts. It turns out that in partially typed programs, a
  20592. function or tuple can flow through a great many casts at runtime. With
  20593. the approach described in this chapter, each cast adds another
  20594. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20595. considerable space, but it also makes the function calls and tuple
  20596. operations slow. For example, a partially typed version of quicksort
  20597. could, in the worst case, build a chain of proxies of length $O(n)$
  20598. around the tuple, changing the overall time complexity of the
  20599. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20600. solution to this problem by representing casts using the coercion
  20601. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20602. long chains of proxies by compressing them into a concise normal
  20603. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20604. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20605. the Grift compiler:
  20606. \begin{center}
  20607. \url{https://github.com/Gradual-Typing/Grift}
  20608. \end{center}
  20609. There are also interesting interactions between gradual typing and
  20610. other language features, such as generics, information-flow types, and
  20611. type inference, to name a few. We recommend to the reader the
  20612. online gradual typing bibliography for more material:
  20613. \begin{center}
  20614. \url{http://samth.github.io/gradual-typing-bib/}
  20615. \end{center}
  20616. % TODO: challenge problem:
  20617. % type analysis and type specialization?
  20618. % coercions?
  20619. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20620. \chapter{Generics}
  20621. \label{ch:Lpoly}
  20622. \setcounter{footnote}{0}
  20623. This chapter studies the compilation of
  20624. generics\index{subject}{generics} (aka parametric
  20625. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20626. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20627. enable programmers to make code more reusable by parameterizing
  20628. functions and data structures with respect to the types on which they
  20629. operate. For example, figure~\ref{fig:map-poly} revisits the
  20630. \code{map} example and this time gives it a more fitting type. This
  20631. \code{map} function is parameterized with respect to the element type
  20632. of the tuple. The type of \code{map} is the following generic type
  20633. specified by the \code{All} type with parameter \code{T}:
  20634. {\if\edition\racketEd
  20635. \begin{lstlisting}
  20636. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20637. \end{lstlisting}
  20638. \fi}
  20639. {\if\edition\pythonEd\pythonColor
  20640. \begin{lstlisting}
  20641. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20642. \end{lstlisting}
  20643. \fi}
  20644. %
  20645. The idea is that \code{map} can be used at \emph{all} choices of a
  20646. type for parameter \code{T}. In the example shown in
  20647. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20648. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20649. \code{T}, but we could have just as well applied \code{map} to a tuple
  20650. of Booleans.
  20651. %
  20652. A \emph{monomorphic} function is simply one that is not generic.
  20653. %
  20654. We use the term \emph{instantiation} for the process (within the
  20655. language implementation) of turning a generic function into a
  20656. monomorphic one, where the type parameters have been replaced by
  20657. types.
  20658. {\if\edition\pythonEd\pythonColor
  20659. %
  20660. In Python, when writing a generic function such as \code{map}, one
  20661. does not explicitly write its generic type (using \code{All}).
  20662. Instead, that the function is generic is implied by the use of type
  20663. variables (such as \code{T}) in the type annotations of its
  20664. parameters.
  20665. %
  20666. \fi}
  20667. \begin{figure}[tbp]
  20668. % poly_test_2.rkt
  20669. \begin{tcolorbox}[colback=white]
  20670. {\if\edition\racketEd
  20671. \begin{lstlisting}
  20672. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20673. (define (map f v)
  20674. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20675. (define (inc [x : Integer]) : Integer (+ x 1))
  20676. (vector-ref (map inc (vector 0 41)) 1)
  20677. \end{lstlisting}
  20678. \fi}
  20679. {\if\edition\pythonEd\pythonColor
  20680. \begin{lstlisting}
  20681. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20682. return (f(tup[0]), f(tup[1]))
  20683. def add1(x : int) -> int:
  20684. return x + 1
  20685. t = map(add1, (0, 41))
  20686. print(t[1])
  20687. \end{lstlisting}
  20688. \fi}
  20689. \end{tcolorbox}
  20690. \caption{A generic version of the \code{map} function.}
  20691. \label{fig:map-poly}
  20692. \end{figure}
  20693. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20694. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20695. shows the definition of the abstract syntax.
  20696. %
  20697. {\if\edition\racketEd
  20698. We add a second form for function definitions in which a type
  20699. declaration comes before the \code{define}. In the abstract syntax,
  20700. the return type in the \code{Def} is \CANYTY{}, but that should be
  20701. ignored in favor of the return type in the type declaration. (The
  20702. \CANYTY{} comes from using the same parser as discussed in
  20703. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20704. enables the use of an \code{All} type for a function, thereby making
  20705. it generic.
  20706. \fi}
  20707. %
  20708. The grammar for types is extended to include the type of a generic
  20709. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20710. abstract syntax)}.
  20711. \newcommand{\LpolyGrammarRacket}{
  20712. \begin{array}{lcl}
  20713. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20714. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20715. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20716. \end{array}
  20717. }
  20718. \newcommand{\LpolyASTRacket}{
  20719. \begin{array}{lcl}
  20720. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20721. \Def &::=& \DECL{\Var}{\Type} \\
  20722. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20723. \end{array}
  20724. }
  20725. \newcommand{\LpolyGrammarPython}{
  20726. \begin{array}{lcl}
  20727. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20728. \end{array}
  20729. }
  20730. \newcommand{\LpolyASTPython}{
  20731. \begin{array}{lcl}
  20732. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20733. \MID \key{GenericVar}\LP\Var\RP
  20734. \end{array}
  20735. }
  20736. \begin{figure}[tp]
  20737. \centering
  20738. \begin{tcolorbox}[colback=white]
  20739. \footnotesize
  20740. {\if\edition\racketEd
  20741. \[
  20742. \begin{array}{l}
  20743. \gray{\LintGrammarRacket{}} \\ \hline
  20744. \gray{\LvarGrammarRacket{}} \\ \hline
  20745. \gray{\LifGrammarRacket{}} \\ \hline
  20746. \gray{\LwhileGrammarRacket} \\ \hline
  20747. \gray{\LtupGrammarRacket} \\ \hline
  20748. \gray{\LfunGrammarRacket} \\ \hline
  20749. \gray{\LlambdaGrammarRacket} \\ \hline
  20750. \LpolyGrammarRacket \\
  20751. \begin{array}{lcl}
  20752. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20753. \end{array}
  20754. \end{array}
  20755. \]
  20756. \fi}
  20757. {\if\edition\pythonEd\pythonColor
  20758. \[
  20759. \begin{array}{l}
  20760. \gray{\LintGrammarPython{}} \\ \hline
  20761. \gray{\LvarGrammarPython{}} \\ \hline
  20762. \gray{\LifGrammarPython{}} \\ \hline
  20763. \gray{\LwhileGrammarPython} \\ \hline
  20764. \gray{\LtupGrammarPython} \\ \hline
  20765. \gray{\LfunGrammarPython} \\ \hline
  20766. \gray{\LlambdaGrammarPython} \\\hline
  20767. \LpolyGrammarPython \\
  20768. \begin{array}{lcl}
  20769. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20770. \end{array}
  20771. \end{array}
  20772. \]
  20773. \fi}
  20774. \end{tcolorbox}
  20775. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20776. (figure~\ref{fig:Llam-concrete-syntax}).}
  20777. \label{fig:Lpoly-concrete-syntax}
  20778. \end{figure}
  20779. \begin{figure}[tp]
  20780. \centering
  20781. \begin{tcolorbox}[colback=white]
  20782. \footnotesize
  20783. {\if\edition\racketEd
  20784. \[
  20785. \begin{array}{l}
  20786. \gray{\LintOpAST} \\ \hline
  20787. \gray{\LvarASTRacket{}} \\ \hline
  20788. \gray{\LifASTRacket{}} \\ \hline
  20789. \gray{\LwhileASTRacket{}} \\ \hline
  20790. \gray{\LtupASTRacket{}} \\ \hline
  20791. \gray{\LfunASTRacket} \\ \hline
  20792. \gray{\LlambdaASTRacket} \\ \hline
  20793. \LpolyASTRacket \\
  20794. \begin{array}{lcl}
  20795. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20796. \end{array}
  20797. \end{array}
  20798. \]
  20799. \fi}
  20800. {\if\edition\pythonEd\pythonColor
  20801. \[
  20802. \begin{array}{l}
  20803. \gray{\LintASTPython} \\ \hline
  20804. \gray{\LvarASTPython{}} \\ \hline
  20805. \gray{\LifASTPython{}} \\ \hline
  20806. \gray{\LwhileASTPython{}} \\ \hline
  20807. \gray{\LtupASTPython{}} \\ \hline
  20808. \gray{\LfunASTPython} \\ \hline
  20809. \gray{\LlambdaASTPython} \\ \hline
  20810. \LpolyASTPython \\
  20811. \begin{array}{lcl}
  20812. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20813. \end{array}
  20814. \end{array}
  20815. \]
  20816. \fi}
  20817. \end{tcolorbox}
  20818. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20819. (figure~\ref{fig:Llam-syntax}).}
  20820. \label{fig:Lpoly-syntax}
  20821. \end{figure}
  20822. By including the \code{All} type in the $\Type$ nonterminal of the
  20823. grammar we choose to make generics first class, which has interesting
  20824. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20825. not include syntax for the \code{All} type. It is inferred for functions whose
  20826. type annotations contain type variables.} Many languages with generics, such as
  20827. C++~\citep{stroustrup88:_param_types} and Standard
  20828. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20829. may be helpful to see an example of first-class generics in action. In
  20830. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20831. whose parameter is a generic function. Indeed, because the grammar for
  20832. $\Type$ includes the \code{All} type, a generic function may also be
  20833. returned from a function or stored inside a tuple. The body of
  20834. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20835. and also to an integer, which would not be possible if \code{f} were
  20836. not generic.
  20837. \begin{figure}[tbp]
  20838. \begin{tcolorbox}[colback=white]
  20839. {\if\edition\racketEd
  20840. \begin{lstlisting}
  20841. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20842. (define (apply_twice f)
  20843. (if (f #t) (f 42) (f 777)))
  20844. (: id (All (T) (T -> T)))
  20845. (define (id x) x)
  20846. (apply_twice id)
  20847. \end{lstlisting}
  20848. \fi}
  20849. {\if\edition\pythonEd\pythonColor
  20850. \begin{lstlisting}
  20851. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20852. if f(True):
  20853. return f(42)
  20854. else:
  20855. return f(777)
  20856. def id(x: T) -> T:
  20857. return x
  20858. print(apply_twice(id))
  20859. \end{lstlisting}
  20860. \fi}
  20861. \end{tcolorbox}
  20862. \caption{An example illustrating first-class generics.}
  20863. \label{fig:apply-twice}
  20864. \end{figure}
  20865. The type checker for \LangPoly{} shown in
  20866. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20867. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20868. {\if\edition\pythonEd\pythonColor
  20869. %
  20870. Regarding function definitions, if the type annotations on its
  20871. parameters contain generic variables, then the function is generic and
  20872. therefore its type is an \code{All} type wrapped around a function
  20873. type. Otherwise the function is monomorphic and its type is simply
  20874. a function type.
  20875. %
  20876. \fi}
  20877. The type checking of a function application is extended to handle the
  20878. case in which the operator expression is a generic function. In that case
  20879. the type arguments are deduced by matching the types of the parameters
  20880. with the types of the arguments.
  20881. %
  20882. The \code{match\_types} auxiliary function
  20883. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20884. recursively descending through a parameter type \code{param\_ty} and
  20885. the corresponding argument type \code{arg\_ty}, making sure that they
  20886. are equal except when there is a type parameter in the parameter
  20887. type. Upon encountering a type parameter for the first time, the
  20888. algorithm deduces an association of the type parameter to the
  20889. corresponding part of the argument type. If it is not the first time
  20890. that the type parameter has been encountered, the algorithm looks up
  20891. its deduced type and makes sure that it is equal to the corresponding
  20892. part of the argument type. The return type of the application is the
  20893. return type of the generic function with the type parameters
  20894. replaced by the deduced type arguments, using the
  20895. \code{substitute\_type} auxiliary function, which is also listed in
  20896. figure~\ref{fig:type-check-Lpoly-aux}.
  20897. The type checker extends type equality to handle the \code{All} type.
  20898. This is not quite as simple as for other types, such as function and
  20899. tuple types, because two \code{All} types can be syntactically
  20900. different even though they are equivalent. For example,
  20901. \begin{center}
  20902. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20903. \end{center}
  20904. is equivalent to
  20905. \begin{center}
  20906. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20907. \end{center}
  20908. Two generic types are equal if they differ only in
  20909. the choice of the names of the type parameters. The definition of type
  20910. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20911. parameters in one type to match the type parameters of the other type.
  20912. {\if\edition\racketEd
  20913. %
  20914. The type checker also ensures that only defined type variables appear
  20915. in type annotations. The \code{check\_well\_formed} function for which
  20916. the definition is shown in figure~\ref{fig:well-formed-types}
  20917. recursively inspects a type, making sure that each type variable has
  20918. been defined.
  20919. %
  20920. \fi}
  20921. \begin{figure}[tbp]
  20922. \begin{tcolorbox}[colback=white]
  20923. {\if\edition\racketEd
  20924. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20925. (define type-check-poly-class
  20926. (class type-check-Llambda-class
  20927. (super-new)
  20928. (inherit check-type-equal?)
  20929. (define/override (type-check-apply env e1 es)
  20930. (define-values (e^ ty) ((type-check-exp env) e1))
  20931. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20932. ((type-check-exp env) e)))
  20933. (match ty
  20934. [`(,ty^* ... -> ,rt)
  20935. (for ([arg-ty ty*] [param-ty ty^*])
  20936. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20937. (values e^ es^ rt)]
  20938. [`(All ,xs (,tys ... -> ,rt))
  20939. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20940. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20941. (match_types env^^ param-ty arg-ty)))
  20942. (define targs
  20943. (for/list ([x xs])
  20944. (match (dict-ref env^^ x (lambda () #f))
  20945. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20946. x (Apply e1 es))]
  20947. [ty ty])))
  20948. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20949. [else (error 'type-check "expected a function, not ~a" ty)]))
  20950. (define/override ((type-check-exp env) e)
  20951. (match e
  20952. [(Lambda `([,xs : ,Ts] ...) rT body)
  20953. (for ([T Ts]) ((check_well_formed env) T))
  20954. ((check_well_formed env) rT)
  20955. ((super type-check-exp env) e)]
  20956. [(HasType e1 ty)
  20957. ((check_well_formed env) ty)
  20958. ((super type-check-exp env) e)]
  20959. [else ((super type-check-exp env) e)]))
  20960. (define/override ((type-check-def env) d)
  20961. (verbose 'type-check "poly/def" d)
  20962. (match d
  20963. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20964. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20965. (for ([p ps]) ((check_well_formed ts-env) p))
  20966. ((check_well_formed ts-env) rt)
  20967. (define new-env (append ts-env (map cons xs ps) env))
  20968. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20969. (check-type-equal? ty^ rt body)
  20970. (Generic ts (Def f p:t* rt info body^))]
  20971. [else ((super type-check-def env) d)]))
  20972. (define/override (type-check-program p)
  20973. (match p
  20974. [(Program info body)
  20975. (type-check-program (ProgramDefsExp info '() body))]
  20976. [(ProgramDefsExp info ds body)
  20977. (define ds^ (combine-decls-defs ds))
  20978. (define new-env (for/list ([d ds^])
  20979. (cons (def-name d) (fun-def-type d))))
  20980. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20981. (define-values (body^ ty) ((type-check-exp new-env) body))
  20982. (check-type-equal? ty 'Integer body)
  20983. (ProgramDefsExp info ds^^ body^)]))
  20984. ))
  20985. \end{lstlisting}
  20986. \fi}
  20987. {\if\edition\pythonEd\pythonColor
  20988. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20989. def type_check_exp(self, e, env):
  20990. match e:
  20991. case Call(Name(f), args) if f in builtin_functions:
  20992. return super().type_check_exp(e, env)
  20993. case Call(func, args):
  20994. func_t = self.type_check_exp(func, env)
  20995. func.has_type = func_t
  20996. match func_t:
  20997. case AllType(ps, FunctionType(p_tys, rt)):
  20998. for arg in args:
  20999. arg.has_type = self.type_check_exp(arg, env)
  21000. arg_tys = [arg.has_type for arg in args]
  21001. deduced = {}
  21002. for (p, a) in zip(p_tys, arg_tys):
  21003. self.match_types(p, a, deduced, e)
  21004. return self.substitute_type(rt, deduced)
  21005. case _:
  21006. return super().type_check_exp(e, env)
  21007. case _:
  21008. return super().type_check_exp(e, env)
  21009. def type_check(self, p):
  21010. match p:
  21011. case Module(body):
  21012. env = {}
  21013. for s in body:
  21014. match s:
  21015. case FunctionDef(name, params, bod, dl, returns, comment):
  21016. params_t = [t for (x,t) in params]
  21017. ty_params = set()
  21018. for t in params_t:
  21019. ty_params |$\mid$|= self.generic_variables(t)
  21020. ty = FunctionType(params_t, returns)
  21021. if len(ty_params) > 0:
  21022. ty = AllType(list(ty_params), ty)
  21023. env[name] = ty
  21024. self.check_stmts(body, IntType(), env)
  21025. case _:
  21026. raise Exception('type_check: unexpected ' + repr(p))
  21027. \end{lstlisting}
  21028. \fi}
  21029. \end{tcolorbox}
  21030. \caption{Type checker for the \LangPoly{} language.}
  21031. \label{fig:type-check-Lpoly}
  21032. \end{figure}
  21033. \begin{figure}[tbp]
  21034. \begin{tcolorbox}[colback=white]
  21035. {\if\edition\racketEd
  21036. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21037. (define/override (type-equal? t1 t2)
  21038. (match* (t1 t2)
  21039. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21040. (define env (map cons xs ys))
  21041. (type-equal? (substitute_type env T1) T2)]
  21042. [(other wise)
  21043. (super type-equal? t1 t2)]))
  21044. (define/public (match_types env pt at)
  21045. (match* (pt at)
  21046. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21047. [('Void 'Void) env] [('Any 'Any) env]
  21048. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21049. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21050. (match_types env^ pt1 at1))]
  21051. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21052. (define env^ (match_types env prt art))
  21053. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21054. (match_types env^^ pt1 at1))]
  21055. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21056. (define env^ (append (map cons pxs axs) env))
  21057. (match_types env^ pt1 at1)]
  21058. [((? symbol? x) at)
  21059. (match (dict-ref env x (lambda () #f))
  21060. [#f (error 'type-check "undefined type variable ~a" x)]
  21061. ['Type (cons (cons x at) env)]
  21062. [t^ (check-type-equal? at t^ 'matching) env])]
  21063. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21064. (define/public (substitute_type env pt)
  21065. (match pt
  21066. ['Integer 'Integer] ['Boolean 'Boolean]
  21067. ['Void 'Void] ['Any 'Any]
  21068. [`(Vector ,ts ...)
  21069. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21070. [`(,ts ... -> ,rt)
  21071. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21072. [`(All ,xs ,t)
  21073. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21074. [(? symbol? x) (dict-ref env x)]
  21075. [else (error 'type-check "expected a type not ~a" pt)]))
  21076. (define/public (combine-decls-defs ds)
  21077. (match ds
  21078. ['() '()]
  21079. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21080. (unless (equal? name f)
  21081. (error 'type-check "name mismatch, ~a != ~a" name f))
  21082. (match type
  21083. [`(All ,xs (,ps ... -> ,rt))
  21084. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21085. (cons (Generic xs (Def name params^ rt info body))
  21086. (combine-decls-defs ds^))]
  21087. [`(,ps ... -> ,rt)
  21088. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21089. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21090. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21091. [`(,(Def f params rt info body) . ,ds^)
  21092. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21093. \end{lstlisting}
  21094. \fi}
  21095. {\if\edition\pythonEd\pythonColor
  21096. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21097. def match_types(self, param_ty, arg_ty, deduced, e):
  21098. match (param_ty, arg_ty):
  21099. case (GenericVar(id), _):
  21100. if id in deduced:
  21101. self.check_type_equal(arg_ty, deduced[id], e)
  21102. else:
  21103. deduced[id] = arg_ty
  21104. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21105. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21106. new_arg_ty = self.substitute_type(arg_ty, rename)
  21107. self.match_types(ty, new_arg_ty, deduced, e)
  21108. case (TupleType(ps), TupleType(ts)):
  21109. for (p, a) in zip(ps, ts):
  21110. self.match_types(p, a, deduced, e)
  21111. case (ListType(p), ListType(a)):
  21112. self.match_types(p, a, deduced, e)
  21113. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21114. for (pp, ap) in zip(pps, aps):
  21115. self.match_types(pp, ap, deduced, e)
  21116. self.match_types(prt, art, deduced, e)
  21117. case (IntType(), IntType()):
  21118. pass
  21119. case (BoolType(), BoolType()):
  21120. pass
  21121. case _:
  21122. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21123. def substitute_type(self, ty, var_map):
  21124. match ty:
  21125. case GenericVar(id):
  21126. return var_map[id]
  21127. case AllType(ps, ty):
  21128. new_map = copy.deepcopy(var_map)
  21129. for p in ps:
  21130. new_map[p] = GenericVar(p)
  21131. return AllType(ps, self.substitute_type(ty, new_map))
  21132. case TupleType(ts):
  21133. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21134. case ListType(ty):
  21135. return ListType(self.substitute_type(ty, var_map))
  21136. case FunctionType(pts, rt):
  21137. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21138. self.substitute_type(rt, var_map))
  21139. case IntType():
  21140. return IntType()
  21141. case BoolType():
  21142. return BoolType()
  21143. case _:
  21144. raise Exception('substitute_type: unexpected ' + repr(ty))
  21145. def check_type_equal(self, t1, t2, e):
  21146. match (t1, t2):
  21147. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21148. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21149. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21150. case (_, _):
  21151. return super().check_type_equal(t1, t2, e)
  21152. \end{lstlisting}
  21153. \fi}
  21154. \end{tcolorbox}
  21155. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21156. \label{fig:type-check-Lpoly-aux}
  21157. \end{figure}
  21158. {\if\edition\racketEd
  21159. \begin{figure}[tbp]
  21160. \begin{tcolorbox}[colback=white]
  21161. \begin{lstlisting}
  21162. (define/public ((check_well_formed env) ty)
  21163. (match ty
  21164. ['Integer (void)]
  21165. ['Boolean (void)]
  21166. ['Void (void)]
  21167. [(? symbol? a)
  21168. (match (dict-ref env a (lambda () #f))
  21169. ['Type (void)]
  21170. [else (error 'type-check "undefined type variable ~a" a)])]
  21171. [`(Vector ,ts ...)
  21172. (for ([t ts]) ((check_well_formed env) t))]
  21173. [`(,ts ... -> ,t)
  21174. (for ([t ts]) ((check_well_formed env) t))
  21175. ((check_well_formed env) t)]
  21176. [`(All ,xs ,t)
  21177. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21178. ((check_well_formed env^) t)]
  21179. [else (error 'type-check "unrecognized type ~a" ty)]))
  21180. \end{lstlisting}
  21181. \end{tcolorbox}
  21182. \caption{Well-formed types.}
  21183. \label{fig:well-formed-types}
  21184. \end{figure}
  21185. \fi}
  21186. % TODO: interpreter for R'_10
  21187. \clearpage
  21188. \section{Compiling Generics}
  21189. \label{sec:compiling-poly}
  21190. Broadly speaking, there are four approaches to compiling generics, as
  21191. follows:
  21192. \begin{description}
  21193. \item[Monomorphization] generates a different version of a generic
  21194. function for each set of type arguments with which it is used,
  21195. producing type-specialized code. This approach results in the most
  21196. efficient code but requires whole-program compilation (no separate
  21197. compilation) and may increase code size. Unfortunately,
  21198. monomorphization is incompatible with first-class generics because
  21199. it is not always possible to determine which generic functions are
  21200. used with which type arguments during compilation. (It can be done
  21201. at runtime with just-in-time compilation.) Monomorphization is
  21202. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21203. generic functions in NESL~\citep{Blelloch:1993aa} and
  21204. ML~\citep{Weeks:2006aa}.
  21205. \item[Uniform representation] generates one version of each generic
  21206. function and requires all values to have a common \emph{boxed} format,
  21207. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21208. generic and monomorphic code is compiled similarly to code in a
  21209. dynamically typed language (like \LangDyn{}), in which primitive
  21210. operators require their arguments to be projected from \CANYTY{} and
  21211. their results to be injected into \CANYTY{}. (In object-oriented
  21212. languages, the projection is accomplished via virtual method
  21213. dispatch.) The uniform representation approach is compatible with
  21214. separate compilation and with first-class generics. However, it
  21215. produces the least efficient code because it introduces overhead in
  21216. the entire program. This approach is used in
  21217. Java~\citep{Bracha:1998fk},
  21218. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21219. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21220. \item[Mixed representation] generates one version of each generic
  21221. function, using a boxed representation for type variables. However,
  21222. monomorphic code is compiled as usual (as in \LangLam{}), and
  21223. conversions are performed at the boundaries between monomorphic code
  21224. and polymorphic code (for example, when a generic function is instantiated
  21225. and called). This approach is compatible with separate compilation
  21226. and first-class generics and maintains efficiency in monomorphic
  21227. code. The trade-off is increased overhead at the boundary between
  21228. monomorphic and generic code. This approach is used in
  21229. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21230. Java 5 with the addition of autoboxing.
  21231. \item[Type passing] uses the unboxed representation in both
  21232. monomorphic and generic code. Each generic function is compiled to a
  21233. single function with extra parameters that describe the type
  21234. arguments. The type information is used by the generated code to
  21235. determine how to access the unboxed values at runtime. This approach is
  21236. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21237. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21238. compilation and first-class generics and maintains the
  21239. efficiency for monomorphic code. There is runtime overhead in
  21240. polymorphic code from dispatching on type information.
  21241. \end{description}
  21242. In this chapter we use the mixed representation approach, partly
  21243. because of its favorable attributes and partly because it is
  21244. straightforward to implement using the tools that we have already
  21245. built to support gradual typing. The work of compiling generic
  21246. functions is performed in two passes, \code{resolve} and
  21247. \code{erase\_types}, that we discuss next. The output of
  21248. \code{erase\_types} is \LangCast{}
  21249. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21250. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21251. \section{Resolve Instantiation}
  21252. \label{sec:generic-resolve}
  21253. Recall that the type checker for \LangPoly{} deduces the type
  21254. arguments at call sites to a generic function. The purpose of the
  21255. \code{resolve} pass is to turn this implicit instantiation into an
  21256. explicit one, by adding \code{inst} nodes to the syntax of the
  21257. intermediate language. An \code{inst} node records the mapping of
  21258. type parameters to type arguments. The semantics of the \code{inst}
  21259. node is to instantiate the result of its first argument, a generic
  21260. function, to produce a monomorphic function. However, because the
  21261. interpreter never analyzes type annotations, instantiation can be a
  21262. no-op and simply return the generic function.
  21263. %
  21264. The output language of the \code{resolve} pass is \LangInst{},
  21265. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21266. {\if\edition\racketEd
  21267. The \code{resolve} pass combines the type declaration and polymorphic
  21268. function into a single definition, using the \code{Poly} form, to make
  21269. polymorphic functions more convenient to process in the next pass of the
  21270. compiler.
  21271. \fi}
  21272. \newcommand{\LinstASTRacket}{
  21273. \begin{array}{lcl}
  21274. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21275. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21276. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21277. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21278. \end{array}
  21279. }
  21280. \newcommand{\LinstASTPython}{
  21281. \begin{array}{lcl}
  21282. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21283. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21284. \end{array}
  21285. }
  21286. \begin{figure}[tp]
  21287. \centering
  21288. \begin{tcolorbox}[colback=white]
  21289. \small
  21290. {\if\edition\racketEd
  21291. \[
  21292. \begin{array}{l}
  21293. \gray{\LintOpAST} \\ \hline
  21294. \gray{\LvarASTRacket{}} \\ \hline
  21295. \gray{\LifASTRacket{}} \\ \hline
  21296. \gray{\LwhileASTRacket{}} \\ \hline
  21297. \gray{\LtupASTRacket{}} \\ \hline
  21298. \gray{\LfunASTRacket} \\ \hline
  21299. \gray{\LlambdaASTRacket} \\ \hline
  21300. \LinstASTRacket \\
  21301. \begin{array}{lcl}
  21302. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21303. \end{array}
  21304. \end{array}
  21305. \]
  21306. \fi}
  21307. {\if\edition\pythonEd\pythonColor
  21308. \[
  21309. \begin{array}{l}
  21310. \gray{\LintASTPython} \\ \hline
  21311. \gray{\LvarASTPython{}} \\ \hline
  21312. \gray{\LifASTPython{}} \\ \hline
  21313. \gray{\LwhileASTPython{}} \\ \hline
  21314. \gray{\LtupASTPython{}} \\ \hline
  21315. \gray{\LfunASTPython} \\ \hline
  21316. \gray{\LlambdaASTPython} \\ \hline
  21317. \LinstASTPython \\
  21318. \begin{array}{lcl}
  21319. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21320. \end{array}
  21321. \end{array}
  21322. \]
  21323. \fi}
  21324. \end{tcolorbox}
  21325. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21326. (figure~\ref{fig:Llam-syntax}).}
  21327. \label{fig:Lpoly-prime-syntax}
  21328. \end{figure}
  21329. The output of the \code{resolve} pass on the generic \code{map}
  21330. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21331. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21332. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21333. \begin{figure}[tbp]
  21334. % poly_test_2.rkt
  21335. \begin{tcolorbox}[colback=white]
  21336. {\if\edition\racketEd
  21337. \begin{lstlisting}
  21338. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21339. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21340. (define (inc [x : Integer]) : Integer (+ x 1))
  21341. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21342. (Integer))
  21343. inc (vector 0 41)) 1)
  21344. \end{lstlisting}
  21345. \fi}
  21346. {\if\edition\pythonEd\pythonColor
  21347. \begin{lstlisting}
  21348. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21349. return (f(tup[0]), f(tup[1]))
  21350. def add1(x : int) -> int:
  21351. return x + 1
  21352. t = inst(map, {T: int})(add1, (0, 41))
  21353. print(t[1])
  21354. \end{lstlisting}
  21355. \fi}
  21356. \end{tcolorbox}
  21357. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21358. \label{fig:map-resolve}
  21359. \end{figure}
  21360. \section{Erase Generic Types}
  21361. \label{sec:erase_types}
  21362. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21363. represent type variables. For example, figure~\ref{fig:map-erase}
  21364. shows the output of the \code{erase\_types} pass on the generic
  21365. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21366. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21367. \code{All} types are removed from the type of \code{map}.
  21368. \begin{figure}[tbp]
  21369. \begin{tcolorbox}[colback=white]
  21370. {\if\edition\racketEd
  21371. \begin{lstlisting}
  21372. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21373. : (Vector Any Any)
  21374. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21375. (define (inc [x : Integer]) : Integer (+ x 1))
  21376. (vector-ref ((cast map
  21377. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21378. ((Integer -> Integer) (Vector Integer Integer)
  21379. -> (Vector Integer Integer)))
  21380. inc (vector 0 41)) 1)
  21381. \end{lstlisting}
  21382. \fi}
  21383. {\if\edition\pythonEd\pythonColor
  21384. \begin{lstlisting}
  21385. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21386. return (f(tup[0]), f(tup[1]))
  21387. def add1(x : int) -> int:
  21388. return (x + 1)
  21389. def main() -> int:
  21390. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21391. print(t[1])
  21392. return 0
  21393. \end{lstlisting}
  21394. {\small
  21395. where\\
  21396. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21397. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21398. }
  21399. \fi}
  21400. \end{tcolorbox}
  21401. \caption{The generic \code{map} example after type erasure.}
  21402. \label{fig:map-erase}
  21403. \end{figure}
  21404. This process of type erasure creates a challenge at points of
  21405. instantiation. For example, consider the instantiation of
  21406. \code{map} shown in figure~\ref{fig:map-resolve}.
  21407. The type of \code{map} is
  21408. %
  21409. {\if\edition\racketEd
  21410. \begin{lstlisting}
  21411. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21412. \end{lstlisting}
  21413. \fi}
  21414. {\if\edition\pythonEd\pythonColor
  21415. \begin{lstlisting}
  21416. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21417. \end{lstlisting}
  21418. \fi}
  21419. %
  21420. \noindent and it is instantiated to
  21421. %
  21422. {\if\edition\racketEd
  21423. \begin{lstlisting}
  21424. ((Integer -> Integer) (Vector Integer Integer)
  21425. -> (Vector Integer Integer))
  21426. \end{lstlisting}
  21427. \fi}
  21428. {\if\edition\pythonEd\pythonColor
  21429. \begin{lstlisting}
  21430. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21431. \end{lstlisting}
  21432. \fi}
  21433. %
  21434. \noindent After erasure, the type of \code{map} is
  21435. %
  21436. {\if\edition\racketEd
  21437. \begin{lstlisting}
  21438. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21439. \end{lstlisting}
  21440. \fi}
  21441. {\if\edition\pythonEd\pythonColor
  21442. \begin{lstlisting}
  21443. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21444. \end{lstlisting}
  21445. \fi}
  21446. %
  21447. \noindent but we need to convert it to the instantiated type. This is
  21448. easy to do in the language \LangCast{} with a single \code{cast}. In
  21449. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21450. \code{map} has been compiled to a \code{cast} from the type of
  21451. \code{map} to the instantiated type. The source and the target type of
  21452. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21453. is the case because both the source and target are obtained from the
  21454. same generic type of \code{map}, replacing the type parameters with
  21455. \CANYTY{} in the former and with the deduced type arguments in the
  21456. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21457. To implement the \code{erase\_types} pass, we first recommend defining
  21458. a recursive function that translates types, named
  21459. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21460. follows.
  21461. %
  21462. {\if\edition\racketEd
  21463. \begin{lstlisting}
  21464. |$T$|
  21465. |$\Rightarrow$|
  21466. Any
  21467. \end{lstlisting}
  21468. \fi}
  21469. {\if\edition\pythonEd\pythonColor
  21470. \begin{lstlisting}
  21471. GenericVar(|$T$|)
  21472. |$\Rightarrow$|
  21473. Any
  21474. \end{lstlisting}
  21475. \fi}
  21476. %
  21477. \noindent The \code{erase\_type} function also removes the generic
  21478. \code{All} types.
  21479. %
  21480. {\if\edition\racketEd
  21481. \begin{lstlisting}
  21482. (All |$xs$| |$T_1$|)
  21483. |$\Rightarrow$|
  21484. |$T'_1$|
  21485. \end{lstlisting}
  21486. \fi}
  21487. {\if\edition\pythonEd\pythonColor
  21488. \begin{lstlisting}
  21489. AllType(|$xs$|, |$T_1$|)
  21490. |$\Rightarrow$|
  21491. |$T'_1$|
  21492. \end{lstlisting}
  21493. \fi}
  21494. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21495. $T_1$.
  21496. %
  21497. In this compiler pass, apply the \code{erase\_type} function to all
  21498. the type annotations in the program.
  21499. Regarding the translation of expressions, the case for \code{Inst} is
  21500. the interesting one. We translate it into a \code{Cast}, as shown
  21501. next.
  21502. The type of the subexpression $e$ is a generic type of the form
  21503. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21504. The source type of the cast is the erasure of $T$, the type $T_s$.
  21505. %
  21506. {\if\edition\racketEd
  21507. %
  21508. The target type $T_t$ is the result of substituting the argument types
  21509. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21510. erasure.
  21511. %
  21512. \begin{lstlisting}
  21513. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21514. |$\Rightarrow$|
  21515. (Cast |$e'$| |$T_s$| |$T_t$|)
  21516. \end{lstlisting}
  21517. %
  21518. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21519. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21520. \fi}
  21521. {\if\edition\pythonEd\pythonColor
  21522. %
  21523. The target type $T_t$ is the result of substituting the deduced
  21524. argument types $d$ in $T$ and then performing type erasure.
  21525. %
  21526. \begin{lstlisting}
  21527. Inst(|$e$|, |$d$|)
  21528. |$\Rightarrow$|
  21529. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21530. \end{lstlisting}
  21531. %
  21532. where
  21533. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21534. \fi}
  21535. Finally, each generic function is translated to a regular
  21536. function in which type erasure has been applied to all the type
  21537. annotations and the body.
  21538. %% \begin{lstlisting}
  21539. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21540. %% |$\Rightarrow$|
  21541. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21542. %% \end{lstlisting}
  21543. \begin{exercise}\normalfont\normalsize
  21544. Implement a compiler for the polymorphic language \LangPoly{} by
  21545. extending and adapting your compiler for \LangGrad{}. Create six new
  21546. test programs that use polymorphic functions. Some of them should
  21547. make use of first-class generics.
  21548. \end{exercise}
  21549. \begin{figure}[tbp]
  21550. \begin{tcolorbox}[colback=white]
  21551. {\if\edition\racketEd
  21552. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21553. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21554. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21555. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21556. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21557. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21558. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21559. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21560. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21561. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21562. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21563. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21564. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21565. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21566. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21567. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21568. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21569. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21570. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21571. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21572. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21573. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21574. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21575. \path[->,bend left=15] (Lpoly) edge [above] node
  21576. {\ttfamily\footnotesize resolve} (Lpolyp);
  21577. \path[->,bend left=15] (Lpolyp) edge [above] node
  21578. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21579. \path[->,bend left=15] (Lgradualp) edge [above] node
  21580. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21581. \path[->,bend left=15] (Llambdapp) edge [left] node
  21582. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21583. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21584. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21585. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21586. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21587. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21588. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21589. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21590. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21591. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21592. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21593. \path[->,bend left=15] (F1-1) edge [above] node
  21594. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21595. \path[->,bend left=15] (F1-2) edge [above] node
  21596. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21597. \path[->,bend left=15] (F1-3) edge [left] node
  21598. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21599. \path[->,bend left=15] (F1-4) edge [below] node
  21600. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21601. \path[->,bend right=15] (F1-5) edge [above] node
  21602. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21603. \path[->,bend right=15] (F1-6) edge [above] node
  21604. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21605. \path[->,bend right=15] (C3-2) edge [right] node
  21606. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21607. \path[->,bend right=15] (x86-2) edge [right] node
  21608. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21609. \path[->,bend right=15] (x86-2-1) edge [below] node
  21610. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21611. \path[->,bend right=15] (x86-2-2) edge [right] node
  21612. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21613. \path[->,bend left=15] (x86-3) edge [above] node
  21614. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21615. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21616. \end{tikzpicture}
  21617. \fi}
  21618. {\if\edition\pythonEd\pythonColor
  21619. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21620. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21621. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21622. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21623. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21624. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21625. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21626. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21627. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21628. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21629. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21630. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21631. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21632. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21633. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21634. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21635. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21636. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21637. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21638. \path[->,bend left=15] (Lgradual) edge [above] node
  21639. {\ttfamily\footnotesize shrink} (Lgradual2);
  21640. \path[->,bend left=15] (Lgradual2) edge [above] node
  21641. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21642. \path[->,bend left=15] (Lgradual3) edge [above] node
  21643. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21644. \path[->,bend left=15] (Lgradual4) edge [left] node
  21645. {\ttfamily\footnotesize resolve} (Lgradualr);
  21646. \path[->,bend left=15] (Lgradualr) edge [below] node
  21647. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21648. \path[->,bend right=15] (Llambdapp) edge [above] node
  21649. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21650. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21651. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21652. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21653. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21654. \path[->,bend right=15] (F1-1) edge [below] node
  21655. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21656. \path[->,bend right=15] (F1-2) edge [below] node
  21657. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21658. \path[->,bend left=15] (F1-3) edge [above] node
  21659. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21660. \path[->,bend left=15] (F1-5) edge [left] node
  21661. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21662. \path[->,bend left=5] (F1-6) edge [below] node
  21663. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21664. \path[->,bend right=15] (C3-2) edge [right] node
  21665. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21666. \path[->,bend right=15] (x86-2) edge [below] node
  21667. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21668. \path[->,bend right=15] (x86-3) edge [below] node
  21669. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21670. \path[->,bend left=15] (x86-4) edge [above] node
  21671. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21672. \end{tikzpicture}
  21673. \fi}
  21674. \end{tcolorbox}
  21675. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21676. \label{fig:Lpoly-passes}
  21677. \end{figure}
  21678. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21679. needed to compile \LangPoly{}.
  21680. % TODO: challenge problem: specialization of instantiations
  21681. % Further Reading
  21682. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21683. \clearpage
  21684. \appendix
  21685. \chapter{Appendix}
  21686. \setcounter{footnote}{0}
  21687. {\if\edition\racketEd
  21688. \section{Interpreters}
  21689. \label{appendix:interp}
  21690. \index{subject}{interpreter}
  21691. We provide interpreters for each of the source languages \LangInt{},
  21692. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21693. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21694. intermediate languages \LangCVar{} and \LangCIf{} are in
  21695. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21696. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21697. \key{interp.rkt} file.
  21698. \section{Utility Functions}
  21699. \label{appendix:utilities}
  21700. The utility functions described in this section are in the
  21701. \key{utilities.rkt} file of the support code.
  21702. \paragraph{\code{interp-tests}}
  21703. This function runs the compiler passes and the interpreters on each of
  21704. the specified tests to check whether each pass is correct. The
  21705. \key{interp-tests} function has the following parameters:
  21706. \begin{description}
  21707. \item[name (a string)] A name to identify the compiler.
  21708. \item[typechecker] A function of exactly one argument that either
  21709. raises an error using the \code{error} function when it encounters a
  21710. type error, or returns \code{\#f} when it encounters a type
  21711. error. If there is no type error, the type checker returns the
  21712. program.
  21713. \item[passes] A list with one entry per pass. An entry is a list
  21714. consisting of four things:
  21715. \begin{enumerate}
  21716. \item a string giving the name of the pass;
  21717. \item the function that implements the pass (a translator from AST
  21718. to AST);
  21719. \item a function that implements the interpreter (a function from
  21720. AST to result value) for the output language; and,
  21721. \item a type checker for the output language. Type checkers for
  21722. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21723. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21724. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21725. type checker entry is optional. The support code does not provide
  21726. type checkers for the x86 languages.
  21727. \end{enumerate}
  21728. \item[source-interp] An interpreter for the source language. The
  21729. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21730. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21731. \item[tests] A list of test numbers that specifies which tests to
  21732. run (explained next).
  21733. \end{description}
  21734. %
  21735. The \key{interp-tests} function assumes that the subdirectory
  21736. \key{tests} has a collection of Racket programs whose names all start
  21737. with the family name, followed by an underscore and then the test
  21738. number, and ending with the file extension \key{.rkt}. Also, for each test
  21739. program that calls \code{read} one or more times, there is a file with
  21740. the same name except that the file extension is \key{.in}, which
  21741. provides the input for the Racket program. If the test program is
  21742. expected to fail type checking, then there should be an empty file of
  21743. the same name with extension \key{.tyerr}.
  21744. \paragraph{\code{compiler-tests}}
  21745. This function runs the compiler passes to generate x86 (a \key{.s}
  21746. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21747. It runs the machine code and checks that the output is $42$. The
  21748. parameters to the \code{compiler-tests} function are similar to those
  21749. of the \code{interp-tests} function, and they consist of
  21750. \begin{itemize}
  21751. \item a compiler name (a string),
  21752. \item a type checker,
  21753. \item description of the passes,
  21754. \item name of a test-family, and
  21755. \item a list of test numbers.
  21756. \end{itemize}
  21757. \paragraph{\code{compile-file}}
  21758. This function takes a description of the compiler passes (see the
  21759. comment for \key{interp-tests}) and returns a function that, given a
  21760. program file name (a string ending in \key{.rkt}), applies all the
  21761. passes and writes the output to a file whose name is the same as the
  21762. program file name with extension \key{.rkt} replaced by \key{.s}.
  21763. \paragraph{\code{read-program}}
  21764. This function takes a file path and parses that file (it must be a
  21765. Racket program) into an abstract syntax tree.
  21766. \paragraph{\code{parse-program}}
  21767. This function takes an S-expression representation of an abstract
  21768. syntax tree and converts it into the struct-based representation.
  21769. \paragraph{\code{assert}}
  21770. This function takes two parameters, a string (\code{msg}) and Boolean
  21771. (\code{bool}), and displays the message \key{msg} if the Boolean
  21772. \key{bool} is false.
  21773. \paragraph{\code{lookup}}
  21774. % remove discussion of lookup? -Jeremy
  21775. This function takes a key and an alist and returns the first value that is
  21776. associated with the given key, if there is one. If not, an error is
  21777. triggered. The alist may contain both immutable pairs (built with
  21778. \key{cons}) and mutable pairs (built with \key{mcons}).
  21779. %The \key{map2} function ...
  21780. \fi} %\racketEd
  21781. \section{x86 Instruction Set Quick Reference}
  21782. \label{sec:x86-quick-reference}
  21783. \index{subject}{x86}
  21784. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21785. do. We write $A \to B$ to mean that the value of $A$ is written into
  21786. location $B$. Address offsets are given in bytes. The instruction
  21787. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21788. registers (such as \code{\%rax}), or memory references (such as
  21789. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21790. reference per instruction. Other operands must be immediates or
  21791. registers.
  21792. \begin{table}[tbp]
  21793. \captionabove{Quick reference for the x86 instructions used in this book.}
  21794. \label{tab:x86-instr}
  21795. \centering
  21796. \begin{tabular}{l|l}
  21797. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21798. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21799. \texttt{negq} $A$ & $- A \to A$ \\
  21800. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21801. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21802. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21803. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21804. \texttt{retq} & Pops the return address and jumps to it. \\
  21805. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21806. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21807. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21808. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21809. & \\
  21810. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21811. matches the condition code of the instruction; otherwise go to the
  21812. next instructions. The condition codes are \key{e} for \emph{equal},
  21813. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21814. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21815. \texttt{jl} $L$ & \\
  21816. \texttt{jle} $L$ & \\
  21817. \texttt{jg} $L$ & \\
  21818. \texttt{jge} $L$ & \\
  21819. \texttt{jmp} $L$ & Jump to label $L$. \\
  21820. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21821. \texttt{movzbq} $A$, $B$ &
  21822. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21823. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21824. and the extra bytes of $B$ are set to zero.} \\
  21825. & \\
  21826. & \\
  21827. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21828. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21829. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21830. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21831. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21832. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21833. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21834. description of the condition codes. $A$ must be a single byte register
  21835. (e.g., \texttt{al} or \texttt{cl}).} \\
  21836. \texttt{setl} $A$ & \\
  21837. \texttt{setle} $A$ & \\
  21838. \texttt{setg} $A$ & \\
  21839. \texttt{setge} $A$ &
  21840. \end{tabular}
  21841. \end{table}
  21842. \backmatter
  21843. \addtocontents{toc}{\vspace{11pt}}
  21844. \cleardoublepage % needed for right page number in TOC for References
  21845. %% \nocite{*} is a way to get all the entries in the .bib file to
  21846. %% print in the bibliography:
  21847. \nocite{*}\let\bibname\refname
  21848. \addcontentsline{toc}{fmbm}{\refname}
  21849. \printbibliography
  21850. %\printindex{authors}{Author Index}
  21851. \printindex{subject}{Index}
  21852. \end{document}
  21853. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21854. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21855. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21856. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21857. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21858. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21859. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21860. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21861. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21862. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21863. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21864. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21865. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21866. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21867. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21868. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21869. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21870. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21871. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21872. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21873. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21874. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21875. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21876. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21877. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21878. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21879. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21880. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21881. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21882. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21883. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21884. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21885. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21886. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21887. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21888. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21889. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21890. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21891. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21892. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21893. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21894. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21895. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21896. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21897. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21898. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21899. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21900. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21901. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21902. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21903. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21904. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21905. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21906. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21907. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21908. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21909. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21910. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21911. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21912. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21913. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21914. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21915. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21916. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21917. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21918. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21919. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21920. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21921. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21922. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21923. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21924. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21925. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21926. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21927. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21928. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21929. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21930. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21931. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21932. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21933. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21934. % LocalWords: pseudocode underapproximation underapproximations LALR
  21935. % LocalWords: semilattices overapproximate incrementing Earley docs
  21936. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21937. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21938. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21939. % LocalWords: LC partialevaluation pythonEd TOC TrappedError