book.tex 829 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. \makeatletter
  35. \newcommand{\captionabove}[2][]{%
  36. \vskip-\abovecaptionskip
  37. \vskip+\belowcaptionskip
  38. \ifx\@nnil#1\@nnil
  39. \caption{#2}%
  40. \else
  41. \caption[#1]{#2}%
  42. \fi
  43. \vskip+\abovecaptionskip
  44. \vskip-\belowcaptionskip
  45. }
  46. %% For multiple indices:
  47. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  48. \makeindex{subject}
  49. %\makeindex{authors}
  50. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  51. \if\edition\racketEd
  52. \lstset{%
  53. language=Lisp,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  56. deletekeywords={read,mapping,vector},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. \if\edition\pythonEd
  64. \lstset{%
  65. language=Python,
  66. basicstyle=\ttfamily\small,
  67. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  68. deletekeywords={},
  69. escapechar=|,
  70. columns=flexible,
  71. %moredelim=[is][\color{red}]{~}{~},
  72. showstringspaces=false
  73. }
  74. \fi
  75. %%% Any shortcut own defined macros place here
  76. %% sample of author macro:
  77. \input{defs}
  78. \newtheorem{exercise}[theorem]{Exercise}
  79. \numberwithin{theorem}{chapter}
  80. \numberwithin{definition}{chapter}
  81. \numberwithin{equation}{chapter}
  82. % Adjusted settings
  83. \setlength{\columnsep}{4pt}
  84. %% \begingroup
  85. %% \setlength{\intextsep}{0pt}%
  86. %% \setlength{\columnsep}{0pt}%
  87. %% \begin{wrapfigure}{r}{0.5\textwidth}
  88. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  89. %% \caption{Basic layout}
  90. %% \end{wrapfigure}
  91. %% \lipsum[1]
  92. %% \endgroup
  93. \newbox\oiintbox
  94. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  95. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  96. \def\oiint{\copy\oiintbox}
  97. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  98. %\usepackage{showframe}
  99. \def\ShowFrameLinethickness{0.125pt}
  100. \addbibresource{book.bib}
  101. \if\edition\pythonEd
  102. \addbibresource{python.bib}
  103. \fi
  104. \begin{document}
  105. \frontmatter
  106. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  107. \HalfTitle{Essentials of Compilation}
  108. \halftitlepage
  109. \clearemptydoublepage
  110. \Title{Essentials of Compilation}
  111. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  112. %\edition{First Edition}
  113. \BookAuthor{Jeremy G. Siek}
  114. \imprint{The MIT Press\\
  115. Cambridge, Massachusetts\\
  116. London, England}
  117. \begin{copyrightpage}
  118. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  119. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  120. Subject to such license, all rights are reserved. \\[2ex]
  121. \includegraphics{CCBY-logo}
  122. The MIT Press would like to thank the anonymous peer reviewers who
  123. provided comments on drafts of this book. The generous work of
  124. academic experts is essential for establishing the authority and
  125. quality of our publications. We acknowledge with gratitude the
  126. contributions of these otherwise uncredited readers.
  127. This book was set in Times LT Std Roman by the author. Printed and
  128. bound in the United States of America.
  129. {\if\edition\racketEd
  130. Library of Congress Cataloging-in-Publication Data\\
  131. \ \\
  132. Names: Siek, Jeremy, author. \\
  133. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  134. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  135. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  136. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  137. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  138. LC record available at https://lccn.loc.gov/2022015399\\
  139. LC ebook record available at https://lccn.loc.gov/2022015400\\
  140. \ \\
  141. \fi}
  142. 10 9 8 7 6 5 4 3 2 1
  143. %% Jeremy G. Siek. Available for free viewing
  144. %% or personal downloading under the
  145. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  146. %% license.
  147. %% Copyright in this monograph has been licensed exclusively to The MIT
  148. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  149. %% version to the public in 2022. All inquiries regarding rights should
  150. %% be addressed to The MIT Press, Rights and Permissions Department.
  151. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  152. %% All rights reserved. No part of this book may be reproduced in any
  153. %% form by any electronic or mechanical means (including photocopying,
  154. %% recording, or information storage and retrieval) without permission in
  155. %% writing from the publisher.
  156. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  157. %% United States of America.
  158. %% Library of Congress Cataloging-in-Publication Data is available.
  159. %% ISBN:
  160. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  161. \end{copyrightpage}
  162. \dedication{This book is dedicated to Katie, my partner in everything,
  163. my children, who grew up during the writing of this book, and the
  164. programming language students at Indiana University, whose
  165. thoughtful questions made this a better book.}
  166. %% \begin{epigraphpage}
  167. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  168. %% \textit{Book Name if any}}
  169. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  170. %% \end{epigraphpage}
  171. \tableofcontents
  172. %\listoffigures
  173. %\listoftables
  174. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  175. \chapter*{Preface}
  176. \addcontentsline{toc}{fmbm}{Preface}
  177. There is a magical moment when a programmer presses the \emph{run}
  178. button and the software begins to execute. Somehow a program written
  179. in a high-level language is running on a computer that is capable only
  180. of shuffling bits. Here we reveal the wizardry that makes that moment
  181. possible. Beginning with the groundbreaking work of Backus and
  182. colleagues in the 1950s, computer scientists developed techniques for
  183. constructing programs called \emph{compilers} that automatically
  184. translate high-level programs into machine code.
  185. We take you on a journey through constructing your own compiler for a
  186. small but powerful language. Along the way we explain the essential
  187. concepts, algorithms, and data structures that underlie compilers. We
  188. develop your understanding of how programs are mapped onto computer
  189. hardware, which is helpful in reasoning about properties at the
  190. junction of hardware and software, such as execution time, software
  191. errors, and security vulnerabilities. For those interested in
  192. pursuing compiler construction as a career, our goal is to provide a
  193. stepping-stone to advanced topics such as just-in-time compilation,
  194. program analysis, and program optimization. For those interested in
  195. designing and implementing programming languages, we connect language
  196. design choices to their impact on the compiler and the generated code.
  197. A compiler is typically organized as a sequence of stages that
  198. progressively translate a program to the code that runs on
  199. hardware. We take this approach to the extreme by partitioning our
  200. compiler into a large number of \emph{nanopasses}, each of which
  201. performs a single task. This enables the testing of each pass in
  202. isolation and focuses our attention, making the compiler far easier to
  203. understand.
  204. The most familiar approach to describing compilers is to dedicate each
  205. chapter to one pass. The problem with that approach is that it
  206. obfuscates how language features motivate design choices in a
  207. compiler. We instead take an \emph{incremental} approach in which we
  208. build a complete compiler in each chapter, starting with a small input
  209. language that includes only arithmetic and variables. We add new
  210. language features in subsequent chapters, extending the compiler as
  211. necessary.
  212. Our choice of language features is designed to elicit fundamental
  213. concepts and algorithms used in compilers.
  214. \begin{itemize}
  215. \item We begin with integer arithmetic and local variables in
  216. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  217. the fundamental tools of compiler construction: \emph{abstract
  218. syntax trees} and \emph{recursive functions}.
  219. {\if\edition\pythonEd\pythonColor
  220. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  221. parser framework to create a parser for the language of integer
  222. arithmetic and local variables. We learn about the parsing
  223. algorithms inside Lark, including Earley and LALR(1).
  224. %
  225. \fi}
  226. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  227. \emph{graph coloring} to assign variables to machine registers.
  228. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  229. motivates an elegant recursive algorithm for translating them into
  230. conditional \code{goto} statements.
  231. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  232. variables}. This elicits the need for \emph{dataflow
  233. analysis} in the register allocator.
  234. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  235. \emph{garbage collection}.
  236. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  237. without lexical scoping, similar to functions in the C programming
  238. language~\citep{Kernighan:1988nx}. The reader learns about the
  239. procedure call stack and \emph{calling conventions} and how they interact
  240. with register allocation and garbage collection. The chapter also
  241. describes how to generate efficient tail calls.
  242. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  243. scoping, that is, \emph{lambda} expressions. The reader learns about
  244. \emph{closure conversion}, in which lambdas are translated into a
  245. combination of functions and tuples.
  246. % Chapter about classes and objects?
  247. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  248. point the input languages are statically typed. The reader extends
  249. the statically typed language with an \code{Any} type that serves
  250. as a target for compiling the dynamically typed language.
  251. %% {\if\edition\pythonEd\pythonColor
  252. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  253. %% \emph{classes}.
  254. %% \fi}
  255. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  256. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  257. in which different regions of a program may be static or dynamically
  258. typed. The reader implements runtime support for \emph{proxies} that
  259. allow values to safely move between regions.
  260. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  261. leveraging the \code{Any} type and type casts developed in chapters
  262. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  263. \end{itemize}
  264. There are many language features that we do not include. Our choices
  265. balance the incidental complexity of a feature versus the fundamental
  266. concepts that it exposes. For example, we include tuples and not
  267. records because although they both elicit the study of heap allocation and
  268. garbage collection, records come with more incidental complexity.
  269. Since 2009, drafts of this book have served as the textbook for
  270. sixteen-week compiler courses for upper-level undergraduates and
  271. first-year graduate students at the University of Colorado and Indiana
  272. University.
  273. %
  274. Students come into the course having learned the basics of
  275. programming, data structures and algorithms, and discrete
  276. mathematics.
  277. %
  278. At the beginning of the course, students form groups of two to four
  279. people. The groups complete approximately one chapter every two
  280. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  281. according to the students interests while respecting the dependencies
  282. between chapters shown in
  283. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  284. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  285. implementation of efficient tail calls.
  286. %
  287. The last two weeks of the course involve a final project in which
  288. students design and implement a compiler extension of their choosing.
  289. The last few chapters can be used in support of these projects. Many
  290. chapters include a challenge problem that we assign to the graduate
  291. students.
  292. For compiler courses at universities on the quarter system
  293. (about ten weeks in length), we recommend completing the course
  294. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  295. some scaffolding code to the students for each compiler pass.
  296. %
  297. The course can be adapted to emphasize functional languages by
  298. skipping chapter~\ref{ch:Lwhile} (loops) and including
  299. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  300. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  301. %
  302. %% \python{A course that emphasizes object-oriented languages would
  303. %% include Chapter~\ref{ch:Lobject}.}
  304. This book has been used in compiler courses at California Polytechnic
  305. State University, Portland State University, Rose–Hulman Institute of
  306. Technology, University of Freiburg, University of Massachusetts
  307. Lowell, and the University of Vermont.
  308. \begin{figure}[tp]
  309. \begin{tcolorbox}[colback=white]
  310. {\if\edition\racketEd
  311. \begin{tikzpicture}[baseline=(current bounding box.center)]
  312. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  313. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  314. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  315. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  316. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  317. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  318. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  319. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  320. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  321. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  322. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  323. \path[->] (C1) edge [above] node {} (C2);
  324. \path[->] (C2) edge [above] node {} (C3);
  325. \path[->] (C3) edge [above] node {} (C4);
  326. \path[->] (C4) edge [above] node {} (C5);
  327. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  328. \path[->] (C5) edge [above] node {} (C7);
  329. \path[->] (C6) edge [above] node {} (C7);
  330. \path[->] (C4) edge [above] node {} (C8);
  331. \path[->] (C4) edge [above] node {} (C9);
  332. \path[->] (C7) edge [above] node {} (C10);
  333. \path[->] (C8) edge [above] node {} (C10);
  334. \path[->] (C10) edge [above] node {} (C11);
  335. \end{tikzpicture}
  336. \fi}
  337. {\if\edition\pythonEd\pythonColor
  338. \begin{tikzpicture}[baseline=(current bounding box.center)]
  339. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  340. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  341. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  342. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  343. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  344. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  345. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  346. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  347. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  348. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  349. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  350. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  351. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  352. \path[->] (Prelim) edge [above] node {} (Var);
  353. \path[->] (Var) edge [above] node {} (Reg);
  354. \path[->] (Var) edge [above] node {} (Parse);
  355. \path[->] (Reg) edge [above] node {} (Cond);
  356. \path[->] (Cond) edge [above] node {} (Tuple);
  357. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  358. \path[->] (Cond) edge [above] node {} (Fun);
  359. \path[->] (Tuple) edge [above] node {} (Lam);
  360. \path[->] (Fun) edge [above] node {} (Lam);
  361. \path[->] (Cond) edge [above] node {} (Dyn);
  362. \path[->] (Cond) edge [above] node {} (Loop);
  363. \path[->] (Lam) edge [above] node {} (Gradual);
  364. \path[->] (Dyn) edge [above] node {} (Gradual);
  365. % \path[->] (Dyn) edge [above] node {} (CO);
  366. \path[->] (Gradual) edge [above] node {} (Generic);
  367. \end{tikzpicture}
  368. \fi}
  369. \end{tcolorbox}
  370. \caption{Diagram of chapter dependencies.}
  371. \label{fig:chapter-dependences}
  372. \end{figure}
  373. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  374. the implementation of the compiler and for the input language, so the
  375. reader should be proficient with Racket or Scheme. There are many
  376. excellent resources for learning Scheme and
  377. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  378. %
  379. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  380. both for the implementation of the compiler and for the input language, so the
  381. reader should be proficient with Python. There are many
  382. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  383. %
  384. The support code for this book is in the GitHub repository at
  385. the following location:
  386. \begin{center}\small\texttt
  387. https://github.com/IUCompilerCourse/
  388. \end{center}
  389. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  390. is helpful but not necessary for the reader to have taken a computer
  391. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  392. assembly language that are needed in the compiler.
  393. %
  394. We follow the System V calling
  395. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  396. that we generate works with the runtime system (written in C) when it
  397. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  398. operating systems on Intel hardware.
  399. %
  400. On the Windows operating system, \code{gcc} uses the Microsoft x64
  401. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  402. assembly code that we generate does \emph{not} work with the runtime
  403. system on Windows. One workaround is to use a virtual machine with
  404. Linux as the guest operating system.
  405. \section*{Acknowledgments}
  406. The tradition of compiler construction at Indiana University goes back
  407. to research and courses on programming languages by Daniel Friedman in
  408. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  409. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  410. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  411. the compiler course and continued the development of Chez Scheme.
  412. %
  413. The compiler course evolved to incorporate novel pedagogical ideas
  414. while also including elements of real-world compilers. One of
  415. Friedman's ideas was to split the compiler into many small
  416. passes. Another idea, called ``the game,'' was to test the code
  417. generated by each pass using interpreters.
  418. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  419. developed infrastructure to support this approach and evolved the
  420. course to use even smaller
  421. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  422. design decisions in this book are inspired by the assignment
  423. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  424. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  425. organization of the course made it difficult for students to
  426. understand the rationale for the compiler design. Ghuloum proposed the
  427. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  428. based.
  429. I thank the many students who served as teaching assistants for the
  430. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  431. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  432. garbage collector and x86 interpreter, Michael Vollmer for work on
  433. efficient tail calls, and Michael Vitousek for help with the first
  434. offering of the incremental compiler course at IU.
  435. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  436. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  437. Michael Wollowski for teaching courses based on drafts of this book
  438. and for their feedback. I thank the National Science Foundation for
  439. the grants that helped to support this work: Grant Numbers 1518844,
  440. 1763922, and 1814460.
  441. I thank Ronald Garcia for helping me survive Dybvig's compiler
  442. course in the early 2000s and especially for finding the bug that
  443. sent our garbage collector on a wild goose chase!
  444. \mbox{}\\
  445. \noindent Jeremy G. Siek \\
  446. Bloomington, Indiana
  447. \mainmatter
  448. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  449. \chapter{Preliminaries}
  450. \label{ch:trees-recur}
  451. \setcounter{footnote}{0}
  452. In this chapter we introduce the basic tools needed to implement a
  453. compiler. Programs are typically input by a programmer as text, that
  454. is, a sequence of characters. The program-as-text representation is
  455. called \emph{concrete syntax}. We use concrete syntax to concisely
  456. write down and talk about programs. Inside the compiler, we use
  457. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  458. that efficiently supports the operations that the compiler needs to
  459. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  460. syntax}\index{subject}{abstract syntax
  461. tree}\index{subject}{AST}\index{subject}{program}
  462. The process of translating concrete syntax to abstract syntax is
  463. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  464. chapter~\ref{ch:parsing}}.
  465. \racket{This book does not cover the theory and implementation of parsing.
  466. We refer the readers interested in parsing to the thorough treatment
  467. of parsing by \citet{Aho:2006wb}.}%
  468. %
  469. \racket{A parser is provided in the support code for translating from
  470. concrete to abstract syntax.}%
  471. %
  472. \python{For now we use the \code{parse} function in Python's
  473. \code{ast} module to translate from concrete to abstract syntax.}
  474. ASTs can be represented inside the compiler in many different ways,
  475. depending on the programming language used to write the compiler.
  476. %
  477. \racket{We use Racket's
  478. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  479. feature to represent ASTs (section~\ref{sec:ast}).}
  480. %
  481. \python{We use Python classes and objects to represent ASTs, especially the
  482. classes defined in the standard \code{ast} module for the Python
  483. source language.}
  484. %
  485. We use grammars to define the abstract syntax of programming languages
  486. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  487. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  488. recursive functions to construct and deconstruct ASTs
  489. (section~\ref{sec:recursion}). This chapter provides a brief
  490. introduction to these components.
  491. \racket{\index{subject}{struct}}
  492. \python{\index{subject}{class}\index{subject}{object}}
  493. \section{Abstract Syntax Trees}
  494. \label{sec:ast}
  495. Compilers use abstract syntax trees to represent programs because they
  496. often need to ask questions such as, for a given part of a program,
  497. what kind of language feature is it? What are its subparts? Consider
  498. the program on the left and the diagram of its AST on the
  499. right~\eqref{eq:arith-prog}. This program is an addition operation
  500. that has two subparts, a \racket{read}\python{input} operation and a
  501. negation. The negation has another subpart, the integer constant
  502. \code{8}. By using a tree to represent the program, we can easily
  503. follow the links to go from one part of a program to its subparts.
  504. \begin{center}
  505. \begin{minipage}{0.4\textwidth}
  506. {\if\edition\racketEd
  507. \begin{lstlisting}
  508. (+ (read) (- 8))
  509. \end{lstlisting}
  510. \fi}
  511. {\if\edition\pythonEd\pythonColor
  512. \begin{lstlisting}
  513. input_int() + -8
  514. \end{lstlisting}
  515. \fi}
  516. \end{minipage}
  517. \begin{minipage}{0.4\textwidth}
  518. \begin{equation}
  519. \begin{tikzpicture}
  520. \node[draw] (plus) at (0 , 0) {\key{+}};
  521. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  522. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  523. \node[draw] (8) at (1 , -2) {\key{8}};
  524. \draw[->] (plus) to (read);
  525. \draw[->] (plus) to (minus);
  526. \draw[->] (minus) to (8);
  527. \end{tikzpicture}
  528. \label{eq:arith-prog}
  529. \end{equation}
  530. \end{minipage}
  531. \end{center}
  532. We use the standard terminology for trees to describe ASTs: each
  533. rectangle above is called a \emph{node}. The arrows connect a node to its
  534. \emph{children}, which are also nodes. The top-most node is the
  535. \emph{root}. Every node except for the root has a \emph{parent} (the
  536. node of which it is the child). If a node has no children, it is a
  537. \emph{leaf} node; otherwise it is an \emph{internal} node.
  538. \index{subject}{node}
  539. \index{subject}{children}
  540. \index{subject}{root}
  541. \index{subject}{parent}
  542. \index{subject}{leaf}
  543. \index{subject}{internal node}
  544. %% Recall that an \emph{symbolic expression} (S-expression) is either
  545. %% \begin{enumerate}
  546. %% \item an atom, or
  547. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  548. %% where $e_1$ and $e_2$ are each an S-expression.
  549. %% \end{enumerate}
  550. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  551. %% null value \code{'()}, etc. We can create an S-expression in Racket
  552. %% simply by writing a backquote (called a quasi-quote in Racket)
  553. %% followed by the textual representation of the S-expression. It is
  554. %% quite common to use S-expressions to represent a list, such as $a, b
  555. %% ,c$ in the following way:
  556. %% \begin{lstlisting}
  557. %% `(a . (b . (c . ())))
  558. %% \end{lstlisting}
  559. %% Each element of the list is in the first slot of a pair, and the
  560. %% second slot is either the rest of the list or the null value, to mark
  561. %% the end of the list. Such lists are so common that Racket provides
  562. %% special notation for them that removes the need for the periods
  563. %% and so many parenthesis:
  564. %% \begin{lstlisting}
  565. %% `(a b c)
  566. %% \end{lstlisting}
  567. %% The following expression creates an S-expression that represents AST
  568. %% \eqref{eq:arith-prog}.
  569. %% \begin{lstlisting}
  570. %% `(+ (read) (- 8))
  571. %% \end{lstlisting}
  572. %% When using S-expressions to represent ASTs, the convention is to
  573. %% represent each AST node as a list and to put the operation symbol at
  574. %% the front of the list. The rest of the list contains the children. So
  575. %% in the above case, the root AST node has operation \code{`+} and its
  576. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  577. %% diagram \eqref{eq:arith-prog}.
  578. %% To build larger S-expressions one often needs to splice together
  579. %% several smaller S-expressions. Racket provides the comma operator to
  580. %% splice an S-expression into a larger one. For example, instead of
  581. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  582. %% we could have first created an S-expression for AST
  583. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  584. %% S-expression.
  585. %% \begin{lstlisting}
  586. %% (define ast1.4 `(- 8))
  587. %% (define ast1_1 `(+ (read) ,ast1.4))
  588. %% \end{lstlisting}
  589. %% In general, the Racket expression that follows the comma (splice)
  590. %% can be any expression that produces an S-expression.
  591. {\if\edition\racketEd
  592. We define a Racket \code{struct} for each kind of node. For this
  593. chapter we require just two kinds of nodes: one for integer constants
  594. (aka literals\index{subject}{literals})
  595. and one for primitive operations. The following is the \code{struct}
  596. definition for integer constants.\footnote{All the AST structures are
  597. defined in the file \code{utilities.rkt} in the support code.}
  598. \begin{lstlisting}
  599. (struct Int (value))
  600. \end{lstlisting}
  601. An integer node contains just one thing: the integer value.
  602. We establish the convention that \code{struct} names, such
  603. as \code{Int}, are capitalized.
  604. To create an AST node for the integer $8$, we write \INT{8}.
  605. \begin{lstlisting}
  606. (define eight (Int 8))
  607. \end{lstlisting}
  608. We say that the value created by \INT{8} is an
  609. \emph{instance} of the
  610. \code{Int} structure.
  611. The following is the \code{struct} definition for primitive operations.
  612. \begin{lstlisting}
  613. (struct Prim (op args))
  614. \end{lstlisting}
  615. A primitive operation node includes an operator symbol \code{op} and a
  616. list of child arguments called \code{args}. For example, to create an
  617. AST that negates the number $8$, we write the following.
  618. \begin{lstlisting}
  619. (define neg-eight (Prim '- (list eight)))
  620. \end{lstlisting}
  621. Primitive operations may have zero or more children. The \code{read}
  622. operator has zero:
  623. \begin{lstlisting}
  624. (define rd (Prim 'read '()))
  625. \end{lstlisting}
  626. The addition operator has two children:
  627. \begin{lstlisting}
  628. (define ast1_1 (Prim '+ (list rd neg-eight)))
  629. \end{lstlisting}
  630. We have made a design choice regarding the \code{Prim} structure.
  631. Instead of using one structure for many different operations
  632. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  633. structure for each operation, as follows:
  634. \begin{lstlisting}
  635. (struct Read ())
  636. (struct Add (left right))
  637. (struct Neg (value))
  638. \end{lstlisting}
  639. The reason that we choose to use just one structure is that many parts
  640. of the compiler can use the same code for the different primitive
  641. operators, so we might as well just write that code once by using a
  642. single structure.
  643. %
  644. \fi}
  645. {\if\edition\pythonEd\pythonColor
  646. We use a Python \code{class} for each kind of node.
  647. The following is the class definition for
  648. constants (aka literals\index{subject}{literals})
  649. from the Python \code{ast} module.
  650. \begin{lstlisting}
  651. class Constant:
  652. def __init__(self, value):
  653. self.value = value
  654. \end{lstlisting}
  655. An integer constant node includes just one thing: the integer value.
  656. To create an AST node for the integer $8$, we write \INT{8}.
  657. \begin{lstlisting}
  658. eight = Constant(8)
  659. \end{lstlisting}
  660. We say that the value created by \INT{8} is an
  661. \emph{instance} of the \code{Constant} class.
  662. The following is the class definition for unary operators.
  663. \begin{lstlisting}
  664. class UnaryOp:
  665. def __init__(self, op, operand):
  666. self.op = op
  667. self.operand = operand
  668. \end{lstlisting}
  669. The specific operation is specified by the \code{op} parameter. For
  670. example, the class \code{USub} is for unary subtraction.
  671. (More unary operators are introduced in later chapters.) To create an AST that
  672. negates the number $8$, we write the following.
  673. \begin{lstlisting}
  674. neg_eight = UnaryOp(USub(), eight)
  675. \end{lstlisting}
  676. The call to the \code{input\_int} function is represented by the
  677. \code{Call} and \code{Name} classes.
  678. \begin{lstlisting}
  679. class Call:
  680. def __init__(self, func, args):
  681. self.func = func
  682. self.args = args
  683. class Name:
  684. def __init__(self, id):
  685. self.id = id
  686. \end{lstlisting}
  687. To create an AST node that calls \code{input\_int}, we write
  688. \begin{lstlisting}
  689. read = Call(Name('input_int'), [])
  690. \end{lstlisting}
  691. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  692. the \code{BinOp} class for binary operators.
  693. \begin{lstlisting}
  694. class BinOp:
  695. def __init__(self, left, op, right):
  696. self.op = op
  697. self.left = left
  698. self.right = right
  699. \end{lstlisting}
  700. Similar to \code{UnaryOp}, the specific operation is specified by the
  701. \code{op} parameter, which for now is just an instance of the
  702. \code{Add} class. So to create the AST
  703. node that adds negative eight to some user input, we write the following.
  704. \begin{lstlisting}
  705. ast1_1 = BinOp(read, Add(), neg_eight)
  706. \end{lstlisting}
  707. \fi}
  708. To compile a program such as \eqref{eq:arith-prog}, we need to know
  709. that the operation associated with the root node is addition and we
  710. need to be able to access its two
  711. children. \racket{Racket}\python{Python} provides pattern matching to
  712. support these kinds of queries, as we see in
  713. section~\ref{sec:pattern-matching}.
  714. We often write down the concrete syntax of a program even when we
  715. actually have in mind the AST, because the concrete syntax is more
  716. concise. We recommend that you always think of programs as abstract
  717. syntax trees.
  718. \section{Grammars}
  719. \label{sec:grammar}
  720. \index{subject}{integer}
  721. %\index{subject}{constant}
  722. A programming language can be thought of as a \emph{set} of programs.
  723. The set is infinite (that is, one can always create larger programs),
  724. so one cannot simply describe a language by listing all the
  725. programs in the language. Instead we write down a set of rules, a
  726. \emph{context-free grammar}, for building programs. Grammars are often used to
  727. define the concrete syntax of a language, but they can also be used to
  728. describe the abstract syntax. We write our rules in a variant of
  729. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  730. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  731. we describe a small language, named \LangInt{}, that consists of
  732. integers and arithmetic operations.\index{subject}{grammar}
  733. \index{subject}{context-free grammar}
  734. The first grammar rule for the abstract syntax of \LangInt{} says that an
  735. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  736. \begin{equation}
  737. \Exp ::= \INT{\Int} \label{eq:arith-int}
  738. \end{equation}
  739. %
  740. Each rule has a left-hand side and a right-hand side.
  741. If you have an AST node that matches the
  742. right-hand side, then you can categorize it according to the
  743. left-hand side.
  744. %
  745. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  746. are \emph{terminal} symbols and must literally appear in the program for the
  747. rule to be applicable.\index{subject}{terminal}
  748. %
  749. Our grammars do not mention \emph{white space}, that is, delimiter
  750. characters like spaces, tabs, and new lines. White space may be
  751. inserted between symbols for disambiguation and to improve
  752. readability. \index{subject}{white space}
  753. %
  754. A name such as $\Exp$ that is defined by the grammar rules is a
  755. \emph{nonterminal}. \index{subject}{nonterminal}
  756. %
  757. The name $\Int$ is also a nonterminal, but instead of defining it with
  758. a grammar rule, we define it with the following explanation. An
  759. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  760. $-$ (for negative integers), such that the sequence of decimals
  761. %
  762. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  763. enables the representation of integers using 63 bits, which simplifies
  764. several aspects of compilation.
  765. %
  766. Thus, these integers correspond to the Racket \texttt{fixnum}
  767. datatype on a 64-bit machine.}
  768. %
  769. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  770. enables the representation of integers using 64 bits, which simplifies
  771. several aspects of compilation. In contrast, integers in Python have
  772. unlimited precision, but the techniques needed to handle unlimited
  773. precision fall outside the scope of this book.}
  774. The second grammar rule is the \READOP{} operation, which receives an
  775. input integer from the user of the program.
  776. \begin{equation}
  777. \Exp ::= \READ{} \label{eq:arith-read}
  778. \end{equation}
  779. The third rule categorizes the negation of an $\Exp$ node as an
  780. $\Exp$.
  781. \begin{equation}
  782. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  783. \end{equation}
  784. We can apply these rules to categorize the ASTs that are in the
  785. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  786. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  787. following AST is an $\Exp$.
  788. \begin{center}
  789. \begin{minipage}{0.5\textwidth}
  790. \NEG{\INT{\code{8}}}
  791. \end{minipage}
  792. \begin{minipage}{0.25\textwidth}
  793. \begin{equation}
  794. \begin{tikzpicture}
  795. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  796. \node[draw, circle] (8) at (0, -1.2) {$8$};
  797. \draw[->] (minus) to (8);
  798. \end{tikzpicture}
  799. \label{eq:arith-neg8}
  800. \end{equation}
  801. \end{minipage}
  802. \end{center}
  803. The next two grammar rules are for addition and subtraction expressions:
  804. \begin{align}
  805. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  806. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  807. \end{align}
  808. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  809. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  810. \eqref{eq:arith-read}, and we have already categorized
  811. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  812. to show that
  813. \[
  814. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  815. \]
  816. is an $\Exp$ in the \LangInt{} language.
  817. If you have an AST for which these rules do not apply, then the
  818. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  819. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  820. because there is no rule for the \key{*} operator. Whenever we
  821. define a language with a grammar, the language includes only those
  822. programs that are justified by the grammar rules.
  823. {\if\edition\pythonEd\pythonColor
  824. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  825. There is a statement for printing the value of an expression
  826. \[
  827. \Stmt{} ::= \PRINT{\Exp}
  828. \]
  829. and a statement that evaluates an expression but ignores the result.
  830. \[
  831. \Stmt{} ::= \EXPR{\Exp}
  832. \]
  833. \fi}
  834. {\if\edition\racketEd
  835. The last grammar rule for \LangInt{} states that there is a
  836. \code{Program} node to mark the top of the whole program:
  837. \[
  838. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  839. \]
  840. The \code{Program} structure is defined as follows:
  841. \begin{lstlisting}
  842. (struct Program (info body))
  843. \end{lstlisting}
  844. where \code{body} is an expression. In further chapters, the \code{info}
  845. part is used to store auxiliary information, but for now it is
  846. just the empty list.
  847. \fi}
  848. {\if\edition\pythonEd\pythonColor
  849. The last grammar rule for \LangInt{} states that there is a
  850. \code{Module} node to mark the top of the whole program:
  851. \[
  852. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  853. \]
  854. The asterisk $*$ indicates a list of the preceding grammar item, in
  855. this case a list of statements.
  856. %
  857. The \code{Module} class is defined as follows:
  858. \begin{lstlisting}
  859. class Module:
  860. def __init__(self, body):
  861. self.body = body
  862. \end{lstlisting}
  863. where \code{body} is a list of statements.
  864. \fi}
  865. It is common to have many grammar rules with the same left-hand side
  866. but different right-hand sides, such as the rules for $\Exp$ in the
  867. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  868. combine several right-hand sides into a single rule.
  869. The concrete syntax for \LangInt{} is shown in
  870. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  871. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  872. %
  873. \racket{The \code{read-program} function provided in
  874. \code{utilities.rkt} of the support code reads a program from a file
  875. (the sequence of characters in the concrete syntax of Racket) and
  876. parses it into an abstract syntax tree. Refer to the description of
  877. \code{read-program} in appendix~\ref{appendix:utilities} for more
  878. details.}
  879. %
  880. \python{We recommend using the \code{parse} function in Python's
  881. \code{ast} module to convert the concrete syntax into an abstract
  882. syntax tree.}
  883. \newcommand{\LintGrammarRacket}{
  884. \begin{array}{rcl}
  885. \Type &::=& \key{Integer} \\
  886. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  887. \MID \CSUB{\Exp}{\Exp}
  888. \end{array}
  889. }
  890. \newcommand{\LintASTRacket}{
  891. \begin{array}{rcl}
  892. \Type &::=& \key{Integer} \\
  893. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  894. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  895. \end{array}
  896. }
  897. \newcommand{\LintGrammarPython}{
  898. \begin{array}{rcl}
  899. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  900. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  901. \end{array}
  902. }
  903. \newcommand{\LintASTPython}{
  904. \begin{array}{rcl}
  905. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  906. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  907. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  908. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  909. \end{array}
  910. }
  911. \begin{figure}[tp]
  912. \begin{tcolorbox}[colback=white]
  913. {\if\edition\racketEd
  914. \[
  915. \begin{array}{l}
  916. \LintGrammarRacket \\
  917. \begin{array}{rcl}
  918. \LangInt{} &::=& \Exp
  919. \end{array}
  920. \end{array}
  921. \]
  922. \fi}
  923. {\if\edition\pythonEd\pythonColor
  924. \[
  925. \begin{array}{l}
  926. \LintGrammarPython \\
  927. \begin{array}{rcl}
  928. \LangInt{} &::=& \Stmt^{*}
  929. \end{array}
  930. \end{array}
  931. \]
  932. \fi}
  933. \end{tcolorbox}
  934. \caption{The concrete syntax of \LangInt{}.}
  935. \label{fig:r0-concrete-syntax}
  936. \end{figure}
  937. \begin{figure}[tp]
  938. \begin{tcolorbox}[colback=white]
  939. {\if\edition\racketEd
  940. \[
  941. \begin{array}{l}
  942. \LintASTRacket{} \\
  943. \begin{array}{rcl}
  944. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  945. \end{array}
  946. \end{array}
  947. \]
  948. \fi}
  949. {\if\edition\pythonEd\pythonColor
  950. \[
  951. \begin{array}{l}
  952. \LintASTPython\\
  953. \begin{array}{rcl}
  954. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  955. \end{array}
  956. \end{array}
  957. \]
  958. \fi}
  959. \end{tcolorbox}
  960. \python{
  961. \index{subject}{Constant@\texttt{Constant}}
  962. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  963. \index{subject}{USub@\texttt{USub}}
  964. \index{subject}{inputint@\texttt{input\_int}}
  965. \index{subject}{Call@\texttt{Call}}
  966. \index{subject}{Name@\texttt{Name}}
  967. \index{subject}{BinOp@\texttt{BinOp}}
  968. \index{subject}{Add@\texttt{Add}}
  969. \index{subject}{Sub@\texttt{Sub}}
  970. \index{subject}{print@\texttt{print}}
  971. \index{subject}{Expr@\texttt{Expr}}
  972. \index{subject}{Module@\texttt{Module}}
  973. }
  974. \caption{The abstract syntax of \LangInt{}.}
  975. \label{fig:r0-syntax}
  976. \end{figure}
  977. \section{Pattern Matching}
  978. \label{sec:pattern-matching}
  979. As mentioned in section~\ref{sec:ast}, compilers often need to access
  980. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  981. provides the \texttt{match} feature to access the parts of a value.
  982. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  983. \begin{center}
  984. \begin{minipage}{1.0\textwidth}
  985. {\if\edition\racketEd
  986. \begin{lstlisting}
  987. (match ast1_1
  988. [(Prim op (list child1 child2))
  989. (print op)])
  990. \end{lstlisting}
  991. \fi}
  992. {\if\edition\pythonEd\pythonColor
  993. \begin{lstlisting}
  994. match ast1_1:
  995. case BinOp(child1, op, child2):
  996. print(op)
  997. \end{lstlisting}
  998. \fi}
  999. \end{minipage}
  1000. \end{center}
  1001. {\if\edition\racketEd
  1002. %
  1003. In this example, the \texttt{match} form checks whether the AST
  1004. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1005. three pattern variables \texttt{op}, \texttt{child1}, and
  1006. \texttt{child2}. In general, a match clause consists of a
  1007. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1008. recursively defined to be a pattern variable, a structure name
  1009. followed by a pattern for each of the structure's arguments, or an
  1010. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1011. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1012. and chapter 9 of The Racket
  1013. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1014. for complete descriptions of \code{match}.)
  1015. %
  1016. The body of a match clause may contain arbitrary Racket code. The
  1017. pattern variables can be used in the scope of the body, such as
  1018. \code{op} in \code{(print op)}.
  1019. %
  1020. \fi}
  1021. %
  1022. %
  1023. {\if\edition\pythonEd\pythonColor
  1024. %
  1025. In the example above, the \texttt{match} form checks whether the AST
  1026. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1027. three pattern variables (\texttt{child1}, \texttt{op}, and
  1028. \texttt{child2}). In general, each \code{case} consists of a
  1029. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1030. recursively defined to be one of the following: a pattern variable, a
  1031. class name followed by a pattern for each of its constructor's
  1032. arguments, or other literals\index{subject}{literals} such as strings
  1033. or lists.
  1034. %
  1035. The body of each \code{case} may contain arbitrary Python code. The
  1036. pattern variables can be used in the body, such as \code{op} in
  1037. \code{print(op)}.
  1038. %
  1039. \fi}
  1040. A \code{match} form may contain several clauses, as in the following
  1041. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1042. the AST. The \code{match} proceeds through the clauses in order,
  1043. checking whether the pattern can match the input AST. The body of the
  1044. first clause that matches is executed. The output of \code{leaf} for
  1045. several ASTs is shown on the right side of the following:
  1046. \begin{center}
  1047. \begin{minipage}{0.6\textwidth}
  1048. {\if\edition\racketEd
  1049. \begin{lstlisting}
  1050. (define (leaf arith)
  1051. (match arith
  1052. [(Int n) #t]
  1053. [(Prim 'read '()) #t]
  1054. [(Prim '- (list e1)) #f]
  1055. [(Prim '+ (list e1 e2)) #f]
  1056. [(Prim '- (list e1 e2)) #f]))
  1057. (leaf (Prim 'read '()))
  1058. (leaf (Prim '- (list (Int 8))))
  1059. (leaf (Int 8))
  1060. \end{lstlisting}
  1061. \fi}
  1062. {\if\edition\pythonEd\pythonColor
  1063. \begin{lstlisting}
  1064. def leaf(arith):
  1065. match arith:
  1066. case Constant(n):
  1067. return True
  1068. case Call(Name('input_int'), []):
  1069. return True
  1070. case UnaryOp(USub(), e1):
  1071. return False
  1072. case BinOp(e1, Add(), e2):
  1073. return False
  1074. case BinOp(e1, Sub(), e2):
  1075. return False
  1076. print(leaf(Call(Name('input_int'), [])))
  1077. print(leaf(UnaryOp(USub(), eight)))
  1078. print(leaf(Constant(8)))
  1079. \end{lstlisting}
  1080. \fi}
  1081. \end{minipage}
  1082. \vrule
  1083. \begin{minipage}{0.25\textwidth}
  1084. {\if\edition\racketEd
  1085. \begin{lstlisting}
  1086. #t
  1087. #f
  1088. #t
  1089. \end{lstlisting}
  1090. \fi}
  1091. {\if\edition\pythonEd\pythonColor
  1092. \begin{lstlisting}
  1093. True
  1094. False
  1095. True
  1096. \end{lstlisting}
  1097. \fi}
  1098. \end{minipage}
  1099. \index{subject}{True@\TRUE{}}
  1100. \index{subject}{False@\FALSE{}}
  1101. \end{center}
  1102. When constructing a \code{match} expression, we refer to the grammar
  1103. definition to identify which nonterminal we are expecting to match
  1104. against, and then we make sure that (1) we have one
  1105. \racket{clause}\python{case} for each alternative of that nonterminal
  1106. and (2) the pattern in each \racket{clause}\python{case}
  1107. corresponds to the corresponding right-hand side of a grammar
  1108. rule. For the \code{match} in the \code{leaf} function, we refer to
  1109. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1110. nonterminal has five alternatives, so the \code{match} has five
  1111. \racket{clauses}\python{cases}. The pattern in each
  1112. \racket{clause}\python{case} corresponds to the right-hand side of a
  1113. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1114. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1115. translating from grammars to patterns, replace nonterminals such as
  1116. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1117. \code{e2}).
  1118. \section{Recursive Functions}
  1119. \label{sec:recursion}
  1120. \index{subject}{recursive function}
  1121. Programs are inherently recursive. For example, an expression is often
  1122. made of smaller expressions. Thus, the natural way to process an
  1123. entire program is to use a recursive function. As a first example of
  1124. such a recursive function, we define the function \code{is\_exp} as
  1125. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1126. value and determine whether or not it is an expression in \LangInt{}.
  1127. %
  1128. We say that a function is defined by \emph{structural recursion} if
  1129. it is defined using a sequence of match \racket{clauses}\python{cases}
  1130. that correspond to a grammar and the body of each
  1131. \racket{clause}\python{case} makes a recursive call on each child
  1132. node.\footnote{This principle of structuring code according to the
  1133. data definition is advocated in the book \emph{How to Design
  1134. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1135. second function, named \code{is\_stmt}, that recognizes whether a value
  1136. is a \LangInt{} statement.} \python{Finally, }
  1137. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1138. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1139. In general, we can write one recursive function to handle each
  1140. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1141. two examples at the bottom of the figure, the first is in
  1142. \LangInt{} and the second is not.
  1143. \begin{figure}[tp]
  1144. \begin{tcolorbox}[colback=white]
  1145. {\if\edition\racketEd
  1146. \begin{lstlisting}
  1147. (define (is_exp ast)
  1148. (match ast
  1149. [(Int n) #t]
  1150. [(Prim 'read '()) #t]
  1151. [(Prim '- (list e)) (is_exp e)]
  1152. [(Prim '+ (list e1 e2))
  1153. (and (is_exp e1) (is_exp e2))]
  1154. [(Prim '- (list e1 e2))
  1155. (and (is_exp e1) (is_exp e2))]
  1156. [else #f]))
  1157. (define (is_Lint ast)
  1158. (match ast
  1159. [(Program '() e) (is_exp e)]
  1160. [else #f]))
  1161. (is_Lint (Program '() ast1_1)
  1162. (is_Lint (Program '()
  1163. (Prim '* (list (Prim 'read '())
  1164. (Prim '+ (list (Int 8)))))))
  1165. \end{lstlisting}
  1166. \fi}
  1167. {\if\edition\pythonEd\pythonColor
  1168. \begin{lstlisting}
  1169. def is_exp(e):
  1170. match e:
  1171. case Constant(n):
  1172. return True
  1173. case Call(Name('input_int'), []):
  1174. return True
  1175. case UnaryOp(USub(), e1):
  1176. return is_exp(e1)
  1177. case BinOp(e1, Add(), e2):
  1178. return is_exp(e1) and is_exp(e2)
  1179. case BinOp(e1, Sub(), e2):
  1180. return is_exp(e1) and is_exp(e2)
  1181. case _:
  1182. return False
  1183. def is_stmt(s):
  1184. match s:
  1185. case Expr(Call(Name('print'), [e])):
  1186. return is_exp(e)
  1187. case Expr(e):
  1188. return is_exp(e)
  1189. case _:
  1190. return False
  1191. def is_Lint(p):
  1192. match p:
  1193. case Module(body):
  1194. return all([is_stmt(s) for s in body])
  1195. case _:
  1196. return False
  1197. print(is_Lint(Module([Expr(ast1_1)])))
  1198. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1199. UnaryOp(Add(), Constant(8))))])))
  1200. \end{lstlisting}
  1201. \fi}
  1202. \end{tcolorbox}
  1203. \caption{Example of recursive functions for \LangInt{}. These functions
  1204. recognize whether an AST is in \LangInt{}.}
  1205. \label{fig:exp-predicate}
  1206. \end{figure}
  1207. %% You may be tempted to merge the two functions into one, like this:
  1208. %% \begin{center}
  1209. %% \begin{minipage}{0.5\textwidth}
  1210. %% \begin{lstlisting}
  1211. %% (define (Lint ast)
  1212. %% (match ast
  1213. %% [(Int n) #t]
  1214. %% [(Prim 'read '()) #t]
  1215. %% [(Prim '- (list e)) (Lint e)]
  1216. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1217. %% [(Program '() e) (Lint e)]
  1218. %% [else #f]))
  1219. %% \end{lstlisting}
  1220. %% \end{minipage}
  1221. %% \end{center}
  1222. %% %
  1223. %% Sometimes such a trick will save a few lines of code, especially when
  1224. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1225. %% \emph{not} recommended because it can get you into trouble.
  1226. %% %
  1227. %% For example, the above function is subtly wrong:
  1228. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1229. %% returns true when it should return false.
  1230. \section{Interpreters}
  1231. \label{sec:interp_Lint}
  1232. \index{subject}{interpreter}
  1233. The behavior of a program is defined by the specification of the
  1234. programming language.
  1235. %
  1236. \racket{For example, the Scheme language is defined in the report by
  1237. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1238. reference manual~\citep{plt-tr}.}
  1239. %
  1240. \python{For example, the Python language is defined in the Python
  1241. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1242. %
  1243. In this book we use interpreters to specify each language that we
  1244. consider. An interpreter that is designated as the definition of a
  1245. language is called a \emph{definitional
  1246. interpreter}~\citep{reynolds72:_def_interp}.
  1247. \index{subject}{definitional interpreter} We warm up by creating a
  1248. definitional interpreter for the \LangInt{} language. This interpreter
  1249. serves as a second example of structural recursion. The definition of the
  1250. \code{interp\_Lint} function is shown in
  1251. figure~\ref{fig:interp_Lint}.
  1252. %
  1253. \racket{The body of the function is a match on the input program
  1254. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1255. which in turn has one match clause per grammar rule for \LangInt{}
  1256. expressions.}
  1257. %
  1258. \python{The body of the function matches on the \code{Module} AST node
  1259. and then invokes \code{interp\_stmt} on each statement in the
  1260. module. The \code{interp\_stmt} function includes a case for each
  1261. grammar rule of the \Stmt{} nonterminal, and it calls
  1262. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1263. function includes a case for each grammar rule of the \Exp{}
  1264. nonterminal. We use several auxiliary functions such as \code{add64}
  1265. and \code{input\_int} that are defined in the support code for this book.}
  1266. \begin{figure}[tp]
  1267. \begin{tcolorbox}[colback=white]
  1268. {\if\edition\racketEd
  1269. \begin{lstlisting}
  1270. (define (interp_exp e)
  1271. (match e
  1272. [(Int n) n]
  1273. [(Prim 'read '())
  1274. (define r (read))
  1275. (cond [(fixnum? r) r]
  1276. [else (error 'interp_exp "read expected an integer" r)])]
  1277. [(Prim '- (list e))
  1278. (define v (interp_exp e))
  1279. (fx- 0 v)]
  1280. [(Prim '+ (list e1 e2))
  1281. (define v1 (interp_exp e1))
  1282. (define v2 (interp_exp e2))
  1283. (fx+ v1 v2)]
  1284. [(Prim '- (list e1 e2))
  1285. (define v1 (interp_exp e1))
  1286. (define v2 (interp_exp e2))
  1287. (fx- v1 v2)]))
  1288. (define (interp_Lint p)
  1289. (match p
  1290. [(Program '() e) (interp_exp e)]))
  1291. \end{lstlisting}
  1292. \fi}
  1293. {\if\edition\pythonEd\pythonColor
  1294. \begin{lstlisting}
  1295. def interp_exp(e):
  1296. match e:
  1297. case BinOp(left, Add(), right):
  1298. l = interp_exp(left); r = interp_exp(right)
  1299. return add64(l, r)
  1300. case BinOp(left, Sub(), right):
  1301. l = interp_exp(left); r = interp_exp(right)
  1302. return sub64(l, r)
  1303. case UnaryOp(USub(), v):
  1304. return neg64(interp_exp(v))
  1305. case Constant(value):
  1306. return value
  1307. case Call(Name('input_int'), []):
  1308. return input_int()
  1309. def interp_stmt(s):
  1310. match s:
  1311. case Expr(Call(Name('print'), [arg])):
  1312. print(interp_exp(arg))
  1313. case Expr(value):
  1314. interp_exp(value)
  1315. def interp_Lint(p):
  1316. match p:
  1317. case Module(body):
  1318. for s in body:
  1319. interp_stmt(s)
  1320. \end{lstlisting}
  1321. \fi}
  1322. \end{tcolorbox}
  1323. \caption{Interpreter for the \LangInt{} language.}
  1324. \label{fig:interp_Lint}
  1325. \end{figure}
  1326. Let us consider the result of interpreting a few \LangInt{} programs. The
  1327. following program adds two integers:
  1328. {\if\edition\racketEd
  1329. \begin{lstlisting}
  1330. (+ 10 32)
  1331. \end{lstlisting}
  1332. \fi}
  1333. {\if\edition\pythonEd\pythonColor
  1334. \begin{lstlisting}
  1335. print(10 + 32)
  1336. \end{lstlisting}
  1337. \fi}
  1338. %
  1339. \noindent The result is \key{42}, the answer to life, the universe,
  1340. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1341. the Galaxy} by Douglas Adams.}
  1342. %
  1343. We wrote this program in concrete syntax, whereas the parsed
  1344. abstract syntax is
  1345. {\if\edition\racketEd
  1346. \begin{lstlisting}
  1347. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1348. \end{lstlisting}
  1349. \fi}
  1350. {\if\edition\pythonEd\pythonColor
  1351. \begin{lstlisting}
  1352. Module([Expr(Call(Name('print'),
  1353. [BinOp(Constant(10), Add(), Constant(32))]))])
  1354. \end{lstlisting}
  1355. \fi}
  1356. The following program demonstrates that expressions may be nested within
  1357. each other, in this case nesting several additions and negations.
  1358. {\if\edition\racketEd
  1359. \begin{lstlisting}
  1360. (+ 10 (- (+ 12 20)))
  1361. \end{lstlisting}
  1362. \fi}
  1363. {\if\edition\pythonEd\pythonColor
  1364. \begin{lstlisting}
  1365. print(10 + -(12 + 20))
  1366. \end{lstlisting}
  1367. \fi}
  1368. %
  1369. \noindent What is the result of this program?
  1370. {\if\edition\racketEd
  1371. As mentioned previously, the \LangInt{} language does not support
  1372. arbitrarily large integers but only $63$-bit integers, so we
  1373. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1374. in Racket.
  1375. Suppose that
  1376. \[
  1377. n = 999999999999999999
  1378. \]
  1379. which indeed fits in $63$ bits. What happens when we run the
  1380. following program in our interpreter?
  1381. \begin{lstlisting}
  1382. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1383. \end{lstlisting}
  1384. It produces the following error:
  1385. \begin{lstlisting}
  1386. fx+: result is not a fixnum
  1387. \end{lstlisting}
  1388. We establish the convention that if running the definitional
  1389. interpreter on a program produces an error, then the meaning of that
  1390. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1391. error is a \code{trapped-error}. A compiler for the language is under
  1392. no obligation regarding programs with unspecified behavior; it does
  1393. not have to produce an executable, and if it does, that executable can
  1394. do anything. On the other hand, if the error is a
  1395. \code{trapped-error}, then the compiler must produce an executable and
  1396. it is required to report that an error occurred. To signal an error,
  1397. exit with a return code of \code{255}. The interpreters in chapters
  1398. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1399. \code{trapped-error}.
  1400. \fi}
  1401. % TODO: how to deal with too-large integers in the Python interpreter?
  1402. %% This convention applies to the languages defined in this
  1403. %% book, as a way to simplify the student's task of implementing them,
  1404. %% but this convention is not applicable to all programming languages.
  1405. %%
  1406. The last feature of the \LangInt{} language, the \READOP{} operation,
  1407. prompts the user of the program for an integer. Recall that program
  1408. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1409. \code{8}. So, if we run {\if\edition\racketEd
  1410. \begin{lstlisting}
  1411. (interp_Lint (Program '() ast1_1))
  1412. \end{lstlisting}
  1413. \fi}
  1414. {\if\edition\pythonEd\pythonColor
  1415. \begin{lstlisting}
  1416. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1417. \end{lstlisting}
  1418. \fi}
  1419. \noindent and if the input is \code{50}, the result is \code{42}.
  1420. We include the \READOP{} operation in \LangInt{} so that a clever
  1421. student cannot implement a compiler for \LangInt{} that simply runs
  1422. the interpreter during compilation to obtain the output and then
  1423. generates the trivial code to produce the output.\footnote{Yes, a
  1424. clever student did this in the first instance of this course!}
  1425. The job of a compiler is to translate a program in one language into a
  1426. program in another language so that the output program behaves the
  1427. same way as the input program. This idea is depicted in the
  1428. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1429. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1430. Given a compiler that translates from language $\mathcal{L}_1$ to
  1431. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1432. compiler must translate it into some program $P_2$ such that
  1433. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1434. same input $i$ yields the same output $o$.
  1435. \begin{equation} \label{eq:compile-correct}
  1436. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1437. \node (p1) at (0, 0) {$P_1$};
  1438. \node (p2) at (3, 0) {$P_2$};
  1439. \node (o) at (3, -2.5) {$o$};
  1440. \path[->] (p1) edge [above] node {compile} (p2);
  1441. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1442. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1443. \end{tikzpicture}
  1444. \end{equation}
  1445. \python{We establish the convention that if running the definitional
  1446. interpreter on a program produces an error, then the meaning of that
  1447. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1448. unless the exception raised is a \code{TrappedError}. A compiler for
  1449. the language is under no obligation regarding programs with
  1450. unspecified behavior; it does not have to produce an executable, and
  1451. if it does, that executable can do anything. On the other hand, if
  1452. the error is a \code{TrappedError}, then the compiler must produce
  1453. an executable and it is required to report that an error
  1454. occurred. To signal an error, exit with a return code of \code{255}.
  1455. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1456. section \ref{sec:arrays} use \code{TrappedError}.}
  1457. In the next section we see our first example of a compiler.
  1458. \section{Example Compiler: A Partial Evaluator}
  1459. \label{sec:partial-evaluation}
  1460. In this section we consider a compiler that translates \LangInt{}
  1461. programs into \LangInt{} programs that may be more efficient. The
  1462. compiler eagerly computes the parts of the program that do not depend
  1463. on any inputs, a process known as \emph{partial
  1464. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1465. For example, given the following program
  1466. {\if\edition\racketEd
  1467. \begin{lstlisting}
  1468. (+ (read) (- (+ 5 3)))
  1469. \end{lstlisting}
  1470. \fi}
  1471. {\if\edition\pythonEd\pythonColor
  1472. \begin{lstlisting}
  1473. print(input_int() + -(5 + 3) )
  1474. \end{lstlisting}
  1475. \fi}
  1476. \noindent our compiler translates it into the program
  1477. {\if\edition\racketEd
  1478. \begin{lstlisting}
  1479. (+ (read) -8)
  1480. \end{lstlisting}
  1481. \fi}
  1482. {\if\edition\pythonEd\pythonColor
  1483. \begin{lstlisting}
  1484. print(input_int() + -8)
  1485. \end{lstlisting}
  1486. \fi}
  1487. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1488. evaluator for the \LangInt{} language. The output of the partial evaluator
  1489. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1490. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1491. whereas the code for partially evaluating the negation and addition
  1492. operations is factored into three auxiliary functions:
  1493. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1494. functions is the output of partially evaluating the children.
  1495. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1496. arguments are integers and if they are, perform the appropriate
  1497. arithmetic. Otherwise, they create an AST node for the arithmetic
  1498. operation.
  1499. \begin{figure}[tp]
  1500. \begin{tcolorbox}[colback=white]
  1501. {\if\edition\racketEd
  1502. \begin{lstlisting}
  1503. (define (pe_neg r)
  1504. (match r
  1505. [(Int n) (Int (fx- 0 n))]
  1506. [else (Prim '- (list r))]))
  1507. (define (pe_add r1 r2)
  1508. (match* (r1 r2)
  1509. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1510. [(_ _) (Prim '+ (list r1 r2))]))
  1511. (define (pe_sub r1 r2)
  1512. (match* (r1 r2)
  1513. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1514. [(_ _) (Prim '- (list r1 r2))]))
  1515. (define (pe_exp e)
  1516. (match e
  1517. [(Int n) (Int n)]
  1518. [(Prim 'read '()) (Prim 'read '())]
  1519. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1520. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1521. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1522. (define (pe_Lint p)
  1523. (match p
  1524. [(Program '() e) (Program '() (pe_exp e))]))
  1525. \end{lstlisting}
  1526. \fi}
  1527. {\if\edition\pythonEd\pythonColor
  1528. \begin{lstlisting}
  1529. def pe_neg(r):
  1530. match r:
  1531. case Constant(n):
  1532. return Constant(neg64(n))
  1533. case _:
  1534. return UnaryOp(USub(), r)
  1535. def pe_add(r1, r2):
  1536. match (r1, r2):
  1537. case (Constant(n1), Constant(n2)):
  1538. return Constant(add64(n1, n2))
  1539. case _:
  1540. return BinOp(r1, Add(), r2)
  1541. def pe_sub(r1, r2):
  1542. match (r1, r2):
  1543. case (Constant(n1), Constant(n2)):
  1544. return Constant(sub64(n1, n2))
  1545. case _:
  1546. return BinOp(r1, Sub(), r2)
  1547. def pe_exp(e):
  1548. match e:
  1549. case BinOp(left, Add(), right):
  1550. return pe_add(pe_exp(left), pe_exp(right))
  1551. case BinOp(left, Sub(), right):
  1552. return pe_sub(pe_exp(left), pe_exp(right))
  1553. case UnaryOp(USub(), v):
  1554. return pe_neg(pe_exp(v))
  1555. case Constant(value):
  1556. return e
  1557. case Call(Name('input_int'), []):
  1558. return e
  1559. def pe_stmt(s):
  1560. match s:
  1561. case Expr(Call(Name('print'), [arg])):
  1562. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1563. case Expr(value):
  1564. return Expr(pe_exp(value))
  1565. def pe_P_int(p):
  1566. match p:
  1567. case Module(body):
  1568. new_body = [pe_stmt(s) for s in body]
  1569. return Module(new_body)
  1570. \end{lstlisting}
  1571. \fi}
  1572. \end{tcolorbox}
  1573. \caption{A partial evaluator for \LangInt{}.}
  1574. \label{fig:pe-arith}
  1575. \end{figure}
  1576. To gain some confidence that the partial evaluator is correct, we can
  1577. test whether it produces programs that produce the same result as the
  1578. input programs. That is, we can test whether it satisfies the diagram
  1579. of \eqref{eq:compile-correct}.
  1580. %
  1581. {\if\edition\racketEd
  1582. The following code runs the partial evaluator on several examples and
  1583. tests the output program. The \texttt{parse-program} and
  1584. \texttt{assert} functions are defined in
  1585. appendix~\ref{appendix:utilities}.\\
  1586. \begin{minipage}{1.0\textwidth}
  1587. \begin{lstlisting}
  1588. (define (test_pe p)
  1589. (assert "testing pe_Lint"
  1590. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1591. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1592. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1593. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1594. \end{lstlisting}
  1595. \end{minipage}
  1596. \fi}
  1597. % TODO: python version of testing the PE
  1598. \begin{exercise}\normalfont\normalsize
  1599. Create three programs in the \LangInt{} language and test whether
  1600. partially evaluating them with \code{pe\_Lint} and then
  1601. interpreting them with \code{interp\_Lint} gives the same result
  1602. as directly interpreting them with \code{interp\_Lint}.
  1603. \end{exercise}
  1604. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1605. \chapter{Integers and Variables}
  1606. \label{ch:Lvar}
  1607. \setcounter{footnote}{0}
  1608. This chapter covers compiling a subset of
  1609. \racket{Racket}\python{Python} to x86-64 assembly
  1610. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1611. integer arithmetic and local variables. We often refer to x86-64
  1612. simply as x86. The chapter first describes the \LangVar{} language
  1613. (section~\ref{sec:s0}) and then introduces x86 assembly
  1614. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1615. discuss only the instructions needed for compiling \LangVar{}. We
  1616. introduce more x86 instructions in subsequent chapters. After
  1617. introducing \LangVar{} and x86, we reflect on their differences and
  1618. create a plan to break down the translation from \LangVar{} to x86
  1619. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1620. the chapter gives detailed hints regarding each step. We aim to give
  1621. enough hints that the well-prepared reader, together with a few
  1622. friends, can implement a compiler from \LangVar{} to x86 in a short
  1623. time. To suggest the scale of this first compiler, we note that the
  1624. instructor solution for the \LangVar{} compiler is approximately
  1625. \racket{500}\python{300} lines of code.
  1626. \section{The \LangVar{} Language}
  1627. \label{sec:s0}
  1628. \index{subject}{variable}
  1629. The \LangVar{} language extends the \LangInt{} language with
  1630. variables. The concrete syntax of the \LangVar{} language is defined
  1631. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1632. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1633. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1634. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1635. \key{-} is a unary operator, and \key{+} is a binary operator.
  1636. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1637. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1638. the top of the program.
  1639. %% The $\itm{info}$
  1640. %% field of the \key{Program} structure contains an \emph{association
  1641. %% list} (a list of key-value pairs) that is used to communicate
  1642. %% auxiliary data from one compiler pass the next.
  1643. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1644. exhibit several compilation techniques.
  1645. \newcommand{\LvarGrammarRacket}{
  1646. \begin{array}{rcl}
  1647. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1648. \end{array}
  1649. }
  1650. \newcommand{\LvarASTRacket}{
  1651. \begin{array}{rcl}
  1652. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1653. \end{array}
  1654. }
  1655. \newcommand{\LvarGrammarPython}{
  1656. \begin{array}{rcl}
  1657. \Exp &::=& \Var{} \\
  1658. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1659. \end{array}
  1660. }
  1661. \newcommand{\LvarASTPython}{
  1662. \begin{array}{rcl}
  1663. \Exp{} &::=& \VAR{\Var{}} \\
  1664. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1665. \end{array}
  1666. }
  1667. \begin{figure}[tp]
  1668. \centering
  1669. \begin{tcolorbox}[colback=white]
  1670. {\if\edition\racketEd
  1671. \[
  1672. \begin{array}{l}
  1673. \gray{\LintGrammarRacket{}} \\ \hline
  1674. \LvarGrammarRacket{} \\
  1675. \begin{array}{rcl}
  1676. \LangVarM{} &::=& \Exp
  1677. \end{array}
  1678. \end{array}
  1679. \]
  1680. \fi}
  1681. {\if\edition\pythonEd\pythonColor
  1682. \[
  1683. \begin{array}{l}
  1684. \gray{\LintGrammarPython} \\ \hline
  1685. \LvarGrammarPython \\
  1686. \begin{array}{rcl}
  1687. \LangVarM{} &::=& \Stmt^{*}
  1688. \end{array}
  1689. \end{array}
  1690. \]
  1691. \fi}
  1692. \end{tcolorbox}
  1693. \caption{The concrete syntax of \LangVar{}.}
  1694. \label{fig:Lvar-concrete-syntax}
  1695. \end{figure}
  1696. \begin{figure}[tp]
  1697. \centering
  1698. \begin{tcolorbox}[colback=white]
  1699. {\if\edition\racketEd
  1700. \[
  1701. \begin{array}{l}
  1702. \gray{\LintASTRacket{}} \\ \hline
  1703. \LvarASTRacket \\
  1704. \begin{array}{rcl}
  1705. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1706. \end{array}
  1707. \end{array}
  1708. \]
  1709. \fi}
  1710. {\if\edition\pythonEd\pythonColor
  1711. \[
  1712. \begin{array}{l}
  1713. \gray{\LintASTPython}\\ \hline
  1714. \LvarASTPython \\
  1715. \begin{array}{rcl}
  1716. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1717. \end{array}
  1718. \end{array}
  1719. \]
  1720. \fi}
  1721. \end{tcolorbox}
  1722. \caption{The abstract syntax of \LangVar{}.}
  1723. \label{fig:Lvar-syntax}
  1724. \end{figure}
  1725. {\if\edition\racketEd
  1726. Let us dive further into the syntax and semantics of the \LangVar{}
  1727. language. The \key{let} feature defines a variable for use within its
  1728. body and initializes the variable with the value of an expression.
  1729. The abstract syntax for \key{let} is shown in
  1730. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1731. \begin{lstlisting}
  1732. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1733. \end{lstlisting}
  1734. For example, the following program initializes \code{x} to $32$ and then
  1735. evaluates the body \code{(+ 10 x)}, producing $42$.
  1736. \begin{lstlisting}
  1737. (let ([x (+ 12 20)]) (+ 10 x))
  1738. \end{lstlisting}
  1739. \fi}
  1740. %
  1741. {\if\edition\pythonEd\pythonColor
  1742. %
  1743. The \LangVar{} language includes an assignment statement, which defines a
  1744. variable for use in later statements and initializes the variable with
  1745. the value of an expression. The abstract syntax for assignment is
  1746. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1747. assignment is \index{subject}{Assign@\texttt{Assign}}
  1748. \begin{lstlisting}
  1749. |$\itm{var}$| = |$\itm{exp}$|
  1750. \end{lstlisting}
  1751. For example, the following program initializes the variable \code{x}
  1752. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1753. \begin{lstlisting}
  1754. x = 12 + 20
  1755. print(10 + x)
  1756. \end{lstlisting}
  1757. \fi}
  1758. {\if\edition\racketEd
  1759. %
  1760. When there are multiple \key{let}s for the same variable, the closest
  1761. enclosing \key{let} is used. That is, variable definitions overshadow
  1762. prior definitions. Consider the following program with two \key{let}s
  1763. that define two variables named \code{x}. Can you figure out the
  1764. result?
  1765. \begin{lstlisting}
  1766. (let ([x 32]) (+ (let ([x 10]) x) x))
  1767. \end{lstlisting}
  1768. For the purposes of depicting which variable occurrences correspond to
  1769. which definitions, the following shows the \code{x}'s annotated with
  1770. subscripts to distinguish them. Double-check that your answer for the
  1771. previous program is the same as your answer for this annotated version
  1772. of the program.
  1773. \begin{lstlisting}
  1774. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1775. \end{lstlisting}
  1776. The initializing expression is always evaluated before the body of the
  1777. \key{let}, so in the following, the \key{read} for \code{x} is
  1778. performed before the \key{read} for \code{y}. Given the input
  1779. $52$ then $10$, the following produces $42$ (not $-42$).
  1780. \begin{lstlisting}
  1781. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1782. \end{lstlisting}
  1783. \fi}
  1784. \subsection{Extensible Interpreters via Method Overriding}
  1785. \label{sec:extensible-interp}
  1786. \index{subject}{method overriding}
  1787. To prepare for discussing the interpreter of \LangVar{}, we explain
  1788. why we implement it in an object-oriented style. Throughout this book
  1789. we define many interpreters, one for each language that we
  1790. study. Because each language builds on the prior one, there is a lot
  1791. of commonality between these interpreters. We want to write down the
  1792. common parts just once instead of many times. A naive interpreter for
  1793. \LangVar{} would handle the \racket{cases for variables and
  1794. \code{let}} \python{case for variables} but dispatch to an
  1795. interpreter for \LangInt{} in the rest of the cases. The following
  1796. code sketches this idea. (We explain the \code{env} parameter in
  1797. section~\ref{sec:interp-Lvar}.)
  1798. \begin{center}
  1799. {\if\edition\racketEd
  1800. \begin{minipage}{0.45\textwidth}
  1801. \begin{lstlisting}
  1802. (define ((interp_Lint env) e)
  1803. (match e
  1804. [(Prim '- (list e1))
  1805. (fx- 0 ((interp_Lint env) e1))]
  1806. ...))
  1807. \end{lstlisting}
  1808. \end{minipage}
  1809. \begin{minipage}{0.45\textwidth}
  1810. \begin{lstlisting}
  1811. (define ((interp_Lvar env) e)
  1812. (match e
  1813. [(Var x)
  1814. (dict-ref env x)]
  1815. [(Let x e body)
  1816. (define v ((interp_Lvar env) e))
  1817. (define env^ (dict-set env x v))
  1818. ((interp_Lvar env^) body)]
  1819. [else ((interp_Lint env) e)]))
  1820. \end{lstlisting}
  1821. \end{minipage}
  1822. \fi}
  1823. {\if\edition\pythonEd\pythonColor
  1824. \begin{minipage}{0.45\textwidth}
  1825. \begin{lstlisting}
  1826. def interp_Lint(e, env):
  1827. match e:
  1828. case UnaryOp(USub(), e1):
  1829. return - interp_Lint(e1, env)
  1830. ...
  1831. \end{lstlisting}
  1832. \end{minipage}
  1833. \begin{minipage}{0.45\textwidth}
  1834. \begin{lstlisting}
  1835. def interp_Lvar(e, env):
  1836. match e:
  1837. case Name(id):
  1838. return env[id]
  1839. case _:
  1840. return interp_Lint(e, env)
  1841. \end{lstlisting}
  1842. \end{minipage}
  1843. \fi}
  1844. \end{center}
  1845. The problem with this naive approach is that it does not handle
  1846. situations in which an \LangVar{} feature, such as a variable, is
  1847. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1848. in the following program.
  1849. {\if\edition\racketEd
  1850. \begin{lstlisting}
  1851. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1852. \end{lstlisting}
  1853. \fi}
  1854. {\if\edition\pythonEd\pythonColor
  1855. \begin{minipage}{1.0\textwidth}
  1856. \begin{lstlisting}
  1857. y = 10
  1858. print(-y)
  1859. \end{lstlisting}
  1860. \end{minipage}
  1861. \fi}
  1862. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1863. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1864. then it recursively calls \code{interp\_Lint} again on its argument.
  1865. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1866. \code{interp\_Lint}, we get an error!
  1867. To make our interpreters extensible we need something called
  1868. \emph{open recursion}\index{subject}{open recursion}, in which the
  1869. tying of the recursive knot is delayed until the functions are
  1870. composed. Object-oriented languages provide open recursion via method
  1871. overriding. The following code uses
  1872. method overriding to interpret \LangInt{} and \LangVar{} using
  1873. %
  1874. \racket{the
  1875. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1876. \index{subject}{class} feature of Racket.}%
  1877. %
  1878. \python{Python \code{class} definitions.}
  1879. %
  1880. We define one class for each language and define a method for
  1881. interpreting expressions inside each class. The class for \LangVar{}
  1882. inherits from the class for \LangInt{}, and the method
  1883. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1884. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1885. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1886. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1887. \code{interp\_exp} in \LangInt{}.
  1888. \begin{center}
  1889. \hspace{-20pt}
  1890. {\if\edition\racketEd
  1891. \begin{minipage}{0.45\textwidth}
  1892. \begin{lstlisting}
  1893. (define interp-Lint-class
  1894. (class object%
  1895. (define/public ((interp_exp env) e)
  1896. (match e
  1897. [(Prim '- (list e))
  1898. (fx- 0 ((interp_exp env) e))]
  1899. ...))
  1900. ...))
  1901. \end{lstlisting}
  1902. \end{minipage}
  1903. \begin{minipage}{0.45\textwidth}
  1904. \begin{lstlisting}
  1905. (define interp-Lvar-class
  1906. (class interp-Lint-class
  1907. (define/override ((interp_exp env) e)
  1908. (match e
  1909. [(Var x)
  1910. (dict-ref env x)]
  1911. [(Let x e body)
  1912. (define v ((interp_exp env) e))
  1913. (define env^ (dict-set env x v))
  1914. ((interp_exp env^) body)]
  1915. [else
  1916. (super (interp_exp env) e)]))
  1917. ...
  1918. ))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \fi}
  1922. {\if\edition\pythonEd\pythonColor
  1923. \begin{minipage}{0.45\textwidth}
  1924. \begin{lstlisting}
  1925. class InterpLint:
  1926. def interp_exp(e):
  1927. match e:
  1928. case UnaryOp(USub(), e1):
  1929. return neg64(self.interp_exp(e1))
  1930. ...
  1931. ...
  1932. \end{lstlisting}
  1933. \end{minipage}
  1934. \begin{minipage}{0.45\textwidth}
  1935. \begin{lstlisting}
  1936. def InterpLvar(InterpLint):
  1937. def interp_exp(e):
  1938. match e:
  1939. case Name(id):
  1940. return env[id]
  1941. case _:
  1942. return super().interp_exp(e)
  1943. ...
  1944. \end{lstlisting}
  1945. \end{minipage}
  1946. \fi}
  1947. \end{center}
  1948. We return to the troublesome example, repeated here:
  1949. {\if\edition\racketEd
  1950. \begin{lstlisting}
  1951. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1952. \end{lstlisting}
  1953. \fi}
  1954. {\if\edition\pythonEd\pythonColor
  1955. \begin{lstlisting}
  1956. y = 10
  1957. print(-y)
  1958. \end{lstlisting}
  1959. \fi}
  1960. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1961. \racket{on this expression,}
  1962. \python{on the \code{-y} expression,}
  1963. %
  1964. which we call \code{e0}, by creating an object of the \LangVar{} class
  1965. and calling the \code{interp\_exp} method
  1966. {\if\edition\racketEd
  1967. \begin{lstlisting}
  1968. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1969. \end{lstlisting}
  1970. \fi}
  1971. {\if\edition\pythonEd\pythonColor
  1972. \begin{lstlisting}
  1973. InterpLvar().interp_exp(e0)
  1974. \end{lstlisting}
  1975. \fi}
  1976. \noindent To process the \code{-} operator, the default case of
  1977. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1978. method in \LangInt{}. But then for the recursive method call, it
  1979. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1980. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  1981. Thus, method overriding gives us the open recursion that we need to
  1982. implement our interpreters in an extensible way.
  1983. \subsection{Definitional Interpreter for \LangVar{}}
  1984. \label{sec:interp-Lvar}
  1985. Having justified the use of classes and methods to implement
  1986. interpreters, we revisit the definitional interpreter for \LangInt{}
  1987. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1988. create an interpreter for \LangVar{}, shown in
  1989. figure~\ref{fig:interp-Lvar}.
  1990. %
  1991. \python{We change the \code{interp\_stmt} method in the interpreter
  1992. for \LangInt{} to take two extra parameters named \code{env}, which
  1993. we discuss in the next paragraph, and \code{cont} for
  1994. \emph{continuation}, which is the technical name for what comes
  1995. after a particular point in a program. The \code{cont} parameter is
  1996. the list of statements that follow the current statement. Note
  1997. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  1998. statement and passes the rest of the statements as the argument for
  1999. \code{cont}. This organization enables each statement to decide what
  2000. if anything should be evaluated after it, for example, allowing a
  2001. \code{return} statement to exit early from a function (see
  2002. Chapter~\ref{ch:Lfun}).}
  2003. The interpreter for \LangVar{} adds two new cases for
  2004. variables and \racket{\key{let}}\python{assignment}. For
  2005. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2006. value bound to a variable to all the uses of the variable. To
  2007. accomplish this, we maintain a mapping from variables to values called
  2008. an \emph{environment}\index{subject}{environment}.
  2009. %
  2010. We use
  2011. %
  2012. \racket{an association list (alist) }%
  2013. %
  2014. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2015. %
  2016. to represent the environment.
  2017. %
  2018. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2019. and the \code{racket/dict} package.}
  2020. %
  2021. The \code{interp\_exp} function takes the current environment,
  2022. \code{env}, as an extra parameter. When the interpreter encounters a
  2023. variable, it looks up the corresponding value in the environment. If
  2024. the variable is not in the environment (because the variable was not
  2025. defined) then the lookup will fail and the interpreter will
  2026. halt with an error. Recall that the compiler is not obligated to
  2027. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2028. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2029. prohibit access to undefined variables.}
  2030. %
  2031. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2032. initializing expression, extends the environment with the result
  2033. value bound to the variable, using \code{dict-set}, then evaluates
  2034. the body of the \key{Let}.}
  2035. %
  2036. \python{When the interpreter encounters an assignment, it evaluates
  2037. the initializing expression and then associates the resulting value
  2038. with the variable in the environment.}
  2039. \begin{figure}[tp]
  2040. \begin{tcolorbox}[colback=white]
  2041. {\if\edition\racketEd
  2042. \begin{lstlisting}
  2043. (define interp-Lint-class
  2044. (class object%
  2045. (super-new)
  2046. (define/public ((interp_exp env) e)
  2047. (match e
  2048. [(Int n) n]
  2049. [(Prim 'read '())
  2050. (define r (read))
  2051. (cond [(fixnum? r) r]
  2052. [else (error 'interp_exp "expected an integer" r)])]
  2053. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2054. [(Prim '+ (list e1 e2))
  2055. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2056. [(Prim '- (list e1 e2))
  2057. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2058. (define/public (interp_program p)
  2059. (match p
  2060. [(Program '() e) ((interp_exp '()) e)]))
  2061. ))
  2062. \end{lstlisting}
  2063. \fi}
  2064. {\if\edition\pythonEd\pythonColor
  2065. \begin{lstlisting}
  2066. class InterpLint:
  2067. def interp_exp(self, e, env):
  2068. match e:
  2069. case BinOp(left, Add(), right):
  2070. l = self.interp_exp(left, env)
  2071. r = self.interp_exp(right, env)
  2072. return add64(l, r)
  2073. case BinOp(left, Sub(), right):
  2074. l = self.interp_exp(left, env)
  2075. r = self.interp_exp(right, env)
  2076. return sub64(l, r)
  2077. case UnaryOp(USub(), v):
  2078. return neg64(self.interp_exp(v, env))
  2079. case Constant(value):
  2080. return value
  2081. case Call(Name('input_int'), []):
  2082. return int(input())
  2083. def interp_stmt(self, s, env, cont):
  2084. match s:
  2085. case Expr(Call(Name('print'), [arg])):
  2086. val = self.interp_exp(arg, env)
  2087. print(val, end='')
  2088. return self.interp_stmts(cont, env)
  2089. case Expr(value):
  2090. self.interp_exp(value, env)
  2091. return self.interp_stmts(cont, env)
  2092. case _:
  2093. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2094. def interp_stmts(self, ss, env):
  2095. match ss:
  2096. case []:
  2097. return 0
  2098. case [s, *ss]:
  2099. return self.interp_stmt(s, env, ss)
  2100. def interp(self, p):
  2101. match p:
  2102. case Module(body):
  2103. self.interp_stmts(body, {})
  2104. def interp_Lint(p):
  2105. return InterpLint().interp(p)
  2106. \end{lstlisting}
  2107. \fi}
  2108. \end{tcolorbox}
  2109. \caption{Interpreter for \LangInt{} as a class.}
  2110. \label{fig:interp-Lint-class}
  2111. \end{figure}
  2112. \begin{figure}[tp]
  2113. \begin{tcolorbox}[colback=white]
  2114. {\if\edition\racketEd
  2115. \begin{lstlisting}
  2116. (define interp-Lvar-class
  2117. (class interp-Lint-class
  2118. (super-new)
  2119. (define/override ((interp_exp env) e)
  2120. (match e
  2121. [(Var x) (dict-ref env x)]
  2122. [(Let x e body)
  2123. (define new-env (dict-set env x ((interp_exp env) e)))
  2124. ((interp_exp new-env) body)]
  2125. [else ((super interp_exp env) e)]))
  2126. ))
  2127. (define (interp_Lvar p)
  2128. (send (new interp-Lvar-class) interp_program p))
  2129. \end{lstlisting}
  2130. \fi}
  2131. {\if\edition\pythonEd\pythonColor
  2132. \begin{lstlisting}
  2133. class InterpLvar(InterpLint):
  2134. def interp_exp(self, e, env):
  2135. match e:
  2136. case Name(id):
  2137. return env[id]
  2138. case _:
  2139. return super().interp_exp(e, env)
  2140. def interp_stmt(self, s, env, cont):
  2141. match s:
  2142. case Assign([Name(id)], value):
  2143. env[id] = self.interp_exp(value, env)
  2144. return self.interp_stmts(cont, env)
  2145. case _:
  2146. return super().interp_stmt(s, env, cont)
  2147. def interp_Lvar(p):
  2148. return InterpLvar().interp(p)
  2149. \end{lstlisting}
  2150. \fi}
  2151. \end{tcolorbox}
  2152. \caption{Interpreter for the \LangVar{} language.}
  2153. \label{fig:interp-Lvar}
  2154. \end{figure}
  2155. {\if\edition\racketEd
  2156. \begin{figure}[tp]
  2157. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2158. \small
  2159. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2160. An \emph{association list} (called an alist) is a list of key-value pairs.
  2161. For example, we can map people to their ages with an alist
  2162. \index{subject}{alist}\index{subject}{association list}
  2163. \begin{lstlisting}[basicstyle=\ttfamily]
  2164. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2165. \end{lstlisting}
  2166. The \emph{dictionary} interface is for mapping keys to values.
  2167. Every alist implements this interface. \index{subject}{dictionary}
  2168. The package
  2169. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2170. provides many functions for working with dictionaries, such as
  2171. \begin{description}
  2172. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2173. returns the value associated with the given $\itm{key}$.
  2174. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2175. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2176. and otherwise is the same as $\itm{dict}$.
  2177. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2178. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2179. of keys and values in $\itm{dict}$. For example, the following
  2180. creates a new alist in which the ages are incremented:
  2181. \end{description}
  2182. \vspace{-10pt}
  2183. \begin{lstlisting}[basicstyle=\ttfamily]
  2184. (for/list ([(k v) (in-dict ages)])
  2185. (cons k (add1 v)))
  2186. \end{lstlisting}
  2187. \end{tcolorbox}
  2188. %\end{wrapfigure}
  2189. \caption{Association lists implement the dictionary interface.}
  2190. \label{fig:alist}
  2191. \end{figure}
  2192. \fi}
  2193. The goal for this chapter is to implement a compiler that translates
  2194. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2195. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2196. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2197. That is, they output the same integer $n$. We depict this correctness
  2198. criteria in the following diagram:
  2199. \[
  2200. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2201. \node (p1) at (0, 0) {$P_1$};
  2202. \node (p2) at (4, 0) {$P_2$};
  2203. \node (o) at (4, -2) {$n$};
  2204. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2205. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2206. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2207. \end{tikzpicture}
  2208. \]
  2209. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2210. compiling \LangVar{}.
  2211. \section{The \LangXInt{} Assembly Language}
  2212. \label{sec:x86}
  2213. \index{subject}{x86}
  2214. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2215. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2216. assembler.
  2217. %
  2218. A program begins with a \code{main} label followed by a sequence of
  2219. instructions. The \key{globl} directive makes the \key{main} procedure
  2220. externally visible so that the operating system can call it.
  2221. %
  2222. An x86 program is stored in the computer's memory. For our purposes,
  2223. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2224. values. The computer has a \emph{program counter}
  2225. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2226. \code{rip} register that points to the address of the next instruction
  2227. to be executed. For most instructions, the program counter is
  2228. incremented after the instruction is executed so that it points to the
  2229. next instruction in memory. Most x86 instructions take two operands,
  2230. each of which is an integer constant (called an \emph{immediate
  2231. value}\index{subject}{immediate value}), a
  2232. \emph{register}\index{subject}{register}, or a memory location.
  2233. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2234. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2235. && \key{r8} \MID \key{r9} \MID \key{r10}
  2236. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2237. \MID \key{r14} \MID \key{r15}}
  2238. \newcommand{\GrammarXInt}{
  2239. \begin{array}{rcl}
  2240. \Reg &::=& \allregisters{} \\
  2241. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2242. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2243. \key{subq} \; \Arg\key{,} \Arg \MID
  2244. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2245. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2246. \key{callq} \; \mathit{label} \MID
  2247. \key{retq} \MID
  2248. \key{jmp}\,\itm{label} \MID \\
  2249. && \itm{label}\key{:}\; \Instr
  2250. \end{array}
  2251. }
  2252. \begin{figure}[tp]
  2253. \begin{tcolorbox}[colback=white]
  2254. {\if\edition\racketEd
  2255. \[
  2256. \begin{array}{l}
  2257. \GrammarXInt \\
  2258. \begin{array}{lcl}
  2259. \LangXIntM{} &::= & \key{.globl main}\\
  2260. & & \key{main:} \; \Instr\ldots
  2261. \end{array}
  2262. \end{array}
  2263. \]
  2264. \fi}
  2265. {\if\edition\pythonEd\pythonColor
  2266. \[
  2267. \begin{array}{lcl}
  2268. \Reg &::=& \allregisters{} \\
  2269. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2270. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2271. \key{subq} \; \Arg\key{,} \Arg \MID
  2272. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2273. && \key{callq} \; \mathit{label} \MID
  2274. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2275. \LangXIntM{} &::= & \key{.globl main}\\
  2276. & & \key{main:} \; \Instr^{*}
  2277. \end{array}
  2278. \]
  2279. \fi}
  2280. \end{tcolorbox}
  2281. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2282. \label{fig:x86-int-concrete}
  2283. \end{figure}
  2284. A register is a special kind of variable that holds a 64-bit
  2285. value. There are 16 general-purpose registers in the computer; their
  2286. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2287. written with a percent sign, \key{\%}, followed by its name,
  2288. for example \key{\%rax}.
  2289. An immediate value is written using the notation \key{\$}$n$ where $n$
  2290. is an integer.
  2291. %
  2292. %
  2293. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2294. which obtains the address stored in register $r$ and then adds $n$
  2295. bytes to the address. The resulting address is used to load or to store
  2296. to memory depending on whether it occurs as a source or destination
  2297. argument of an instruction.
  2298. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2299. the source $s$ and destination $d$, applies the arithmetic operation,
  2300. and then writes the result to the destination $d$. \index{subject}{instruction}
  2301. %
  2302. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2303. stores the result in $d$.
  2304. %
  2305. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2306. specified by the label, and $\key{retq}$ returns from a procedure to
  2307. its caller.
  2308. %
  2309. We discuss procedure calls in more detail further in this chapter and
  2310. in chapter~\ref{ch:Lfun}.
  2311. %
  2312. The last letter \key{q} indicates that these instructions operate on
  2313. quadwords, which are 64-bit values.
  2314. %
  2315. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2316. counter to the address of the instruction immediately after the
  2317. specified label.}
  2318. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2319. all the x86 instructions used in this book.
  2320. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2321. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2322. \lstinline{movq $10, %rax}
  2323. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2324. adds $32$ to the $10$ in \key{rax} and
  2325. puts the result, $42$, into \key{rax}.
  2326. %
  2327. The last instruction \key{retq} finishes the \key{main} function by
  2328. returning the integer in \key{rax} to the operating system. The
  2329. operating system interprets this integer as the program's exit
  2330. code. By convention, an exit code of 0 indicates that a program has
  2331. completed successfully, and all other exit codes indicate various
  2332. errors.
  2333. %
  2334. \racket{However, in this book we return the result of the program
  2335. as the exit code.}
  2336. \begin{figure}[tbp]
  2337. \begin{minipage}{0.45\textwidth}
  2338. \begin{tcolorbox}[colback=white]
  2339. \begin{lstlisting}
  2340. .globl main
  2341. main:
  2342. movq $10, %rax
  2343. addq $32, %rax
  2344. retq
  2345. \end{lstlisting}
  2346. \end{tcolorbox}
  2347. \end{minipage}
  2348. \caption{An x86 program that computes
  2349. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2350. \label{fig:p0-x86}
  2351. \end{figure}
  2352. We exhibit the use of memory for storing intermediate results in the
  2353. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2354. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2355. uses a region of memory called the \emph{procedure call stack}
  2356. (\emph{stack} for
  2357. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2358. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2359. for each procedure call. The memory layout for an individual frame is
  2360. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2361. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2362. address of the item at the top of the stack. In general, we use the
  2363. term \emph{pointer}\index{subject}{pointer} for something that
  2364. contains an address. The stack grows downward in memory, so we
  2365. increase the size of the stack by subtracting from the stack pointer.
  2366. In the context of a procedure call, the \emph{return
  2367. address}\index{subject}{return address} is the location of the
  2368. instruction that immediately follows the call instruction on the
  2369. caller side. The function call instruction, \code{callq}, pushes the
  2370. return address onto the stack prior to jumping to the procedure. The
  2371. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2372. pointer} and is used to access variables that are stored in the
  2373. frame of the current procedure call. The base pointer of the caller
  2374. is stored immediately after the return address.
  2375. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2376. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2377. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2378. $-16\key{(\%rbp)}$, and so on.
  2379. \begin{figure}[tbp]
  2380. \begin{minipage}{0.66\textwidth}
  2381. \begin{tcolorbox}[colback=white]
  2382. {\if\edition\racketEd
  2383. \begin{lstlisting}
  2384. start:
  2385. movq $10, -8(%rbp)
  2386. negq -8(%rbp)
  2387. movq -8(%rbp), %rax
  2388. addq $52, %rax
  2389. jmp conclusion
  2390. .globl main
  2391. main:
  2392. pushq %rbp
  2393. movq %rsp, %rbp
  2394. subq $16, %rsp
  2395. jmp start
  2396. conclusion:
  2397. addq $16, %rsp
  2398. popq %rbp
  2399. retq
  2400. \end{lstlisting}
  2401. \fi}
  2402. {\if\edition\pythonEd\pythonColor
  2403. \begin{lstlisting}
  2404. .globl main
  2405. main:
  2406. pushq %rbp
  2407. movq %rsp, %rbp
  2408. subq $16, %rsp
  2409. movq $10, -8(%rbp)
  2410. negq -8(%rbp)
  2411. movq -8(%rbp), %rax
  2412. addq $52, %rax
  2413. addq $16, %rsp
  2414. popq %rbp
  2415. retq
  2416. \end{lstlisting}
  2417. \fi}
  2418. \end{tcolorbox}
  2419. \end{minipage}
  2420. \caption{An x86 program that computes
  2421. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2422. \label{fig:p1-x86}
  2423. \end{figure}
  2424. \begin{figure}[tbp]
  2425. \begin{minipage}{0.66\textwidth}
  2426. \begin{tcolorbox}[colback=white]
  2427. \centering
  2428. \begin{tabular}{|r|l|} \hline
  2429. Position & Contents \\ \hline
  2430. $8$(\key{\%rbp}) & return address \\
  2431. $0$(\key{\%rbp}) & old \key{rbp} \\
  2432. $-8$(\key{\%rbp}) & variable $1$ \\
  2433. $-16$(\key{\%rbp}) & variable $2$ \\
  2434. \ldots & \ldots \\
  2435. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2436. \end{tabular}
  2437. \end{tcolorbox}
  2438. \end{minipage}
  2439. \caption{Memory layout of a frame.}
  2440. \label{fig:frame}
  2441. \end{figure}
  2442. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2443. is transferred from the operating system to the \code{main} function.
  2444. The operating system issues a \code{callq main} instruction that
  2445. pushes its return address on the stack and then jumps to
  2446. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2447. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2448. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2449. out of alignment (because the \code{callq} pushed the return address).
  2450. The first three instructions are the typical
  2451. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2452. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2453. pointer \code{rsp} and then saves the base pointer of the caller at
  2454. address \code{rsp} on the stack. The next instruction \code{movq
  2455. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2456. which is pointing to the location of the old base pointer. The
  2457. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2458. make enough room for storing variables. This program needs one
  2459. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2460. 16-byte-aligned, and then we are ready to make calls to other functions.
  2461. \racket{The last instruction of the prelude is \code{jmp start}, which
  2462. transfers control to the instructions that were generated from the
  2463. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2464. \racket{The first instruction under the \code{start} label is}
  2465. %
  2466. \python{The first instruction after the prelude is}
  2467. %
  2468. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2469. %
  2470. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2471. $1$ to $-10$.
  2472. %
  2473. The next instruction moves the $-10$ from variable $1$ into the
  2474. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2475. the value in \code{rax}, updating its contents to $42$.
  2476. \racket{The three instructions under the label \code{conclusion} are the
  2477. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2478. %
  2479. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2480. \code{main} function consists of the last three instructions.}
  2481. %
  2482. The first two restore the \code{rsp} and \code{rbp} registers to their
  2483. states at the beginning of the procedure. In particular,
  2484. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2485. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2486. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2487. \key{retq}, jumps back to the procedure that called this one and adds
  2488. $8$ to the stack pointer.
  2489. Our compiler needs a convenient representation for manipulating x86
  2490. programs, so we define an abstract syntax for x86, shown in
  2491. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2492. \LangXInt{}.
  2493. %
  2494. {\if\edition\pythonEd\pythonColor%
  2495. The main difference between this and the concrete syntax of \LangXInt{}
  2496. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2497. names, and register names are explicitly represented by strings.
  2498. \fi} %
  2499. {\if\edition\racketEd
  2500. The main difference between this and the concrete syntax of \LangXInt{}
  2501. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2502. front of every instruction. Instead instructions are grouped into
  2503. \emph{basic blocks}\index{subject}{basic block} with a
  2504. label associated with every basic block; this is why the \key{X86Program}
  2505. struct includes an alist mapping labels to basic blocks. The reason for this
  2506. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2507. introduce conditional branching. The \code{Block} structure includes
  2508. an $\itm{info}$ field that is not needed in this chapter but becomes
  2509. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2510. $\itm{info}$ field should contain an empty list.
  2511. \fi}
  2512. %
  2513. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2514. node includes an integer for representing the arity of the function,
  2515. that is, the number of arguments, which is helpful to know during
  2516. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2517. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2518. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2519. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2520. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2521. \MID \skey{r14} \MID \skey{r15}}
  2522. \newcommand{\ASTXIntRacket}{
  2523. \begin{array}{lcl}
  2524. \Reg &::=& \allregisters{} \\
  2525. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2526. \MID \DEREF{\Reg}{\Int} \\
  2527. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2528. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2529. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2530. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2531. &\MID& \PUSHQ{\Arg}
  2532. \MID \POPQ{\Arg} \\
  2533. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2534. \MID \RETQ{}
  2535. \MID \JMP{\itm{label}} \\
  2536. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2537. \end{array}
  2538. }
  2539. \newcommand{\ASTXIntPython}{
  2540. \begin{array}{lcl}
  2541. \Reg &::=& \allregisters{} \\
  2542. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2543. \MID \DEREF{\Reg}{\Int} \\
  2544. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2545. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2546. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2547. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2548. &\MID& \PUSHQ{\Arg}
  2549. \MID \POPQ{\Arg} \\
  2550. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2551. \MID \RETQ{}
  2552. \MID \JMP{\itm{label}} \\
  2553. \Block &::= & \Instr^{+}
  2554. \end{array}
  2555. }
  2556. \begin{figure}[tp]
  2557. \begin{tcolorbox}[colback=white]
  2558. \small
  2559. {\if\edition\racketEd
  2560. \[\arraycolsep=3pt
  2561. \begin{array}{l}
  2562. \ASTXIntRacket \\
  2563. \begin{array}{lcl}
  2564. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2565. \end{array}
  2566. \end{array}
  2567. \]
  2568. \fi}
  2569. {\if\edition\pythonEd\pythonColor
  2570. \[
  2571. \begin{array}{lcl}
  2572. \Reg &::=& \allastregisters{} \\
  2573. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2574. \MID \DEREF{\Reg}{\Int} \\
  2575. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2576. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2577. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2578. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2579. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2580. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2581. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2582. \end{array}
  2583. \]
  2584. \fi}
  2585. \end{tcolorbox}
  2586. \caption{The abstract syntax of \LangXInt{} assembly.}
  2587. \label{fig:x86-int-ast}
  2588. \end{figure}
  2589. \section{Planning the Trip to x86}
  2590. \label{sec:plan-s0-x86}
  2591. To compile one language to another, it helps to focus on the
  2592. differences between the two languages because the compiler will need
  2593. to bridge those differences. What are the differences between \LangVar{}
  2594. and x86 assembly? Here are some of the most important ones:
  2595. \begin{enumerate}
  2596. \item x86 arithmetic instructions typically have two arguments and
  2597. update the second argument in place. In contrast, \LangVar{}
  2598. arithmetic operations take two arguments and produce a new value.
  2599. An x86 instruction may have at most one memory-accessing argument.
  2600. Furthermore, some x86 instructions place special restrictions on
  2601. their arguments.
  2602. \item An argument of an \LangVar{} operator can be a deeply nested
  2603. expression, whereas x86 instructions restrict their arguments to be
  2604. integer constants, registers, and memory locations.
  2605. {\if\edition\racketEd
  2606. \item The order of execution in x86 is explicit in the syntax, which
  2607. is a sequence of instructions and jumps to labeled positions,
  2608. whereas in \LangVar{} the order of evaluation is a left-to-right
  2609. depth-first traversal of the abstract syntax tree. \fi}
  2610. \item A program in \LangVar{} can have any number of variables,
  2611. whereas x86 has 16 registers and the procedure call stack.
  2612. {\if\edition\racketEd
  2613. \item Variables in \LangVar{} can shadow other variables with the
  2614. same name. In x86, registers have unique names, and memory locations
  2615. have unique addresses.
  2616. \fi}
  2617. \end{enumerate}
  2618. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2619. down the problem into several steps, which deal with these differences
  2620. one at a time. Each of these steps is called a \emph{pass} of the
  2621. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2622. %
  2623. This term indicates that each step passes over, or traverses, the AST
  2624. of the program.
  2625. %
  2626. Furthermore, we follow the nanopass approach, which means that we
  2627. strive for each pass to accomplish one clear objective rather than two
  2628. or three at the same time.
  2629. %
  2630. We begin by sketching how we might implement each pass and give each
  2631. pass a name. We then figure out an ordering of the passes and the
  2632. input/output language for each pass. The very first pass has
  2633. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2634. its output language. In between these two passes, we can choose
  2635. whichever language is most convenient for expressing the output of
  2636. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2637. \emph{intermediate language} of our own design. Finally, to
  2638. implement each pass we write one recursive function per nonterminal in
  2639. the grammar of the input language of the pass.
  2640. \index{subject}{intermediate language}
  2641. Our compiler for \LangVar{} consists of the following passes:
  2642. %
  2643. \begin{description}
  2644. {\if\edition\racketEd
  2645. \item[\key{uniquify}] deals with the shadowing of variables by
  2646. renaming every variable to a unique name.
  2647. \fi}
  2648. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2649. of a primitive operation or function call is a variable or integer,
  2650. that is, an \emph{atomic} expression. We refer to nonatomic
  2651. expressions as \emph{complex}. This pass introduces temporary
  2652. variables to hold the results of complex
  2653. subexpressions.\index{subject}{atomic
  2654. expression}\index{subject}{complex expression}%
  2655. {\if\edition\racketEd
  2656. \item[\key{explicate\_control}] makes the execution order of the
  2657. program explicit. It converts the abstract syntax tree
  2658. representation into a graph in which each node is a labeled sequence
  2659. of statements and the edges are \code{goto} statements.
  2660. \fi}
  2661. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2662. handles the difference between
  2663. \LangVar{} operations and x86 instructions. This pass converts each
  2664. \LangVar{} operation to a short sequence of instructions that
  2665. accomplishes the same task.
  2666. \item[\key{assign\_homes}] replaces variables with registers or stack
  2667. locations.
  2668. \end{description}
  2669. %
  2670. {\if\edition\racketEd
  2671. %
  2672. Our treatment of \code{remove\_complex\_operands} and
  2673. \code{explicate\_control} as separate passes is an example of the
  2674. nanopass approach.\footnote{For analogous decompositions of the
  2675. translation into continuation passing style, see the work of
  2676. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2677. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2678. %
  2679. \fi}
  2680. The next question is, in what order should we apply these passes? This
  2681. question can be challenging because it is difficult to know ahead of
  2682. time which orderings will be better (that is, will be easier to
  2683. implement, produce more efficient code, and so on), and therefore
  2684. ordering often involves trial and error. Nevertheless, we can plan
  2685. ahead and make educated choices regarding the ordering.
  2686. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2687. \key{uniquify}? The \key{uniquify} pass should come first because
  2688. \key{explicate\_control} changes all the \key{let}-bound variables to
  2689. become local variables whose scope is the entire program, which would
  2690. confuse variables with the same name.}
  2691. %
  2692. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2693. because the later removes the \key{let} form, but it is convenient to
  2694. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2695. %
  2696. \racket{The ordering of \key{uniquify} with respect to
  2697. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2698. \key{uniquify} to come first.}
  2699. The \key{select\_instructions} and \key{assign\_homes} passes are
  2700. intertwined.
  2701. %
  2702. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2703. passing arguments to functions and that it is preferable to assign
  2704. parameters to their corresponding registers. This suggests that it
  2705. would be better to start with the \key{select\_instructions} pass,
  2706. which generates the instructions for argument passing, before
  2707. performing register allocation.
  2708. %
  2709. On the other hand, by selecting instructions first we may run into a
  2710. dead end in \key{assign\_homes}. Recall that only one argument of an
  2711. x86 instruction may be a memory access, but \key{assign\_homes} might
  2712. be forced to assign both arguments to memory locations.
  2713. %
  2714. A sophisticated approach is to repeat the two passes until a solution
  2715. is found. However, to reduce implementation complexity we recommend
  2716. placing \key{select\_instructions} first, followed by the
  2717. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2718. that uses a reserved register to fix outstanding problems.
  2719. \begin{figure}[tbp]
  2720. \begin{tcolorbox}[colback=white]
  2721. {\if\edition\racketEd
  2722. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2723. \node (Lvar) at (0,2) {\large \LangVar{}};
  2724. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2725. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2726. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2727. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2728. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2729. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2730. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2731. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2732. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2733. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2734. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2735. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2736. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2737. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2738. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2739. \end{tikzpicture}
  2740. \fi}
  2741. {\if\edition\pythonEd\pythonColor
  2742. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2743. \node (Lvar) at (0,2) {\large \LangVar{}};
  2744. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2745. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2746. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2747. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2748. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2749. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2750. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2751. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2752. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2753. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2754. \end{tikzpicture}
  2755. \fi}
  2756. \end{tcolorbox}
  2757. \caption{Diagram of the passes for compiling \LangVar{}. }
  2758. \label{fig:Lvar-passes}
  2759. \end{figure}
  2760. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2761. passes and identifies the input and output language of each pass.
  2762. %
  2763. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2764. language, which extends \LangXInt{} with an unbounded number of
  2765. program-scope variables and removes the restrictions regarding
  2766. instruction arguments.
  2767. %
  2768. The last pass, \key{prelude\_and\_conclusion}, places the program
  2769. instructions inside a \code{main} function with instructions for the
  2770. prelude and conclusion.
  2771. %
  2772. \racket{In the next section we discuss the \LangCVar{} intermediate
  2773. language that serves as the output of \code{explicate\_control}.}
  2774. %
  2775. The remainder of this chapter provides guidance on the implementation
  2776. of each of the compiler passes represented in
  2777. figure~\ref{fig:Lvar-passes}.
  2778. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2779. %% are programs that are still in the \LangVar{} language, though the
  2780. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2781. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2782. %% %
  2783. %% The output of \code{explicate\_control} is in an intermediate language
  2784. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2785. %% syntax, which we introduce in the next section. The
  2786. %% \key{select-instruction} pass translates from \LangCVar{} to
  2787. %% \LangXVar{}. The \key{assign-homes} and
  2788. %% \key{patch-instructions}
  2789. %% passes input and output variants of x86 assembly.
  2790. \newcommand{\CvarGrammarRacket}{
  2791. \begin{array}{lcl}
  2792. \Atm &::=& \Int \MID \Var \\
  2793. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2794. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2795. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2796. \end{array}
  2797. }
  2798. \newcommand{\CvarASTRacket}{
  2799. \begin{array}{lcl}
  2800. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2801. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2802. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2803. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2804. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2805. \end{array}
  2806. }
  2807. {\if\edition\racketEd
  2808. \subsection{The \LangCVar{} Intermediate Language}
  2809. The output of \code{explicate\_control} is similar to the C
  2810. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2811. categories for expressions and statements, so we name it \LangCVar{}.
  2812. This style of intermediate language is also known as
  2813. \emph{three-address code}, to emphasize that the typical form of a
  2814. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2815. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2816. The concrete syntax for \LangCVar{} is shown in
  2817. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2818. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2819. %
  2820. The \LangCVar{} language supports the same operators as \LangVar{} but
  2821. the arguments of operators are restricted to atomic
  2822. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2823. assignment statements that can be executed in sequence using the
  2824. \key{Seq} form. A sequence of statements always ends with
  2825. \key{Return}, a guarantee that is baked into the grammar rules for
  2826. \itm{tail}. The naming of this nonterminal comes from the term
  2827. \emph{tail position}\index{subject}{tail position}, which refers to an
  2828. expression that is the last one to execute within a function or
  2829. program.
  2830. A \LangCVar{} program consists of an alist mapping labels to
  2831. tails. This is more general than necessary for the present chapter, as
  2832. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2833. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2834. there is just one label, \key{start}, and the whole program is
  2835. its tail.
  2836. %
  2837. The $\itm{info}$ field of the \key{CProgram} form, after the
  2838. \code{explicate\_control} pass, contains an alist that associates the
  2839. symbol \key{locals} with a list of all the variables used in the
  2840. program. At the start of the program, these variables are
  2841. uninitialized; they become initialized on their first assignment.
  2842. \begin{figure}[tbp]
  2843. \begin{tcolorbox}[colback=white]
  2844. \[
  2845. \begin{array}{l}
  2846. \CvarGrammarRacket \\
  2847. \begin{array}{lcl}
  2848. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2849. \end{array}
  2850. \end{array}
  2851. \]
  2852. \end{tcolorbox}
  2853. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2854. \label{fig:c0-concrete-syntax}
  2855. \end{figure}
  2856. \begin{figure}[tbp]
  2857. \begin{tcolorbox}[colback=white]
  2858. \[
  2859. \begin{array}{l}
  2860. \CvarASTRacket \\
  2861. \begin{array}{lcl}
  2862. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2863. \end{array}
  2864. \end{array}
  2865. \]
  2866. \end{tcolorbox}
  2867. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2868. \label{fig:c0-syntax}
  2869. \end{figure}
  2870. The definitional interpreter for \LangCVar{} is in the support code,
  2871. in the file \code{interp-Cvar.rkt}.
  2872. \fi}
  2873. {\if\edition\racketEd
  2874. \section{Uniquify Variables}
  2875. \label{sec:uniquify-Lvar}
  2876. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2877. with a unique name. Both the input and output of the \code{uniquify}
  2878. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2879. should translate the program on the left into the program on the
  2880. right.
  2881. \begin{transformation}
  2882. \begin{lstlisting}
  2883. (let ([x 32])
  2884. (+ (let ([x 10]) x) x))
  2885. \end{lstlisting}
  2886. \compilesto
  2887. \begin{lstlisting}
  2888. (let ([x.1 32])
  2889. (+ (let ([x.2 10]) x.2) x.1))
  2890. \end{lstlisting}
  2891. \end{transformation}
  2892. The following is another example translation, this time of a program
  2893. with a \key{let} nested inside the initializing expression of another
  2894. \key{let}.
  2895. \begin{transformation}
  2896. \begin{lstlisting}
  2897. (let ([x (let ([x 4])
  2898. (+ x 1))])
  2899. (+ x 2))
  2900. \end{lstlisting}
  2901. \compilesto
  2902. \begin{lstlisting}
  2903. (let ([x.2 (let ([x.1 4])
  2904. (+ x.1 1))])
  2905. (+ x.2 2))
  2906. \end{lstlisting}
  2907. \end{transformation}
  2908. We recommend implementing \code{uniquify} by creating a structurally
  2909. recursive function named \code{uniquify\_exp} that does little other
  2910. than copy an expression. However, when encountering a \key{let}, it
  2911. should generate a unique name for the variable and associate the old
  2912. name with the new name in an alist.\footnote{The Racket function
  2913. \code{gensym} is handy for generating unique variable names.} The
  2914. \code{uniquify\_exp} function needs to access this alist when it gets
  2915. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2916. for the alist.
  2917. The skeleton of the \code{uniquify\_exp} function is shown in
  2918. figure~\ref{fig:uniquify-Lvar}.
  2919. %% The function is curried so that it is
  2920. %% convenient to partially apply it to an alist and then apply it to
  2921. %% different expressions, as in the last case for primitive operations in
  2922. %% figure~\ref{fig:uniquify-Lvar}.
  2923. The
  2924. %
  2925. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2926. %
  2927. form of Racket is useful for transforming the element of a list to
  2928. produce a new list.\index{subject}{for/list}
  2929. \begin{figure}[tbp]
  2930. \begin{tcolorbox}[colback=white]
  2931. \begin{lstlisting}
  2932. (define (uniquify_exp env)
  2933. (lambda (e)
  2934. (match e
  2935. [(Var x) ___]
  2936. [(Int n) (Int n)]
  2937. [(Let x e body) ___]
  2938. [(Prim op es)
  2939. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2940. (define (uniquify p)
  2941. (match p
  2942. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2943. \end{lstlisting}
  2944. \end{tcolorbox}
  2945. \caption{Skeleton for the \key{uniquify} pass.}
  2946. \label{fig:uniquify-Lvar}
  2947. \end{figure}
  2948. \begin{exercise}
  2949. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2950. Complete the \code{uniquify} pass by filling in the blanks in
  2951. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2952. variables and for the \key{let} form in the file \code{compiler.rkt}
  2953. in the support code.
  2954. \end{exercise}
  2955. \begin{exercise}
  2956. \normalfont\normalsize
  2957. \label{ex:Lvar}
  2958. Create five \LangVar{} programs that exercise the most interesting
  2959. parts of the \key{uniquify} pass; that is, the programs should include
  2960. \key{let} forms, variables, and variables that shadow each other.
  2961. The five programs should be placed in the subdirectory named
  2962. \key{tests}, and the file names should start with \code{var\_test\_}
  2963. followed by a unique integer and end with the file extension
  2964. \key{.rkt}.
  2965. %
  2966. The \key{run-tests.rkt} script in the support code checks whether the
  2967. output programs produce the same result as the input programs. The
  2968. script uses the \key{interp-tests} function
  2969. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2970. your \key{uniquify} pass on the example programs. The \code{passes}
  2971. parameter of \key{interp-tests} is a list that should have one entry
  2972. for each pass in your compiler. For now, define \code{passes} to
  2973. contain just one entry for \code{uniquify} as follows:
  2974. \begin{lstlisting}
  2975. (define passes
  2976. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2977. \end{lstlisting}
  2978. Run the \key{run-tests.rkt} script in the support code to check
  2979. whether the output programs produce the same result as the input
  2980. programs.
  2981. \end{exercise}
  2982. \fi}
  2983. \section{Remove Complex Operands}
  2984. \label{sec:remove-complex-opera-Lvar}
  2985. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2986. into a restricted form in which the arguments of operations are atomic
  2987. expressions. Put another way, this pass removes complex
  2988. operands\index{subject}{complex operand}, such as the expression
  2989. \racket{\code{(- 10)}}\python{\code{-10}}
  2990. in the following program. This is accomplished by introducing a new
  2991. temporary variable, assigning the complex operand to the new
  2992. variable, and then using the new variable in place of the complex
  2993. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2994. right.
  2995. {\if\edition\racketEd
  2996. \begin{transformation}
  2997. % var_test_19.rkt
  2998. \begin{lstlisting}
  2999. (let ([x (+ 42 (- 10))])
  3000. (+ x 10))
  3001. \end{lstlisting}
  3002. \compilesto
  3003. \begin{lstlisting}
  3004. (let ([x (let ([tmp.1 (- 10)])
  3005. (+ 42 tmp.1))])
  3006. (+ x 10))
  3007. \end{lstlisting}
  3008. \end{transformation}
  3009. \fi}
  3010. {\if\edition\pythonEd\pythonColor
  3011. \begin{transformation}
  3012. \begin{lstlisting}
  3013. x = 42 + -10
  3014. print(x + 10)
  3015. \end{lstlisting}
  3016. \compilesto
  3017. \begin{lstlisting}
  3018. tmp_0 = -10
  3019. x = 42 + tmp_0
  3020. tmp_1 = x + 10
  3021. print(tmp_1)
  3022. \end{lstlisting}
  3023. \end{transformation}
  3024. \fi}
  3025. \newcommand{\LvarMonadASTRacket}{
  3026. \begin{array}{rcl}
  3027. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3028. \Exp &::=& \Atm \MID \READ{} \\
  3029. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3030. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3031. \end{array}
  3032. }
  3033. \newcommand{\LvarMonadASTPython}{
  3034. \begin{array}{rcl}
  3035. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3036. \Exp{} &::=& \Atm \MID \READ{} \\
  3037. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3038. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3039. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3040. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3041. \end{array}
  3042. }
  3043. \begin{figure}[tp]
  3044. \centering
  3045. \begin{tcolorbox}[colback=white]
  3046. {\if\edition\racketEd
  3047. \[
  3048. \begin{array}{l}
  3049. \LvarMonadASTRacket \\
  3050. \begin{array}{rcl}
  3051. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3052. \end{array}
  3053. \end{array}
  3054. \]
  3055. \fi}
  3056. {\if\edition\pythonEd\pythonColor
  3057. \[
  3058. \begin{array}{l}
  3059. \LvarMonadASTPython \\
  3060. \begin{array}{rcl}
  3061. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3062. \end{array}
  3063. \end{array}
  3064. \]
  3065. \fi}
  3066. \end{tcolorbox}
  3067. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3068. atomic expressions.}
  3069. \label{fig:Lvar-anf-syntax}
  3070. \end{figure}
  3071. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3072. of this pass, the language \LangVarANF{}. The only difference is that
  3073. operator arguments are restricted to be atomic expressions that are
  3074. defined by the \Atm{} nonterminal. In particular, integer constants
  3075. and variables are atomic.
  3076. The atomic expressions are pure (they do not cause or depend on side
  3077. effects) whereas complex expressions may have side effects, such as
  3078. \READ{}. A language with this separation between pure expressions
  3079. versus expressions with side effects is said to be in monadic normal
  3080. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3081. in the name \LangVarANF{}. An important invariant of the
  3082. \code{remove\_complex\_operands} pass is that the relative ordering
  3083. among complex expressions is not changed, but the relative ordering
  3084. between atomic expressions and complex expressions can change and
  3085. often does. These changes are behavior preserving because
  3086. atomic expressions are pure.
  3087. {\if\edition\racketEd
  3088. Another well-known form for intermediate languages is the
  3089. \emph{administrative normal form}
  3090. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3091. \index{subject}{administrative normal form} \index{subject}{ANF}
  3092. %
  3093. The \LangVarANF{} language is not quite in ANF because it allows the
  3094. right-hand side of a \code{let} to be a complex expression, such as
  3095. another \code{let}. The flattening of nested \code{let} expressions is
  3096. instead one of the responsibilities of the \code{explicate\_control}
  3097. pass.
  3098. \fi}
  3099. {\if\edition\racketEd
  3100. We recommend implementing this pass with two mutually recursive
  3101. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3102. \code{rco\_atom} to subexpressions that need to become atomic and to
  3103. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3104. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3105. returns an expression. The \code{rco\_atom} function returns two
  3106. things: an atomic expression and an alist mapping temporary variables to
  3107. complex subexpressions. You can return multiple things from a function
  3108. using Racket's \key{values} form, and you can receive multiple things
  3109. from a function call using the \key{define-values} form.
  3110. \fi}
  3111. %
  3112. {\if\edition\pythonEd\pythonColor
  3113. %
  3114. We recommend implementing this pass with an auxiliary method named
  3115. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3116. Boolean that specifies whether the expression needs to become atomic
  3117. or not. The \code{rco\_exp} method should return a pair consisting of
  3118. the new expression and a list of pairs, associating new temporary
  3119. variables with their initializing expressions.
  3120. %
  3121. \fi}
  3122. {\if\edition\racketEd
  3123. %
  3124. In the example program with the expression \code{(+ 42 (-
  3125. 10))}, the subexpression \code{(- 10)} should be processed using the
  3126. \code{rco\_atom} function because it is an argument of the \code{+}
  3127. operator and therefore needs to become atomic. The output of
  3128. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3129. \begin{transformation}
  3130. \begin{lstlisting}
  3131. (- 10)
  3132. \end{lstlisting}
  3133. \compilesto
  3134. \begin{lstlisting}
  3135. tmp.1
  3136. ((tmp.1 . (- 10)))
  3137. \end{lstlisting}
  3138. \end{transformation}
  3139. \fi}
  3140. %
  3141. {\if\edition\pythonEd\pythonColor
  3142. %
  3143. Returning to the example program with the expression \code{42 + -10},
  3144. the subexpression \code{-10} should be processed using the
  3145. \code{rco\_exp} function with \code{True} as the second argument,
  3146. because \code{-10} is an argument of the \code{+} operator and
  3147. therefore needs to become atomic. The output of \code{rco\_exp}
  3148. applied to \code{-10} is as follows.
  3149. \begin{transformation}
  3150. \begin{lstlisting}
  3151. -10
  3152. \end{lstlisting}
  3153. \compilesto
  3154. \begin{lstlisting}
  3155. tmp_1
  3156. [(tmp_1, -10)]
  3157. \end{lstlisting}
  3158. \end{transformation}
  3159. %
  3160. \fi}
  3161. Take special care of programs, such as the following, that
  3162. %
  3163. \racket{bind a variable to an atomic expression.}
  3164. %
  3165. \python{assign an atomic expression to a variable.}
  3166. %
  3167. You should leave such \racket{variable bindings}\python{assignments}
  3168. unchanged, as shown in the program on the right:\\
  3169. %
  3170. {\if\edition\racketEd
  3171. \begin{transformation}
  3172. % var_test_20.rkt
  3173. \begin{lstlisting}
  3174. (let ([a 42])
  3175. (let ([b a])
  3176. b))
  3177. \end{lstlisting}
  3178. \compilesto
  3179. \begin{lstlisting}
  3180. (let ([a 42])
  3181. (let ([b a])
  3182. b))
  3183. \end{lstlisting}
  3184. \end{transformation}
  3185. \fi}
  3186. {\if\edition\pythonEd\pythonColor
  3187. \begin{transformation}
  3188. \begin{lstlisting}
  3189. a = 42
  3190. b = a
  3191. print(b)
  3192. \end{lstlisting}
  3193. \compilesto
  3194. \begin{lstlisting}
  3195. a = 42
  3196. b = a
  3197. print(b)
  3198. \end{lstlisting}
  3199. \end{transformation}
  3200. \fi}
  3201. %
  3202. \noindent A careless implementation might produce the following output with
  3203. unnecessary temporary variables.
  3204. \begin{center}
  3205. \begin{minipage}{0.4\textwidth}
  3206. {\if\edition\racketEd
  3207. \begin{lstlisting}
  3208. (let ([tmp.1 42])
  3209. (let ([a tmp.1])
  3210. (let ([tmp.2 a])
  3211. (let ([b tmp.2])
  3212. b))))
  3213. \end{lstlisting}
  3214. \fi}
  3215. {\if\edition\pythonEd\pythonColor
  3216. \begin{lstlisting}
  3217. tmp_1 = 42
  3218. a = tmp_1
  3219. tmp_2 = a
  3220. b = tmp_2
  3221. print(b)
  3222. \end{lstlisting}
  3223. \fi}
  3224. \end{minipage}
  3225. \end{center}
  3226. \begin{exercise}
  3227. \normalfont\normalsize
  3228. {\if\edition\racketEd
  3229. Implement the \code{remove\_complex\_operands} function in
  3230. \code{compiler.rkt}.
  3231. %
  3232. Create three new \LangVar{} programs that exercise the interesting
  3233. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3234. regarding file names described in exercise~\ref{ex:Lvar}.
  3235. %
  3236. In the \code{run-tests.rkt} script, add the following entry to the
  3237. list of \code{passes}, and then run the script to test your compiler.
  3238. \begin{lstlisting}
  3239. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3240. \end{lstlisting}
  3241. In debugging your compiler, it is often useful to see the intermediate
  3242. programs that are output from each pass. To print the intermediate
  3243. programs, place \lstinline{(debug-level 1)} before the call to
  3244. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3245. %
  3246. {\if\edition\pythonEd\pythonColor
  3247. Implement the \code{remove\_complex\_operands} pass in
  3248. \code{compiler.py}, creating auxiliary functions for each
  3249. nonterminal in the grammar, that is, \code{rco\_exp}
  3250. and \code{rco\_stmt}. We recommend that you use the function
  3251. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3252. \fi}
  3253. \end{exercise}
  3254. {\if\edition\pythonEd\pythonColor
  3255. \begin{exercise}
  3256. \normalfont\normalsize
  3257. \label{ex:Lvar}
  3258. Create five \LangVar{} programs that exercise the most interesting
  3259. parts of the \code{remove\_complex\_operands} pass. The five programs
  3260. should be placed in the subdirectory \key{tests/var}, and the file
  3261. names should end with the file extension \key{.py}. Run the
  3262. \key{run-tests.py} script in the support code to check whether the
  3263. output programs produce the same result as the input programs.
  3264. \end{exercise}
  3265. \fi}
  3266. {\if\edition\racketEd
  3267. \section{Explicate Control}
  3268. \label{sec:explicate-control-Lvar}
  3269. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3270. programs that make the order of execution explicit in their
  3271. syntax. For now this amounts to flattening \key{let} constructs into a
  3272. sequence of assignment statements. For example, consider the following
  3273. \LangVar{} program:\\
  3274. % var_test_11.rkt
  3275. \begin{minipage}{0.96\textwidth}
  3276. \begin{lstlisting}
  3277. (let ([y (let ([x 20])
  3278. (+ x (let ([x 22]) x)))])
  3279. y)
  3280. \end{lstlisting}
  3281. \end{minipage}\\
  3282. %
  3283. The output of the previous pass is shown next, on the left, and the
  3284. output of \code{explicate\_control} is on the right. Recall that the
  3285. right-hand side of a \key{let} executes before its body, so that the order
  3286. of evaluation for this program is to assign \code{20} to \code{x.1},
  3287. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3288. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3289. this ordering explicit.
  3290. \begin{transformation}
  3291. \begin{lstlisting}
  3292. (let ([y (let ([x.1 20])
  3293. (let ([x.2 22])
  3294. (+ x.1 x.2)))])
  3295. y)
  3296. \end{lstlisting}
  3297. \compilesto
  3298. \begin{lstlisting}[language=C]
  3299. start:
  3300. x.1 = 20;
  3301. x.2 = 22;
  3302. y = (+ x.1 x.2);
  3303. return y;
  3304. \end{lstlisting}
  3305. \end{transformation}
  3306. \begin{figure}[tbp]
  3307. \begin{tcolorbox}[colback=white]
  3308. \begin{lstlisting}
  3309. (define (explicate_tail e)
  3310. (match e
  3311. [(Var x) ___]
  3312. [(Int n) (Return (Int n))]
  3313. [(Let x rhs body) ___]
  3314. [(Prim op es) ___]
  3315. [else (error "explicate_tail unhandled case" e)]))
  3316. (define (explicate_assign e x cont)
  3317. (match e
  3318. [(Var x) ___]
  3319. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3320. [(Let y rhs body) ___]
  3321. [(Prim op es) ___]
  3322. [else (error "explicate_assign unhandled case" e)]))
  3323. (define (explicate_control p)
  3324. (match p
  3325. [(Program info body) ___]))
  3326. \end{lstlisting}
  3327. \end{tcolorbox}
  3328. \caption{Skeleton for the \code{explicate\_control} pass.}
  3329. \label{fig:explicate-control-Lvar}
  3330. \end{figure}
  3331. The organization of this pass depends on the notion of tail position
  3332. to which we have alluded. Here is the definition.
  3333. \begin{definition}\normalfont
  3334. The following rules define when an expression is in \emph{tail
  3335. position}\index{subject}{tail position} for the language \LangVar{}.
  3336. \begin{enumerate}
  3337. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3338. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3339. \end{enumerate}
  3340. \end{definition}
  3341. We recommend implementing \code{explicate\_control} using two
  3342. recursive functions, \code{explicate\_tail} and
  3343. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3344. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3345. function should be applied to expressions in tail position, whereas the
  3346. \code{explicate\_assign} should be applied to expressions that occur on
  3347. the right-hand side of a \key{let}.
  3348. %
  3349. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3350. input and produces a \Tail{} in \LangCVar{} (see
  3351. figure~\ref{fig:c0-syntax}).
  3352. %
  3353. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3354. the variable to which it is to be assigned, and a \Tail{} in
  3355. \LangCVar{} for the code that comes after the assignment. The
  3356. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3357. The \code{explicate\_assign} function is in accumulator-passing style:
  3358. the \code{cont} parameter is used for accumulating the output. This
  3359. accumulator-passing style plays an important role in the way that we
  3360. generate high-quality code for conditional expressions in
  3361. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3362. continuation because it contains the generated code that should come
  3363. after the current assignment. This code organization is also related
  3364. to continuation-passing style, except that \code{cont} is not what
  3365. happens next during compilation but is what happens next in the
  3366. generated code.
  3367. \begin{exercise}\normalfont\normalsize
  3368. %
  3369. Implement the \code{explicate\_control} function in
  3370. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3371. exercise the code in \code{explicate\_control}.
  3372. %
  3373. In the \code{run-tests.rkt} script, add the following entry to the
  3374. list of \code{passes} and then run the script to test your compiler.
  3375. \begin{lstlisting}
  3376. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3377. \end{lstlisting}
  3378. \end{exercise}
  3379. \fi}
  3380. \section{Select Instructions}
  3381. \label{sec:select-Lvar}
  3382. \index{subject}{select instructions}
  3383. In the \code{select\_instructions} pass we begin the work of
  3384. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3385. language of this pass is a variant of x86 that still uses variables,
  3386. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3387. nonterminal of the \LangXInt{} abstract syntax
  3388. (figure~\ref{fig:x86-int-ast}).
  3389. \racket{We recommend implementing the
  3390. \code{select\_instructions} with three auxiliary functions, one for
  3391. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3392. $\Tail$.}
  3393. \python{We recommend implementing an auxiliary function
  3394. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3395. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3396. same and integer constants change to immediates; that is, $\INT{n}$
  3397. changes to $\IMM{n}$.}
  3398. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3399. arithmetic operations. For example, consider the following addition
  3400. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3401. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3402. \key{addq} instruction in x86, but it performs an in-place update.
  3403. %
  3404. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3405. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3406. \begin{transformation}
  3407. {\if\edition\racketEd
  3408. \begin{lstlisting}
  3409. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3410. \end{lstlisting}
  3411. \fi}
  3412. {\if\edition\pythonEd\pythonColor
  3413. \begin{lstlisting}
  3414. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3415. \end{lstlisting}
  3416. \fi}
  3417. \compilesto
  3418. \begin{lstlisting}
  3419. movq |$\Arg_1$|, %rax
  3420. addq |$\Arg_2$|, %rax
  3421. movq %rax, |$\itm{var}$|
  3422. \end{lstlisting}
  3423. \end{transformation}
  3424. %
  3425. However, with some care we can generate shorter sequences of
  3426. instructions. Suppose that one or more of the arguments of the
  3427. addition is the same variable as the left-hand side of the assignment.
  3428. Then the assignment statement can be translated into a single
  3429. \key{addq} instruction, as follows.
  3430. \begin{transformation}
  3431. {\if\edition\racketEd
  3432. \begin{lstlisting}
  3433. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3434. \end{lstlisting}
  3435. \fi}
  3436. {\if\edition\pythonEd\pythonColor
  3437. \begin{lstlisting}
  3438. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3439. \end{lstlisting}
  3440. \fi}
  3441. \compilesto
  3442. \begin{lstlisting}
  3443. addq |$\Arg_1$|, |$\itm{var}$|
  3444. \end{lstlisting}
  3445. \end{transformation}
  3446. %
  3447. On the other hand, if $\Atm_1$ is not the same variable as the
  3448. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3449. and then add $\Arg_2$ to \itm{var}.
  3450. %
  3451. \begin{transformation}
  3452. {\if\edition\racketEd
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3455. \end{lstlisting}
  3456. \fi}
  3457. {\if\edition\pythonEd\pythonColor
  3458. \begin{lstlisting}
  3459. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3460. \end{lstlisting}
  3461. \fi}
  3462. \compilesto
  3463. \begin{lstlisting}
  3464. movq |$\Arg_1$|, |$\itm{var}$|
  3465. addq |$\Arg_2$|, |$\itm{var}$|
  3466. \end{lstlisting}
  3467. \end{transformation}
  3468. The \READOP{} operation does not have a direct counterpart in x86
  3469. assembly, so we provide this functionality with the function
  3470. \code{read\_int} in the file \code{runtime.c}, written in
  3471. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3472. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3473. system}, or simply the \emph{runtime} for short. When compiling your
  3474. generated x86 assembly code, you need to compile \code{runtime.c} to
  3475. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3476. \code{-c}) and link it into the executable. For our purposes of code
  3477. generation, all you need to do is translate an assignment of
  3478. \READOP{} into a call to the \code{read\_int} function followed by a
  3479. move from \code{rax} to the left-hand side variable. (The
  3480. return value of a function is placed in \code{rax}.)
  3481. \begin{transformation}
  3482. {\if\edition\racketEd
  3483. \begin{lstlisting}
  3484. |$\itm{var}$| = (read);
  3485. \end{lstlisting}
  3486. \fi}
  3487. {\if\edition\pythonEd\pythonColor
  3488. \begin{lstlisting}
  3489. |$\itm{var}$| = input_int();
  3490. \end{lstlisting}
  3491. \fi}
  3492. \compilesto
  3493. \begin{lstlisting}
  3494. callq read_int
  3495. movq %rax, |$\itm{var}$|
  3496. \end{lstlisting}
  3497. \end{transformation}
  3498. {\if\edition\pythonEd\pythonColor
  3499. %
  3500. Similarly, we translate the \code{print} operation, shown below, into
  3501. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3502. In x86, the first six arguments to functions are passed in registers,
  3503. with the first argument passed in register \code{rdi}. So we move the
  3504. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3505. \code{callq} instruction.
  3506. \begin{transformation}
  3507. \begin{lstlisting}
  3508. print(|$\Atm$|)
  3509. \end{lstlisting}
  3510. \compilesto
  3511. \begin{lstlisting}
  3512. movq |$\Arg$|, %rdi
  3513. callq print_int
  3514. \end{lstlisting}
  3515. \end{transformation}
  3516. %
  3517. \fi}
  3518. {\if\edition\racketEd
  3519. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3520. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3521. assignment to the \key{rax} register followed by a jump to the
  3522. conclusion of the program (so the conclusion needs to be labeled).
  3523. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3524. recursively and then append the resulting instructions.
  3525. \fi}
  3526. {\if\edition\pythonEd\pythonColor
  3527. We recommend that you use the function \code{utils.label\_name} to
  3528. transform strings into labels, for example, in
  3529. the target of the \code{callq} instruction. This practice makes your
  3530. compiler portable across Linux and Mac OS X, which requires an underscore
  3531. prefixed to all labels.
  3532. \fi}
  3533. \begin{exercise}
  3534. \normalfont\normalsize
  3535. {\if\edition\racketEd
  3536. Implement the \code{select\_instructions} pass in
  3537. \code{compiler.rkt}. Create three new example programs that are
  3538. designed to exercise all the interesting cases in this pass.
  3539. %
  3540. In the \code{run-tests.rkt} script, add the following entry to the
  3541. list of \code{passes} and then run the script to test your compiler.
  3542. \begin{lstlisting}
  3543. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3544. \end{lstlisting}
  3545. \fi}
  3546. {\if\edition\pythonEd\pythonColor
  3547. Implement the \key{select\_instructions} pass in
  3548. \code{compiler.py}. Create three new example programs that are
  3549. designed to exercise all the interesting cases in this pass.
  3550. Run the \code{run-tests.py} script to check
  3551. whether the output programs produce the same result as the input
  3552. programs.
  3553. \fi}
  3554. \end{exercise}
  3555. \section{Assign Homes}
  3556. \label{sec:assign-Lvar}
  3557. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3558. \LangXVar{} programs that no longer use program variables. Thus, the
  3559. \code{assign\_homes} pass is responsible for placing all the program
  3560. variables in registers or on the stack. For runtime efficiency, it is
  3561. better to place variables in registers, but because there are only
  3562. sixteen registers, some programs must necessarily resort to placing
  3563. some variables on the stack. In this chapter we focus on the mechanics
  3564. of placing variables on the stack. We study an algorithm for placing
  3565. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3566. Consider again the following \LangVar{} program from
  3567. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3568. % var_test_20.rkt
  3569. \begin{minipage}{0.96\textwidth}
  3570. {\if\edition\racketEd
  3571. \begin{lstlisting}
  3572. (let ([a 42])
  3573. (let ([b a])
  3574. b))
  3575. \end{lstlisting}
  3576. \fi}
  3577. {\if\edition\pythonEd\pythonColor
  3578. \begin{lstlisting}
  3579. a = 42
  3580. b = a
  3581. print(b)
  3582. \end{lstlisting}
  3583. \fi}
  3584. \end{minipage}\\
  3585. %
  3586. The output of \code{select\_instructions} is shown next, on the left,
  3587. and the output of \code{assign\_homes} is on the right. In this
  3588. example, we assign variable \code{a} to stack location
  3589. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3590. \begin{transformation}
  3591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3592. movq $42, a
  3593. movq a, b
  3594. movq b, %rax
  3595. \end{lstlisting}
  3596. \compilesto
  3597. %stack-space: 16
  3598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3599. movq $42, -8(%rbp)
  3600. movq -8(%rbp), -16(%rbp)
  3601. movq -16(%rbp), %rax
  3602. \end{lstlisting}
  3603. \end{transformation}
  3604. \racket{
  3605. The \code{assign\_homes} pass should replace all variables
  3606. with stack locations.
  3607. The list of variables can be obtained from
  3608. the \code{locals-types} entry in the $\itm{info}$ of the
  3609. \code{X86Program} node. The \code{locals-types} entry is an alist
  3610. mapping all the variables in the program to their types
  3611. (for now, just \code{Integer}).
  3612. As an aside, the \code{locals-types} entry is
  3613. computed by \code{type-check-Cvar} in the support code, which
  3614. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3615. which you should propagate to the \code{X86Program} node.}
  3616. %
  3617. \python{The \code{assign\_homes} pass should replace all uses of
  3618. variables with stack locations.}
  3619. %
  3620. In the process of assigning variables to stack locations, it is
  3621. convenient for you to compute and store the size of the frame (in
  3622. bytes) in
  3623. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3624. %
  3625. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3626. %
  3627. which is needed later to generate the conclusion of the \code{main}
  3628. procedure. The x86-64 standard requires the frame size to be a
  3629. multiple of 16 bytes.\index{subject}{frame}
  3630. % TODO: store the number of variables instead? -Jeremy
  3631. \begin{exercise}\normalfont\normalsize
  3632. Implement the \code{assign\_homes} pass in
  3633. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3634. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3635. grammar. We recommend that the auxiliary functions take an extra
  3636. parameter that maps variable names to homes (stack locations for now).
  3637. %
  3638. {\if\edition\racketEd
  3639. In the \code{run-tests.rkt} script, add the following entry to the
  3640. list of \code{passes} and then run the script to test your compiler.
  3641. \begin{lstlisting}
  3642. (list "assign homes" assign-homes interp_x86-0)
  3643. \end{lstlisting}
  3644. \fi}
  3645. {\if\edition\pythonEd\pythonColor
  3646. Run the \code{run-tests.py} script to check
  3647. whether the output programs produce the same result as the input
  3648. programs.
  3649. \fi}
  3650. \end{exercise}
  3651. \section{Patch Instructions}
  3652. \label{sec:patch-s0}
  3653. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3654. \LangXInt{} by making sure that each instruction adheres to the
  3655. restriction that at most one argument of an instruction may be a
  3656. memory reference.
  3657. We return to the following example.\\
  3658. \begin{minipage}{0.5\textwidth}
  3659. % var_test_20.rkt
  3660. {\if\edition\racketEd
  3661. \begin{lstlisting}
  3662. (let ([a 42])
  3663. (let ([b a])
  3664. b))
  3665. \end{lstlisting}
  3666. \fi}
  3667. {\if\edition\pythonEd\pythonColor
  3668. \begin{lstlisting}
  3669. a = 42
  3670. b = a
  3671. print(b)
  3672. \end{lstlisting}
  3673. \fi}
  3674. \end{minipage}\\
  3675. The \code{assign\_homes} pass produces the following translation. \\
  3676. \begin{minipage}{0.5\textwidth}
  3677. {\if\edition\racketEd
  3678. \begin{lstlisting}
  3679. movq $42, -8(%rbp)
  3680. movq -8(%rbp), -16(%rbp)
  3681. movq -16(%rbp), %rax
  3682. \end{lstlisting}
  3683. \fi}
  3684. {\if\edition\pythonEd\pythonColor
  3685. \begin{lstlisting}
  3686. movq $42, -8(%rbp)
  3687. movq -8(%rbp), -16(%rbp)
  3688. movq -16(%rbp), %rdi
  3689. callq print_int
  3690. \end{lstlisting}
  3691. \fi}
  3692. \end{minipage}\\
  3693. The second \key{movq} instruction is problematic because both
  3694. arguments are stack locations. We suggest fixing this problem by
  3695. moving from the source location to the register \key{rax} and then
  3696. from \key{rax} to the destination location, as follows.
  3697. \begin{lstlisting}
  3698. movq -8(%rbp), %rax
  3699. movq %rax, -16(%rbp)
  3700. \end{lstlisting}
  3701. There is a similar corner case that also needs to be dealt with. If
  3702. one argument is an immediate integer larger than $2^{16}$ and the
  3703. other is a memory reference, then the instruction is invalid. One can
  3704. fix this, for example, by first moving the immediate integer into
  3705. \key{rax} and then using \key{rax} in place of the integer.
  3706. \begin{exercise}
  3707. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3708. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3709. Create three new example programs that are
  3710. designed to exercise all the interesting cases in this pass.
  3711. %
  3712. {\if\edition\racketEd
  3713. In the \code{run-tests.rkt} script, add the following entry to the
  3714. list of \code{passes} and then run the script to test your compiler.
  3715. \begin{lstlisting}
  3716. (list "patch instructions" patch_instructions interp_x86-0)
  3717. \end{lstlisting}
  3718. \fi}
  3719. {\if\edition\pythonEd\pythonColor
  3720. Run the \code{run-tests.py} script to check
  3721. whether the output programs produce the same result as the input
  3722. programs.
  3723. \fi}
  3724. \end{exercise}
  3725. \section{Generate Prelude and Conclusion}
  3726. \label{sec:print-x86}
  3727. \index{subject}{prelude}\index{subject}{conclusion}
  3728. The last step of the compiler from \LangVar{} to x86 is to generate
  3729. the \code{main} function with a prelude and conclusion wrapped around
  3730. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3731. discussed in section~\ref{sec:x86}.
  3732. When running on Mac OS X, your compiler should prefix an underscore to
  3733. all labels (for example, changing \key{main} to \key{\_main}).
  3734. %
  3735. \racket{The Racket call \code{(system-type 'os)} is useful for
  3736. determining which operating system the compiler is running on. It
  3737. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3738. %
  3739. \python{The Python \code{platform.system}
  3740. function returns \code{\textquotesingle Linux\textquotesingle},
  3741. \code{\textquotesingle Windows\textquotesingle}, or
  3742. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3743. \begin{exercise}\normalfont\normalsize
  3744. %
  3745. Implement the \key{prelude\_and\_conclusion} pass in
  3746. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3747. %
  3748. {\if\edition\racketEd
  3749. In the \code{run-tests.rkt} script, add the following entry to the
  3750. list of \code{passes} and then run the script to test your compiler.
  3751. \begin{lstlisting}
  3752. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3753. \end{lstlisting}
  3754. %
  3755. Uncomment the call to the \key{compiler-tests} function
  3756. (appendix~\ref{appendix:utilities}), which tests your complete
  3757. compiler by executing the generated x86 code. It translates the x86
  3758. AST that you produce into a string by invoking the \code{print-x86}
  3759. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3760. the provided \key{runtime.c} file to \key{runtime.o} using
  3761. \key{gcc}. Run the script to test your compiler.
  3762. %
  3763. \fi}
  3764. {\if\edition\pythonEd\pythonColor
  3765. %
  3766. Run the \code{run-tests.py} script to check whether the output
  3767. programs produce the same result as the input programs. That script
  3768. translates the x86 AST that you produce into a string by invoking the
  3769. \code{repr} method that is implemented by the x86 AST classes in
  3770. \code{x86\_ast.py}.
  3771. %
  3772. \fi}
  3773. \end{exercise}
  3774. \section{Challenge: Partial Evaluator for \LangVar{}}
  3775. \label{sec:pe-Lvar}
  3776. \index{subject}{partialevaluation@partial evaluation}
  3777. This section describes two optional challenge exercises that involve
  3778. adapting and improving the partial evaluator for \LangInt{} that was
  3779. introduced in section~\ref{sec:partial-evaluation}.
  3780. \begin{exercise}\label{ex:pe-Lvar}
  3781. \normalfont\normalsize
  3782. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3783. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3784. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3785. %
  3786. \racket{\key{let} binding}\python{assignment}
  3787. %
  3788. to the \LangInt{} language, so you will need to add cases for them in
  3789. the \code{pe\_exp}
  3790. %
  3791. \racket{function.}
  3792. %
  3793. \python{and \code{pe\_stmt} functions.}
  3794. %
  3795. Once complete, add the partial evaluation pass to the front of your
  3796. compiler, and check that your compiler still passes all the
  3797. tests.
  3798. \end{exercise}
  3799. \begin{exercise}
  3800. \normalfont\normalsize
  3801. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3802. \code{pe\_add} auxiliary functions with functions that know more about
  3803. arithmetic. For example, your partial evaluator should translate
  3804. {\if\edition\racketEd
  3805. \[
  3806. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3807. \code{(+ 2 (read))}
  3808. \]
  3809. \fi}
  3810. {\if\edition\pythonEd\pythonColor
  3811. \[
  3812. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3813. \code{2 + input\_int()}
  3814. \]
  3815. \fi}
  3816. %
  3817. To accomplish this, the \code{pe\_exp} function should produce output
  3818. in the form of the $\itm{residual}$ nonterminal of the following
  3819. grammar. The idea is that when processing an addition expression, we
  3820. can always produce one of the following: (1) an integer constant, (2)
  3821. an addition expression with an integer constant on the left-hand side
  3822. but not the right-hand side, or (3) an addition expression in which
  3823. neither subexpression is a constant.
  3824. %
  3825. {\if\edition\racketEd
  3826. \[
  3827. \begin{array}{lcl}
  3828. \itm{inert} &::=& \Var
  3829. \MID \LP\key{read}\RP
  3830. \MID \LP\key{-} ~\Var\RP
  3831. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3832. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3833. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3834. \itm{residual} &::=& \Int
  3835. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3836. \MID \itm{inert}
  3837. \end{array}
  3838. \]
  3839. \fi}
  3840. {\if\edition\pythonEd\pythonColor
  3841. \[
  3842. \begin{array}{lcl}
  3843. \itm{inert} &::=& \Var
  3844. \MID \key{input\_int}\LP\RP
  3845. \MID \key{-} \Var
  3846. \MID \key{-} \key{input\_int}\LP\RP
  3847. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3848. \itm{residual} &::=& \Int
  3849. \MID \Int ~ \key{+} ~ \itm{inert}
  3850. \MID \itm{inert}
  3851. \end{array}
  3852. \]
  3853. \fi}
  3854. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3855. inputs are $\itm{residual}$ expressions and they should return
  3856. $\itm{residual}$ expressions. Once the improvements are complete,
  3857. make sure that your compiler still passes all the tests. After
  3858. all, fast code is useless if it produces incorrect results!
  3859. \end{exercise}
  3860. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3861. {\if\edition\pythonEd\pythonColor
  3862. \chapter{Parsing}
  3863. \label{ch:parsing}
  3864. \setcounter{footnote}{0}
  3865. \index{subject}{parsing}
  3866. In this chapter we learn how to use the Lark parser
  3867. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3868. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3869. You are then asked to create a parser for \LangVar{} using Lark.
  3870. We also describe the parsing algorithms used inside Lark, studying the
  3871. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3872. A parser framework such as Lark takes in a specification of the
  3873. concrete syntax and an input program and produces a parse tree. Even
  3874. though a parser framework does most of the work for us, using one
  3875. properly requires some knowledge. In particular, we must learn about
  3876. its specification languages and we must learn how to deal with
  3877. ambiguity in our language specifications. Also, some algorithms, such
  3878. as LALR(1), place restrictions on the grammars they can handle, in
  3879. which case knowing the algorithm helps with trying to decipher the
  3880. error messages.
  3881. The process of parsing is traditionally subdivided into two phases:
  3882. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3883. analysis} (also called parsing). The lexical analysis phase
  3884. translates the sequence of characters into a sequence of
  3885. \emph{tokens}, that is, words consisting of several characters. The
  3886. parsing phase organizes the tokens into a \emph{parse tree} that
  3887. captures how the tokens were matched by rules in the grammar of the
  3888. language. The reason for the subdivision into two phases is to enable
  3889. the use of a faster but less powerful algorithm for lexical analysis
  3890. and the use of a slower but more powerful algorithm for parsing.
  3891. %
  3892. %% Likewise, parser generators typical come in pairs, with separate
  3893. %% generators for the lexical analyzer (or lexer for short) and for the
  3894. %% parser. A particularly influential pair of generators were
  3895. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3896. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3897. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3898. %% Compiler Compiler.
  3899. %
  3900. The Lark parser framework that we use in this chapter includes both
  3901. lexical analyzers and parsers. The next section discusses lexical
  3902. analysis, and the remainder of the chapter discusses parsing.
  3903. \section{Lexical Analysis and Regular Expressions}
  3904. \label{sec:lex}
  3905. The lexical analyzers produced by Lark turn a sequence of characters
  3906. (a string) into a sequence of token objects. For example, a Lark
  3907. generated lexer for \LangInt{} converts the string
  3908. \begin{lstlisting}
  3909. 'print(1 + 3)'
  3910. \end{lstlisting}
  3911. \noindent into the following sequence of token objects:
  3912. \begin{center}
  3913. \begin{minipage}{0.95\textwidth}
  3914. \begin{lstlisting}
  3915. Token('PRINT', 'print')
  3916. Token('LPAR', '(')
  3917. Token('INT', '1')
  3918. Token('PLUS', '+')
  3919. Token('INT', '3')
  3920. Token('RPAR', ')')
  3921. Token('NEWLINE', '\n')
  3922. \end{lstlisting}
  3923. \end{minipage}
  3924. \end{center}
  3925. Each token includes a field for its \code{type}, such as \skey{INT},
  3926. and a field for its \code{value}, such as \skey{1}.
  3927. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3928. specification language for Lark's lexer is one regular expression for
  3929. each type of token. The term \emph{regular} comes from the term
  3930. \emph{regular languages}, which are the languages that can be
  3931. recognized by a finite state machine. A \emph{regular expression} is a
  3932. pattern formed of the following core elements:\index{subject}{regular
  3933. expression}\footnote{Regular expressions traditionally include the
  3934. empty regular expression that matches any zero-length part of a
  3935. string, but Lark does not support the empty regular expression.}
  3936. \begin{itemize}
  3937. \item A single character $c$ is a regular expression, and it matches
  3938. only itself. For example, the regular expression \code{a} matches
  3939. only the string \skey{a}.
  3940. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3941. R_2$ form a regular expression that matches any string that matches
  3942. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3943. matches the string \skey{a} and the string \skey{c}.
  3944. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3945. expression that matches any string that can be formed by
  3946. concatenating two strings, where the first string matches $R_1$ and
  3947. the second string matches $R_2$. For example, the regular expression
  3948. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3949. (Parentheses can be used to control the grouping of operators within
  3950. a regular expression.)
  3951. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3952. Kleene closure) is a regular expression that matches any string that
  3953. can be formed by concatenating zero or more strings that each match
  3954. the regular expression $R$. For example, the regular expression
  3955. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3956. \skey{abc}.
  3957. \end{itemize}
  3958. For our convenience, Lark also accepts the following extended set of
  3959. regular expressions that are automatically translated into the core
  3960. regular expressions.
  3961. \begin{itemize}
  3962. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3963. c_n]$ is a regular expression that matches any one of the
  3964. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3965. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3966. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3967. a regular expression that matches any character between $c_1$ and
  3968. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3969. letter in the alphabet.
  3970. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3971. is a regular expression that matches any string that can
  3972. be formed by concatenating one or more strings that each match $R$.
  3973. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3974. matches \skey{b} and \skey{bzca}.
  3975. \item A regular expression followed by a question mark $R\ttm{?}$
  3976. is a regular expression that matches any string that either
  3977. matches $R$ or is the empty string.
  3978. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3979. \end{itemize}
  3980. In a Lark grammar file, each kind of token is specified by a
  3981. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  3982. that consists of the name of the terminal followed by a colon followed
  3983. by a sequence of literals. The literals include strings such as
  3984. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  3985. terminal names, and literals composed using the regular expression
  3986. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  3987. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  3988. \begin{center}
  3989. \begin{minipage}{0.95\textwidth}
  3990. \begin{lstlisting}
  3991. DIGIT: /[0-9]/
  3992. INT: "-"? DIGIT+
  3993. NEWLINE: (/\r/? /\n/)+
  3994. \end{lstlisting}
  3995. \end{minipage}
  3996. \end{center}
  3997. \section{Grammars and Parse Trees}
  3998. \label{sec:CFG}
  3999. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4000. specify the abstract syntax of a language. We now take a closer look
  4001. at using grammar rules to specify the concrete syntax. Recall that
  4002. each rule has a left-hand side and a right-hand side, where the
  4003. left-hand side is a nonterminal and the right-hand side is a pattern
  4004. that defines what can be parsed as that nonterminal. For concrete
  4005. syntax, each right-hand side expresses a pattern for a string instead
  4006. of a pattern for an abstract syntax tree. In particular, each
  4007. right-hand side is a sequence of
  4008. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4009. terminal or a nonterminal. The nonterminals play the same role as in
  4010. the abstract syntax, defining categories of syntax. The nonterminals
  4011. of a grammar include the tokens defined in the lexer and all the
  4012. nonterminals defined by the grammar rules.
  4013. As an example, let us take a closer look at the concrete syntax of the
  4014. \LangInt{} language, repeated here.
  4015. \[
  4016. \begin{array}{l}
  4017. \LintGrammarPython \\
  4018. \begin{array}{rcl}
  4019. \LangInt{} &::=& \Stmt^{*}
  4020. \end{array}
  4021. \end{array}
  4022. \]
  4023. The Lark syntax for grammar rules differs slightly from the variant of
  4024. BNF that we use in this book. In particular, the notation $::=$ is
  4025. replaced by a single colon, and the use of typewriter font for string
  4026. literals is replaced by quotation marks. The following grammar serves
  4027. as a first draft of a Lark grammar for \LangInt{}.
  4028. \begin{center}
  4029. \begin{minipage}{0.95\textwidth}
  4030. \begin{lstlisting}[escapechar=$]
  4031. exp: INT
  4032. | "input_int" "(" ")"
  4033. | "-" exp
  4034. | exp "+" exp
  4035. | exp "-" exp
  4036. | "(" exp ")"
  4037. stmt_list:
  4038. | stmt NEWLINE stmt_list
  4039. lang_int: stmt_list
  4040. \end{lstlisting}
  4041. \end{minipage}
  4042. \end{center}
  4043. Let us begin by discussing the rule \code{exp: INT}, which says that
  4044. if the lexer matches a string to \code{INT}, then the parser also
  4045. categorizes the string as an \code{exp}. Recall that in
  4046. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4047. nonterminal with a sentence in English. Here we specify \code{INT}
  4048. more formally using a type of token \code{INT} and its regular
  4049. expression \code{"-"? DIGIT+}.
  4050. The rule \code{exp: exp "+" exp} says that any string that matches
  4051. \code{exp}, followed by the \code{+} character, followed by another
  4052. string that matches \code{exp}, is itself an \code{exp}. For example,
  4053. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4054. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4055. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4056. \code{exp}. We can visualize the application of grammar rules to parse
  4057. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4058. internal node in the tree is an application of a grammar rule and is
  4059. labeled with its left-hand side nonterminal. Each leaf node is a
  4060. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4061. shown in figure~\ref{fig:simple-parse-tree}.
  4062. \begin{figure}[tbp]
  4063. \begin{tcolorbox}[colback=white]
  4064. \centering
  4065. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4066. \end{tcolorbox}
  4067. \caption{The parse tree for \lstinline{'1+3'}.}
  4068. \label{fig:simple-parse-tree}
  4069. \end{figure}
  4070. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4071. following parse tree as represented by \code{Tree} and \code{Token}
  4072. objects.
  4073. \begin{lstlisting}
  4074. Tree('lang_int',
  4075. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4076. Tree('exp', [Token('INT', '3')])])]),
  4077. Token('NEWLINE', '\n')])
  4078. \end{lstlisting}
  4079. The nodes that come from the lexer are \code{Token} objects, whereas
  4080. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4081. object has a \code{data} field containing the name of the nonterminal
  4082. for the grammar rule that was applied. Each \code{Tree} object also
  4083. has a \code{children} field that is a list containing trees and/or
  4084. tokens. Note that Lark does not produce nodes for string literals in
  4085. the grammar. For example, the \code{Tree} node for the addition
  4086. expression has only two children for the two integers but is missing
  4087. its middle child for the \code{"+"} terminal. This would be
  4088. problematic except that Lark provides a mechanism for customizing the
  4089. \code{data} field of each \code{Tree} node on the basis of which rule was
  4090. applied. Next to each alternative in a grammar rule, write \code{->}
  4091. followed by a string that you want to appear in the \code{data}
  4092. field. The following is a second draft of a Lark grammar for
  4093. \LangInt{}, this time with more specific labels on the \code{Tree}
  4094. nodes.
  4095. \begin{center}
  4096. \begin{minipage}{0.95\textwidth}
  4097. \begin{lstlisting}[escapechar=$]
  4098. exp: INT -> int
  4099. | "input_int" "(" ")" -> input_int
  4100. | "-" exp -> usub
  4101. | exp "+" exp -> add
  4102. | exp "-" exp -> sub
  4103. | "(" exp ")" -> paren
  4104. stmt: "print" "(" exp ")" -> print
  4105. | exp -> expr
  4106. stmt_list: -> empty_stmt
  4107. | stmt NEWLINE stmt_list -> add_stmt
  4108. lang_int: stmt_list -> module
  4109. \end{lstlisting}
  4110. \end{minipage}
  4111. \end{center}
  4112. Here is the resulting parse tree.
  4113. \begin{lstlisting}
  4114. Tree('module',
  4115. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4116. Tree('int', [Token('INT', '3')])])]),
  4117. Token('NEWLINE', '\n')])
  4118. \end{lstlisting}
  4119. \section{Ambiguous Grammars}
  4120. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4121. can be parsed in more than one way. For example, consider the string
  4122. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4123. our draft grammar, resulting in the two parse trees shown in
  4124. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4125. interpreting the second parse tree would yield \code{-4} even through
  4126. the correct answer is \code{2}.
  4127. \begin{figure}[tbp]
  4128. \begin{tcolorbox}[colback=white]
  4129. \centering
  4130. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4131. \end{tcolorbox}
  4132. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4133. \label{fig:ambig-parse-tree}
  4134. \end{figure}
  4135. To deal with this problem we can change the grammar by categorizing
  4136. the syntax in a more fine-grained fashion. In this case we want to
  4137. disallow the application of the rule \code{exp: exp "-" exp} when the
  4138. child on the right is an addition. To do this we can replace the
  4139. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4140. the expressions except for addition, as in the following.
  4141. \begin{center}
  4142. \begin{minipage}{0.95\textwidth}
  4143. \begin{lstlisting}[escapechar=$]
  4144. exp: exp "-" exp_no_add -> sub
  4145. | exp "+" exp -> add
  4146. | exp_no_add
  4147. exp_no_add: INT -> int
  4148. | "input_int" "(" ")" -> input_int
  4149. | "-" exp -> usub
  4150. | exp "-" exp_no_add -> sub
  4151. | "(" exp ")" -> paren
  4152. \end{lstlisting}
  4153. \end{minipage}
  4154. \end{center}
  4155. However, there remains some ambiguity in the grammar. For example, the
  4156. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4157. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4158. (incorrect). That is, subtraction is left associative. Likewise,
  4159. addition in Python is left associative. We also need to consider the
  4160. interaction of unary subtraction with both addition and
  4161. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4162. has higher \emph{precedence}\index{subject}{precedence} than addition
  4163. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4164. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4165. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4166. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4167. all the other expressions, and it uses \code{exp\_hi} for the second
  4168. child in the rules for addition and subtraction. Furthermore, unary
  4169. subtraction uses \code{exp\_hi} for its child.
  4170. For languages with more operators and more precedence levels, one must
  4171. refine the \code{exp} nonterminal into several nonterminals, one for
  4172. each precedence level.
  4173. \begin{figure}[tbp]
  4174. \begin{tcolorbox}[colback=white]
  4175. \centering
  4176. \begin{lstlisting}[escapechar=$]
  4177. exp: exp "+" exp_hi -> add
  4178. | exp "-" exp_hi -> sub
  4179. | exp_hi
  4180. exp_hi: INT -> int
  4181. | "input_int" "(" ")" -> input_int
  4182. | "-" exp_hi -> usub
  4183. | "(" exp ")" -> paren
  4184. stmt: "print" "(" exp ")" -> print
  4185. | exp -> expr
  4186. stmt_list: -> empty_stmt
  4187. | stmt NEWLINE stmt_list -> add_stmt
  4188. lang_int: stmt_list -> module
  4189. \end{lstlisting}
  4190. \end{tcolorbox}
  4191. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4192. \label{fig:Lint-lark-grammar}
  4193. \end{figure}
  4194. \section{From Parse Trees to Abstract Syntax Trees}
  4195. As we have seen, the output of a Lark parser is a parse tree, that is,
  4196. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4197. step is to convert the parse tree to an abstract syntax tree. This can
  4198. be accomplished with a recursive function that inspects the
  4199. \code{data} field of each node and then constructs the corresponding
  4200. AST node, using recursion to handle its children. The following is an
  4201. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4202. \begin{center}
  4203. \begin{minipage}{0.95\textwidth}
  4204. \begin{lstlisting}
  4205. def parse_tree_to_ast(e):
  4206. if e.data == 'int':
  4207. return Constant(int(e.children[0].value))
  4208. elif e.data == 'input_int':
  4209. return Call(Name('input_int'), [])
  4210. elif e.data == 'add':
  4211. e1, e2 = e.children
  4212. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4213. ...
  4214. else:
  4215. raise Exception('unhandled parse tree', e)
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. \end{center}
  4219. \begin{exercise}
  4220. \normalfont\normalsize
  4221. %
  4222. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4223. default parsing algorithm (Earley) with the \code{ambiguity} option
  4224. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4225. output will include multiple parse trees that will indicate to you
  4226. that there is a problem with your grammar. Your parser should ignore
  4227. white space, so we recommend using Lark's \code{\%ignore} directive
  4228. as follows.
  4229. \begin{lstlisting}
  4230. WS: /[ \t\f\r\n]/+
  4231. %ignore WS
  4232. \end{lstlisting}
  4233. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4234. Lark parser instead of using the \code{parse} function from
  4235. the \code{ast} module. Test your compiler on all the \LangVar{}
  4236. programs that you have created, and create four additional programs
  4237. that test for ambiguities in your grammar.
  4238. \end{exercise}
  4239. \section{Earley's Algorithm}
  4240. \label{sec:earley}
  4241. In this section we discuss the parsing algorithm of
  4242. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4243. algorithm is powerful in that it can handle any context-free grammar,
  4244. which makes it easy to use, but it is not a particularly
  4245. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4246. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4247. the number of tokens in the input
  4248. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4249. learn about the LALR(1) algorithm, which is more efficient but cannot
  4250. handle all context-free grammars.
  4251. Earley's algorithm can be viewed as an interpreter; it treats the
  4252. grammar as the program being interpreted, and it treats the concrete
  4253. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4254. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4255. keep track of its progress and to store its results. The chart is an
  4256. array with one slot for each position in the input string, where
  4257. position $0$ is before the first character and position $n$ is
  4258. immediately after the last character. So, the array has length $n+1$
  4259. for an input string of length $n$. Each slot in the chart contains a
  4260. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4261. with a period indicating how much of its right-hand side has already
  4262. been parsed. For example, the dotted rule
  4263. \begin{lstlisting}
  4264. exp: exp "+" . exp_hi
  4265. \end{lstlisting}
  4266. represents a partial parse that has matched an \code{exp} followed by
  4267. \code{+} but has not yet parsed an \code{exp} to the right of
  4268. \code{+}.
  4269. %
  4270. Earley's algorithm starts with an initialization phase and then
  4271. repeats three actions---prediction, scanning, and completion---for as
  4272. long as opportunities arise. We demonstrate Earley's algorithm on a
  4273. running example, parsing the following program:
  4274. \begin{lstlisting}
  4275. print(1 + 3)
  4276. \end{lstlisting}
  4277. The algorithm's initialization phase creates dotted rules for all the
  4278. grammar rules whose left-hand side is the start symbol and places them
  4279. in slot $0$ of the chart. We also record the starting position of the
  4280. dotted rule in parentheses on the right. For example, given the
  4281. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4282. \begin{lstlisting}
  4283. lang_int: . stmt_list (0)
  4284. \end{lstlisting}
  4285. in slot $0$ of the chart. The algorithm then proceeds with
  4286. \emph{prediction} actions in which it adds more dotted rules to the
  4287. chart based on the nonterminals that come immediately after a period. In
  4288. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4289. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4290. period at the beginning of their right-hand sides, as follows:
  4291. \begin{lstlisting}
  4292. stmt_list: . (0)
  4293. stmt_list: . stmt NEWLINE stmt_list (0)
  4294. \end{lstlisting}
  4295. We continue to perform prediction actions as more opportunities
  4296. arise. For example, the \code{stmt} nonterminal now appears after a
  4297. period, so we add all the rules for \code{stmt}.
  4298. \begin{lstlisting}
  4299. stmt: . "print" "(" exp ")" (0)
  4300. stmt: . exp (0)
  4301. \end{lstlisting}
  4302. This reveals yet more opportunities for prediction, so we add the grammar
  4303. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4304. \begin{lstlisting}[escapechar=$]
  4305. exp: . exp "+" exp_hi (0)
  4306. exp: . exp "-" exp_hi (0)
  4307. exp: . exp_hi (0)
  4308. exp_hi: . INT (0)
  4309. exp_hi: . "input_int" "(" ")" (0)
  4310. exp_hi: . "-" exp_hi (0)
  4311. exp_hi: . "(" exp ")" (0)
  4312. \end{lstlisting}
  4313. We have exhausted the opportunities for prediction, so the algorithm
  4314. proceeds to \emph{scanning}, in which we inspect the next input token
  4315. and look for a dotted rule at the current position that has a matching
  4316. terminal immediately following the period. In our running example, the
  4317. first input token is \code{"print"}, so we identify the rule in slot
  4318. $0$ of the chart where \code{"print"} follows the period:
  4319. \begin{lstlisting}
  4320. stmt: . "print" "(" exp ")" (0)
  4321. \end{lstlisting}
  4322. We advance the period past \code{"print"} and add the resulting rule
  4323. to slot $1$:
  4324. \begin{lstlisting}
  4325. stmt: "print" . "(" exp ")" (0)
  4326. \end{lstlisting}
  4327. If the new dotted rule had a nonterminal after the period, we would
  4328. need to carry out a prediction action, adding more dotted rules to
  4329. slot $1$. That is not the case, so we continue scanning. The next
  4330. input token is \code{"("}, so we add the following to slot $2$ of the
  4331. chart.
  4332. \begin{lstlisting}
  4333. stmt: "print" "(" . exp ")" (0)
  4334. \end{lstlisting}
  4335. Now we have a nonterminal after the period, so we carry out several
  4336. prediction actions, adding dotted rules for \code{exp} and
  4337. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4338. starting position $2$.
  4339. \begin{lstlisting}[escapechar=$]
  4340. exp: . exp "+" exp_hi (2)
  4341. exp: . exp "-" exp_hi (2)
  4342. exp: . exp_hi (2)
  4343. exp_hi: . INT (2)
  4344. exp_hi: . "input_int" "(" ")" (2)
  4345. exp_hi: . "-" exp_hi (2)
  4346. exp_hi: . "(" exp ")" (2)
  4347. \end{lstlisting}
  4348. With this prediction complete, we return to scanning, noting that the
  4349. next input token is \code{"1"}, which the lexer parses as an
  4350. \code{INT}. There is a matching rule in slot $2$:
  4351. \begin{lstlisting}
  4352. exp_hi: . INT (2)
  4353. \end{lstlisting}
  4354. so we advance the period and put the following rule into slot $3$.
  4355. \begin{lstlisting}
  4356. exp_hi: INT . (2)
  4357. \end{lstlisting}
  4358. This brings us to \emph{completion} actions. When the period reaches
  4359. the end of a dotted rule, we recognize that the substring
  4360. has matched the nonterminal on the left-hand side of the rule, in this case
  4361. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4362. rules into slot $2$ (the starting position for the finished rule) if
  4363. the period is immediately followed by \code{exp\_hi}. So we identify
  4364. \begin{lstlisting}
  4365. exp: . exp_hi (2)
  4366. \end{lstlisting}
  4367. and add the following dotted rule to slot $3$
  4368. \begin{lstlisting}
  4369. exp: exp_hi . (2)
  4370. \end{lstlisting}
  4371. This triggers another completion step for the nonterminal \code{exp},
  4372. adding two more dotted rules to slot $3$.
  4373. \begin{lstlisting}[escapechar=$]
  4374. exp: exp . "+" exp_hi (2)
  4375. exp: exp . "-" exp_hi (2)
  4376. \end{lstlisting}
  4377. Returning to scanning, the next input token is \code{"+"}, so
  4378. we add the following to slot $4$.
  4379. \begin{lstlisting}[escapechar=$]
  4380. exp: exp "+" . exp_hi (2)
  4381. \end{lstlisting}
  4382. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4383. the following dotted rules to slot $4$ of the chart.
  4384. \begin{lstlisting}[escapechar=$]
  4385. exp_hi: . INT (4)
  4386. exp_hi: . "input_int" "(" ")" (4)
  4387. exp_hi: . "-" exp_hi (4)
  4388. exp_hi: . "(" exp ")" (4)
  4389. \end{lstlisting}
  4390. The next input token is \code{"3"} which the lexer categorized as an
  4391. \code{INT}, so we advance the period past \code{INT} for the rules in
  4392. slot $4$, of which there is just one, and put the following into slot $5$.
  4393. \begin{lstlisting}[escapechar=$]
  4394. exp_hi: INT . (4)
  4395. \end{lstlisting}
  4396. The period at the end of the rule triggers a completion action for the
  4397. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4398. So we advance the period and put the following into slot $5$.
  4399. \begin{lstlisting}[escapechar=$]
  4400. exp: exp "+" exp_hi . (2)
  4401. \end{lstlisting}
  4402. This triggers another completion action for the rules in slot $2$ that
  4403. have a period before \code{exp}.
  4404. \begin{lstlisting}[escapechar=$]
  4405. stmt: "print" "(" exp . ")" (0)
  4406. exp: exp . "+" exp_hi (2)
  4407. exp: exp . "-" exp_hi (2)
  4408. \end{lstlisting}
  4409. We scan the next input token \code{")"}, placing the following dotted
  4410. rule into slot $6$.
  4411. \begin{lstlisting}[escapechar=$]
  4412. stmt: "print" "(" exp ")" . (0)
  4413. \end{lstlisting}
  4414. This triggers the completion of \code{stmt} in slot $0$
  4415. \begin{lstlisting}
  4416. stmt_list: stmt . NEWLINE stmt_list (0)
  4417. \end{lstlisting}
  4418. The last input token is a \code{NEWLINE}, so we advance the period
  4419. and place the new dotted rule into slot $7$.
  4420. \begin{lstlisting}
  4421. stmt_list: stmt NEWLINE . stmt_list (0)
  4422. \end{lstlisting}
  4423. We are close to the end of parsing the input!
  4424. The period is before the \code{stmt\_list} nonterminal, so we
  4425. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4426. \begin{lstlisting}
  4427. stmt_list: . (7)
  4428. stmt_list: . stmt NEWLINE stmt_list (7)
  4429. stmt: . "print" "(" exp ")" (7)
  4430. stmt: . exp (7)
  4431. \end{lstlisting}
  4432. There is immediately an opportunity for completion of \code{stmt\_list},
  4433. so we add the following to slot $7$.
  4434. \begin{lstlisting}
  4435. stmt_list: stmt NEWLINE stmt_list . (0)
  4436. \end{lstlisting}
  4437. This triggers another completion action for \code{stmt\_list} in slot $0$
  4438. \begin{lstlisting}
  4439. lang_int: stmt_list . (0)
  4440. \end{lstlisting}
  4441. which in turn completes \code{lang\_int}, the start symbol of the
  4442. grammar, so the parsing of the input is complete.
  4443. For reference, we give a general description of Earley's
  4444. algorithm.
  4445. \begin{enumerate}
  4446. \item The algorithm begins by initializing slot $0$ of the chart with the
  4447. grammar rule for the start symbol, placing a period at the beginning
  4448. of the right-hand side, and recording its starting position as $0$.
  4449. \item The algorithm repeatedly applies the following three kinds of
  4450. actions for as long as there are opportunities to do so.
  4451. \begin{itemize}
  4452. \item Prediction: If there is a rule in slot $k$ whose period comes
  4453. before a nonterminal, add the rules for that nonterminal into slot
  4454. $k$, placing a period at the beginning of their right-hand sides
  4455. and recording their starting position as $k$.
  4456. \item Scanning: If the token at position $k$ of the input string
  4457. matches the symbol after the period in a dotted rule in slot $k$
  4458. of the chart, advance the period in the dotted rule, adding
  4459. the result to slot $k+1$.
  4460. \item Completion: If a dotted rule in slot $k$ has a period at the
  4461. end, inspect the rules in the slot corresponding to the starting
  4462. position of the completed rule. If any of those rules have a
  4463. nonterminal following their period that matches the left-hand side
  4464. of the completed rule, then advance their period, placing the new
  4465. dotted rule in slot $k$.
  4466. \end{itemize}
  4467. While repeating these three actions, take care never to add
  4468. duplicate dotted rules to the chart.
  4469. \end{enumerate}
  4470. We have described how Earley's algorithm recognizes that an input
  4471. string matches a grammar, but we have not described how it builds a
  4472. parse tree. The basic idea is simple, but building parse trees in an
  4473. efficient way is more complex, requiring a data structure called a
  4474. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4475. to attach a partial parse tree to every dotted rule in the chart.
  4476. Initially, the node associated with a dotted rule has no
  4477. children. As the period moves to the right, the nodes from the
  4478. subparses are added as children to the node.
  4479. As mentioned at the beginning of this section, Earley's algorithm is
  4480. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4481. files that contain thousands of tokens in a reasonable amount of time,
  4482. but not millions.
  4483. %
  4484. In the next section we discuss the LALR(1) parsing algorithm, which is
  4485. efficient enough to use with even the largest of input files.
  4486. \section{The LALR(1) Algorithm}
  4487. \label{sec:lalr}
  4488. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4489. two-phase approach in which it first compiles the grammar into a state
  4490. machine and then runs the state machine to parse an input string. The
  4491. second phase has time complexity $O(n)$ where $n$ is the number of
  4492. tokens in the input, so LALR(1) is the best one could hope for with
  4493. respect to efficiency.
  4494. %
  4495. A particularly influential implementation of LALR(1) is the
  4496. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4497. \texttt{yacc} stands for ``yet another compiler compiler.''
  4498. %
  4499. The LALR(1) state machine uses a stack to record its progress in
  4500. parsing the input string. Each element of the stack is a pair: a
  4501. state number and a grammar symbol (a terminal or a nonterminal). The
  4502. symbol characterizes the input that has been parsed so far, and the
  4503. state number is used to remember how to proceed once the next
  4504. symbol's worth of input has been parsed. Each state in the machine
  4505. represents where the parser stands in the parsing process with respect
  4506. to certain grammar rules. In particular, each state is associated with
  4507. a set of dotted rules.
  4508. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4509. (also called parse table) for the following simple but ambiguous
  4510. grammar:
  4511. \begin{lstlisting}[escapechar=$]
  4512. exp: INT
  4513. | exp "+" exp
  4514. stmt: "print" exp
  4515. start: stmt
  4516. \end{lstlisting}
  4517. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4518. read in a \lstinline{"print"} token, so the top of the stack is
  4519. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4520. the input according to grammar rule 1, which is signified by showing
  4521. rule 1 with a period after the \code{"print"} token and before the
  4522. \code{exp} nonterminal. There are two rules that could apply next,
  4523. rules 2 and 3, so state 1 also shows those rules with a period at
  4524. the beginning of their right-hand sides. The edges between states
  4525. indicate which transitions the machine should make depending on the
  4526. next input token. So, for example, if the next input token is
  4527. \code{INT} then the parser will push \code{INT} and the target state 4
  4528. on the stack and transition to state 4. Suppose that we are now at the end
  4529. of the input. State 4 says that we should reduce by rule 3, so we pop
  4530. from the stack the same number of items as the number of symbols in
  4531. the right-hand side of the rule, in this case just one. We then
  4532. momentarily jump to the state at the top of the stack (state 1) and
  4533. then follow the goto edge that corresponds to the left-hand side of
  4534. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4535. state 3. (A slightly longer example parse is shown in
  4536. figure~\ref{fig:shift-reduce}.)
  4537. \begin{figure}[tbp]
  4538. \centering
  4539. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4540. \caption{An LALR(1) parse table and a trace of an example run.}
  4541. \label{fig:shift-reduce}
  4542. \end{figure}
  4543. In general, the algorithm works as follows. First, set the current state to
  4544. state $0$. Then repeat the following, looking at the next input token.
  4545. \begin{itemize}
  4546. \item If there there is a shift edge for the input token in the
  4547. current state, push the edge's target state and the input token onto
  4548. the stack and proceed to the edge's target state.
  4549. \item If there is a reduce action for the input token in the current
  4550. state, pop $k$ elements from the stack, where $k$ is the number of
  4551. symbols in the right-hand side of the rule being reduced. Jump to
  4552. the state at the top of the stack and then follow the goto edge for
  4553. the nonterminal that matches the left-hand side of the rule that we
  4554. are reducing by. Push the edge's target state and the nonterminal on the
  4555. stack.
  4556. \end{itemize}
  4557. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4558. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4559. algorithm does not know which action to take in this case. When a
  4560. state has both a shift and a reduce action for the same token, we say
  4561. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4562. will arise, for example, in trying to parse the input
  4563. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4564. the parser will be in state 6 and will not know whether to
  4565. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4566. to proceed by shifting the next \lstinline{+} from the input.
  4567. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4568. arises when there are two reduce actions in a state for the same
  4569. token. To understand which grammars give rise to shift/reduce and
  4570. reduce/reduce conflicts, it helps to know how the parse table is
  4571. generated from the grammar, which we discuss next.
  4572. The parse table is generated one state at a time. State 0 represents
  4573. the start of the parser. We add the grammar rule for the start symbol
  4574. to this state with a period at the beginning of the right-hand side,
  4575. similarly to the initialization phase of the Earley parser. If the
  4576. period appears immediately before another nonterminal, we add all the
  4577. rules with that nonterminal on the left-hand side. Again, we place a
  4578. period at the beginning of the right-hand side of each new
  4579. rule. This process, called \emph{state closure}, is continued
  4580. until there are no more rules to add (similarly to the prediction
  4581. actions of an Earley parser). We then examine each dotted rule in the
  4582. current state $I$. Suppose that a dotted rule has the form $A ::=
  4583. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4584. are sequences of symbols. We create a new state and call it $J$. If $X$
  4585. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4586. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4587. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4588. state $J$. We start by adding all dotted rules from state $I$ that
  4589. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4590. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4591. the period moved past the $X$. (This is analogous to completion in
  4592. Earley's algorithm.) We then perform state closure on $J$. This
  4593. process repeats until there are no more states or edges to add.
  4594. We then mark states as accepting states if they have a dotted rule
  4595. that is the start rule with a period at the end. Also, to add
  4596. the reduce actions, we look for any state containing a dotted rule
  4597. with a period at the end. Let $n$ be the rule number for this dotted
  4598. rule. We then put a reduce $n$ action into that state for every token
  4599. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4600. dotted rule with a period at the end. We therefore put a reduce by
  4601. rule 3 action into state 4 for every
  4602. token.
  4603. When inserting reduce actions, take care to spot any shift/reduce or
  4604. reduce/reduce conflicts. If there are any, abort the construction of
  4605. the parse table.
  4606. \begin{exercise}
  4607. \normalfont\normalsize
  4608. %
  4609. Working on paper, walk through the parse table generation process for
  4610. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4611. your results against the parse table shown in
  4612. figure~\ref{fig:shift-reduce}.
  4613. \end{exercise}
  4614. \begin{exercise}
  4615. \normalfont\normalsize
  4616. %
  4617. Change the parser in your compiler for \LangVar{} to set the
  4618. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4619. all the \LangVar{} programs that you have created. In doing so, Lark
  4620. may signal an error due to shift/reduce or reduce/reduce conflicts
  4621. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4622. remove those conflicts.
  4623. \end{exercise}
  4624. \section{Further Reading}
  4625. In this chapter we have just scratched the surface of the field of
  4626. parsing, with the study of a very general but less efficient algorithm
  4627. (Earley) and with a more limited but highly efficient algorithm
  4628. (LALR). There are many more algorithms and classes of grammars that
  4629. fall between these two ends of the spectrum. We recommend to the reader
  4630. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4631. Regarding lexical analysis, we have described the specification
  4632. language, which are the regular expressions, but not the algorithms
  4633. for recognizing them. In short, regular expressions can be translated
  4634. to nondeterministic finite automata, which in turn are translated to
  4635. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4636. all the details on lexical analysis.
  4637. \fi}
  4638. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4639. \chapter{Register Allocation}
  4640. \label{ch:register-allocation-Lvar}
  4641. \setcounter{footnote}{0}
  4642. \index{subject}{register allocation}
  4643. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4644. storing variables on the procedure call stack. The CPU may require tens
  4645. to hundreds of cycles to access a location on the stack, whereas
  4646. accessing a register takes only a single cycle. In this chapter we
  4647. improve the efficiency of our generated code by storing some variables
  4648. in registers. The goal of register allocation is to fit as many
  4649. variables into registers as possible. Some programs have more
  4650. variables than registers, so we cannot always map each variable to a
  4651. different register. Fortunately, it is common for different variables
  4652. to be in use during different periods of time during program
  4653. execution, and in those cases we can map multiple variables to the
  4654. same register.
  4655. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4656. example. The source program is on the left and the output of
  4657. instruction selection\index{subject}{instruction selection}
  4658. is on the right. The program is almost
  4659. completely in the x86 assembly language, but it still uses variables.
  4660. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4661. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4662. the other hand, is used only after this point, so \code{x} and
  4663. \code{z} could share the same register.
  4664. \begin{figure}
  4665. \begin{tcolorbox}[colback=white]
  4666. \begin{minipage}{0.45\textwidth}
  4667. Example \LangVar{} program:
  4668. % var_test_28.rkt
  4669. {\if\edition\racketEd
  4670. \begin{lstlisting}
  4671. (let ([v 1])
  4672. (let ([w 42])
  4673. (let ([x (+ v 7)])
  4674. (let ([y x])
  4675. (let ([z (+ x w)])
  4676. (+ z (- y)))))))
  4677. \end{lstlisting}
  4678. \fi}
  4679. {\if\edition\pythonEd\pythonColor
  4680. \begin{lstlisting}
  4681. v = 1
  4682. w = 42
  4683. x = v + 7
  4684. y = x
  4685. z = x + w
  4686. print(z + (- y))
  4687. \end{lstlisting}
  4688. \fi}
  4689. \end{minipage}
  4690. \begin{minipage}{0.45\textwidth}
  4691. After instruction selection:
  4692. {\if\edition\racketEd
  4693. \begin{lstlisting}
  4694. locals-types:
  4695. x : Integer, y : Integer,
  4696. z : Integer, t : Integer,
  4697. v : Integer, w : Integer
  4698. start:
  4699. movq $1, v
  4700. movq $42, w
  4701. movq v, x
  4702. addq $7, x
  4703. movq x, y
  4704. movq x, z
  4705. addq w, z
  4706. movq y, t
  4707. negq t
  4708. movq z, %rax
  4709. addq t, %rax
  4710. jmp conclusion
  4711. \end{lstlisting}
  4712. \fi}
  4713. {\if\edition\pythonEd\pythonColor
  4714. \begin{lstlisting}
  4715. movq $1, v
  4716. movq $42, w
  4717. movq v, x
  4718. addq $7, x
  4719. movq x, y
  4720. movq x, z
  4721. addq w, z
  4722. movq y, tmp_0
  4723. negq tmp_0
  4724. movq z, tmp_1
  4725. addq tmp_0, tmp_1
  4726. movq tmp_1, %rdi
  4727. callq print_int
  4728. \end{lstlisting}
  4729. \fi}
  4730. \end{minipage}
  4731. \end{tcolorbox}
  4732. \caption{A running example for register allocation.}
  4733. \label{fig:reg-eg}
  4734. \end{figure}
  4735. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4736. compute where a variable is in use. Once we have that information, we
  4737. compute which variables are in use at the same time, that is, which ones
  4738. \emph{interfere}\index{subject}{interfere} with each other, and
  4739. represent this relation as an undirected graph whose vertices are
  4740. variables and edges indicate when two variables interfere
  4741. (section~\ref{sec:build-interference}). We then model register
  4742. allocation as a graph coloring problem
  4743. (section~\ref{sec:graph-coloring}).
  4744. If we run out of registers despite these efforts, we place the
  4745. remaining variables on the stack, similarly to how we handled
  4746. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4747. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4748. location. The decision to spill a variable is handled as part of the
  4749. graph coloring process.
  4750. We make the simplifying assumption that each variable is assigned to
  4751. one location (a register or stack address). A more sophisticated
  4752. approach is to assign a variable to one or more locations in different
  4753. regions of the program. For example, if a variable is used many times
  4754. in short sequence and then used again only after many other
  4755. instructions, it could be more efficient to assign the variable to a
  4756. register during the initial sequence and then move it to the stack for
  4757. the rest of its lifetime. We refer the interested reader to
  4758. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4759. approach.
  4760. % discuss prioritizing variables based on how much they are used.
  4761. \section{Registers and Calling Conventions}
  4762. \label{sec:calling-conventions}
  4763. \index{subject}{calling conventions}
  4764. As we perform register allocation, we must be aware of the
  4765. \emph{calling conventions} \index{subject}{calling conventions} that
  4766. govern how function calls are performed in x86.
  4767. %
  4768. Even though \LangVar{} does not include programmer-defined functions,
  4769. our generated code includes a \code{main} function that is called by
  4770. the operating system and our generated code contains calls to the
  4771. \code{read\_int} function.
  4772. Function calls require coordination between two pieces of code that
  4773. may be written by different programmers or generated by different
  4774. compilers. Here we follow the System V calling conventions that are
  4775. used by the GNU C compiler on Linux and
  4776. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4777. %
  4778. The calling conventions include rules about how functions share the
  4779. use of registers. In particular, the caller is responsible for freeing
  4780. some registers prior to the function call for use by the callee.
  4781. These are called the \emph{caller-saved registers}
  4782. \index{subject}{caller-saved registers}
  4783. and they are
  4784. \begin{lstlisting}
  4785. rax rcx rdx rsi rdi r8 r9 r10 r11
  4786. \end{lstlisting}
  4787. On the other hand, the callee is responsible for preserving the values
  4788. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4789. which are
  4790. \begin{lstlisting}
  4791. rsp rbp rbx r12 r13 r14 r15
  4792. \end{lstlisting}
  4793. We can think about this caller/callee convention from two points of
  4794. view, the caller view and the callee view, as follows:
  4795. \begin{itemize}
  4796. \item The caller should assume that all the caller-saved registers get
  4797. overwritten with arbitrary values by the callee. On the other hand,
  4798. the caller can safely assume that all the callee-saved registers
  4799. retain their original values.
  4800. \item The callee can freely use any of the caller-saved registers.
  4801. However, if the callee wants to use a callee-saved register, the
  4802. callee must arrange to put the original value back in the register
  4803. prior to returning to the caller. This can be accomplished by saving
  4804. the value to the stack in the prelude of the function and restoring
  4805. the value in the conclusion of the function.
  4806. \end{itemize}
  4807. In x86, registers are also used for passing arguments to a function
  4808. and for the return value. In particular, the first six arguments of a
  4809. function are passed in the following six registers, in this order.
  4810. \begin{lstlisting}
  4811. rdi rsi rdx rcx r8 r9
  4812. \end{lstlisting}
  4813. We refer to these six registers are the argument-passing registers
  4814. \index{subject}{argument-passing registers}.
  4815. If there are more than six arguments, the convention is to use space
  4816. on the frame of the caller for the rest of the arguments. In
  4817. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4818. argument and the rest of the arguments, which simplifies the treatment
  4819. of efficient tail calls.
  4820. %
  4821. \racket{For now, the only function we care about is \code{read\_int},
  4822. which takes zero arguments.}
  4823. %
  4824. \python{For now, the only functions we care about are \code{read\_int}
  4825. and \code{print\_int}, which take zero and one argument, respectively.}
  4826. %
  4827. The register \code{rax} is used for the return value of a function.
  4828. The next question is how these calling conventions impact register
  4829. allocation. Consider the \LangVar{} program presented in
  4830. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4831. example from the caller point of view and then from the callee point
  4832. of view. We refer to a variable that is in use during a function call
  4833. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4834. The program makes two calls to \READOP{}. The variable \code{x} is
  4835. call-live because it is in use during the second call to \READOP{}; we
  4836. must ensure that the value in \code{x} does not get overwritten during
  4837. the call to \READOP{}. One obvious approach is to save all the values
  4838. that reside in caller-saved registers to the stack prior to each
  4839. function call and to restore them after each call. That way, if the
  4840. register allocator chooses to assign \code{x} to a caller-saved
  4841. register, its value will be preserved across the call to \READOP{}.
  4842. However, saving and restoring to the stack is relatively slow. If
  4843. \code{x} is not used many times, it may be better to assign \code{x}
  4844. to a stack location in the first place. Or better yet, if we can
  4845. arrange for \code{x} to be placed in a callee-saved register, then it
  4846. won't need to be saved and restored during function calls.
  4847. We recommend an approach that captures these issues in the
  4848. interference graph, without complicating the graph coloring algorithm.
  4849. During liveness analysis we know which variables are call-live because
  4850. we compute which variables are in use at every instruction
  4851. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4852. interference graph (section~\ref{sec:build-interference}), we can
  4853. place an edge in the interference graph between each call-live
  4854. variable and the caller-saved registers. This will prevent the graph
  4855. coloring algorithm from assigning call-live variables to caller-saved
  4856. registers.
  4857. On the other hand, for variables that are not call-live, we prefer
  4858. placing them in caller-saved registers to leave more room for
  4859. call-live variables in the callee-saved registers. This can also be
  4860. implemented without complicating the graph coloring algorithm. We
  4861. recommend that the graph coloring algorithm assign variables to
  4862. natural numbers, choosing the lowest number for which there is no
  4863. interference. After the coloring is complete, we map the numbers to
  4864. registers and stack locations: mapping the lowest numbers to
  4865. caller-saved registers, the next lowest to callee-saved registers, and
  4866. the largest numbers to stack locations. This ordering gives preference
  4867. to registers over stack locations and to caller-saved registers over
  4868. callee-saved registers.
  4869. Returning to the example in
  4870. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4871. generated x86 code on the right-hand side. Variable \code{x} is
  4872. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4873. in a safe place during the second call to \code{read\_int}. Next,
  4874. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4875. because \code{y} is not a call-live variable.
  4876. We have completed the analysis from the caller point of view, so now
  4877. we switch to the callee point of view, focusing on the prelude and
  4878. conclusion of the \code{main} function. As usual, the prelude begins
  4879. with saving the \code{rbp} register to the stack and setting the
  4880. \code{rbp} to the current stack pointer. We now know why it is
  4881. necessary to save the \code{rbp}: it is a callee-saved register. The
  4882. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4883. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4884. (\code{x}). The other callee-saved registers are not saved in the
  4885. prelude because they are not used. The prelude subtracts 8 bytes from
  4886. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4887. conclusion, we see that \code{rbx} is restored from the stack with a
  4888. \code{popq} instruction.
  4889. \index{subject}{prelude}\index{subject}{conclusion}
  4890. \begin{figure}[tp]
  4891. \begin{tcolorbox}[colback=white]
  4892. \begin{minipage}{0.45\textwidth}
  4893. Example \LangVar{} program:
  4894. %var_test_14.rkt
  4895. {\if\edition\racketEd
  4896. \begin{lstlisting}
  4897. (let ([x (read)])
  4898. (let ([y (read)])
  4899. (+ (+ x y) 42)))
  4900. \end{lstlisting}
  4901. \fi}
  4902. {\if\edition\pythonEd\pythonColor
  4903. \begin{lstlisting}
  4904. x = input_int()
  4905. y = input_int()
  4906. print((x + y) + 42)
  4907. \end{lstlisting}
  4908. \fi}
  4909. \end{minipage}
  4910. \begin{minipage}{0.45\textwidth}
  4911. Generated x86 assembly:
  4912. {\if\edition\racketEd
  4913. \begin{lstlisting}
  4914. start:
  4915. callq read_int
  4916. movq %rax, %rbx
  4917. callq read_int
  4918. movq %rax, %rcx
  4919. addq %rcx, %rbx
  4920. movq %rbx, %rax
  4921. addq $42, %rax
  4922. jmp _conclusion
  4923. .globl main
  4924. main:
  4925. pushq %rbp
  4926. movq %rsp, %rbp
  4927. pushq %rbx
  4928. subq $8, %rsp
  4929. jmp start
  4930. conclusion:
  4931. addq $8, %rsp
  4932. popq %rbx
  4933. popq %rbp
  4934. retq
  4935. \end{lstlisting}
  4936. \fi}
  4937. {\if\edition\pythonEd\pythonColor
  4938. \begin{lstlisting}
  4939. .globl main
  4940. main:
  4941. pushq %rbp
  4942. movq %rsp, %rbp
  4943. pushq %rbx
  4944. subq $8, %rsp
  4945. callq read_int
  4946. movq %rax, %rbx
  4947. callq read_int
  4948. movq %rax, %rcx
  4949. movq %rbx, %rdx
  4950. addq %rcx, %rdx
  4951. movq %rdx, %rcx
  4952. addq $42, %rcx
  4953. movq %rcx, %rdi
  4954. callq print_int
  4955. addq $8, %rsp
  4956. popq %rbx
  4957. popq %rbp
  4958. retq
  4959. \end{lstlisting}
  4960. \fi}
  4961. \end{minipage}
  4962. \end{tcolorbox}
  4963. \caption{An example with function calls.}
  4964. \label{fig:example-calling-conventions}
  4965. \end{figure}
  4966. %\clearpage
  4967. \section{Liveness Analysis}
  4968. \label{sec:liveness-analysis-Lvar}
  4969. \index{subject}{liveness analysis}
  4970. The \code{uncover\_live} \racket{pass}\python{function} performs
  4971. \emph{liveness analysis}; that is, it discovers which variables are
  4972. in use in different regions of a program.
  4973. %
  4974. A variable or register is \emph{live} at a program point if its
  4975. current value is used at some later point in the program. We refer to
  4976. variables, stack locations, and registers collectively as
  4977. \emph{locations}.
  4978. %
  4979. Consider the following code fragment in which there are two writes to
  4980. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4981. time?
  4982. \begin{center}
  4983. \begin{minipage}{0.85\textwidth}
  4984. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4985. movq $5, a
  4986. movq $30, b
  4987. movq a, c
  4988. movq $10, b
  4989. addq b, c
  4990. \end{lstlisting}
  4991. \end{minipage}
  4992. \end{center}
  4993. The answer is no, because \code{a} is live from line 1 to 3 and
  4994. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4995. line 2 is never used because it is overwritten (line 4) before the
  4996. next read (line 5).
  4997. The live locations for each instruction can be computed by traversing
  4998. the instruction sequence back to front (i.e., backward in execution
  4999. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5000. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5001. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5002. locations before instruction $I_k$. \racket{We recommend representing
  5003. these sets with the Racket \code{set} data structure described in
  5004. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5005. with the Python
  5006. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5007. data structure.}
  5008. {\if\edition\racketEd
  5009. \begin{figure}[tp]
  5010. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5011. \small
  5012. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5013. A \emph{set} is an unordered collection of elements without duplicates.
  5014. Here are some of the operations defined on sets.
  5015. \index{subject}{set}
  5016. \begin{description}
  5017. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5018. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5019. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5020. difference of the two sets.
  5021. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5022. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5023. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5024. \end{description}
  5025. \end{tcolorbox}
  5026. %\end{wrapfigure}
  5027. \caption{The \code{set} data structure.}
  5028. \label{fig:set}
  5029. \end{figure}
  5030. \fi}
  5031. % TODO: add a python version of the reference box for sets. -Jeremy
  5032. The locations that are live after an instruction are its
  5033. \emph{live-after}\index{subject}{live-after} set, and the locations
  5034. that are live before an instruction are its
  5035. \emph{live-before}\index{subject}{live-before} set. The live-after
  5036. set of an instruction is always the same as the live-before set of the
  5037. next instruction.
  5038. \begin{equation} \label{eq:live-after-before-next}
  5039. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5040. \end{equation}
  5041. To start things off, there are no live locations after the last
  5042. instruction, so
  5043. \begin{equation}\label{eq:live-last-empty}
  5044. L_{\mathsf{after}}(n) = \emptyset
  5045. \end{equation}
  5046. We then apply the following rule repeatedly, traversing the
  5047. instruction sequence back to front.
  5048. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5049. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5050. \end{equation}
  5051. where $W(k)$ are the locations written to by instruction $I_k$, and
  5052. $R(k)$ are the locations read by instruction $I_k$.
  5053. {\if\edition\racketEd
  5054. %
  5055. There is a special case for \code{jmp} instructions. The locations
  5056. that are live before a \code{jmp} should be the locations in
  5057. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5058. maintaining an alist named \code{label->live} that maps each label to
  5059. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5060. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5061. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5062. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5063. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5064. %
  5065. \fi}
  5066. Let us walk through the previous example, applying these formulas
  5067. starting with the instruction on line 5 of the code fragment. We
  5068. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5069. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5070. $\emptyset$ because it is the last instruction
  5071. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5072. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5073. variables \code{b} and \code{c}
  5074. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5075. \[
  5076. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5077. \]
  5078. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5079. the live-before set from line 5 to be the live-after set for this
  5080. instruction (formula~\eqref{eq:live-after-before-next}).
  5081. \[
  5082. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5083. \]
  5084. This move instruction writes to \code{b} and does not read from any
  5085. variables, so we have the following live-before set
  5086. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5087. \[
  5088. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5089. \]
  5090. The live-before for instruction \code{movq a, c}
  5091. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5092. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5093. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5094. variable that is not live and does not read from a variable.
  5095. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5096. because it writes to variable \code{a}.
  5097. \begin{figure}[tbp]
  5098. \centering
  5099. \begin{tcolorbox}[colback=white]
  5100. \hspace{10pt}
  5101. \begin{minipage}{0.4\textwidth}
  5102. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5103. movq $5, a
  5104. movq $30, b
  5105. movq a, c
  5106. movq $10, b
  5107. addq b, c
  5108. \end{lstlisting}
  5109. \end{minipage}
  5110. \vrule\hspace{10pt}
  5111. \begin{minipage}{0.45\textwidth}
  5112. \begin{align*}
  5113. L_{\mathsf{before}}(1)= \emptyset,
  5114. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5115. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5116. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5117. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5118. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5119. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5120. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5121. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5122. L_{\mathsf{after}}(5)= \emptyset
  5123. \end{align*}
  5124. \end{minipage}
  5125. \end{tcolorbox}
  5126. \caption{Example output of liveness analysis on a short example.}
  5127. \label{fig:liveness-example-0}
  5128. \end{figure}
  5129. \begin{exercise}\normalfont\normalsize
  5130. Perform liveness analysis by hand on the running example in
  5131. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5132. sets for each instruction. Compare your answers to the solution
  5133. shown in figure~\ref{fig:live-eg}.
  5134. \end{exercise}
  5135. \begin{figure}[tp]
  5136. \hspace{20pt}
  5137. \begin{minipage}{0.55\textwidth}
  5138. \begin{tcolorbox}[colback=white]
  5139. {\if\edition\racketEd
  5140. \begin{lstlisting}
  5141. |$\{\ttm{rsp}\}$|
  5142. movq $1, v
  5143. |$\{\ttm{v},\ttm{rsp}\}$|
  5144. movq $42, w
  5145. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5146. movq v, x
  5147. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5148. addq $7, x
  5149. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5150. movq x, y
  5151. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5152. movq x, z
  5153. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5154. addq w, z
  5155. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5156. movq y, t
  5157. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5158. negq t
  5159. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5160. movq z, %rax
  5161. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5162. addq t, %rax
  5163. |$\{\ttm{rax},\ttm{rsp}\}$|
  5164. jmp conclusion
  5165. \end{lstlisting}
  5166. \fi}
  5167. {\if\edition\pythonEd\pythonColor
  5168. \begin{lstlisting}
  5169. movq $1, v
  5170. |$\{\ttm{v}\}$|
  5171. movq $42, w
  5172. |$\{\ttm{w}, \ttm{v}\}$|
  5173. movq v, x
  5174. |$\{\ttm{w}, \ttm{x}\}$|
  5175. addq $7, x
  5176. |$\{\ttm{w}, \ttm{x}\}$|
  5177. movq x, y
  5178. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5179. movq x, z
  5180. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5181. addq w, z
  5182. |$\{\ttm{y}, \ttm{z}\}$|
  5183. movq y, tmp_0
  5184. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5185. negq tmp_0
  5186. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5187. movq z, tmp_1
  5188. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5189. addq tmp_0, tmp_1
  5190. |$\{\ttm{tmp\_1}\}$|
  5191. movq tmp_1, %rdi
  5192. |$\{\ttm{rdi}\}$|
  5193. callq print_int
  5194. |$\{\}$|
  5195. \end{lstlisting}
  5196. \fi}
  5197. \end{tcolorbox}
  5198. \end{minipage}
  5199. \caption{The running example annotated with live-after sets.}
  5200. \label{fig:live-eg}
  5201. \end{figure}
  5202. \begin{exercise}\normalfont\normalsize
  5203. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5204. %
  5205. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5206. field of the \code{Block} structure.}
  5207. %
  5208. \python{Return a dictionary that maps each instruction to its
  5209. live-after set.}
  5210. %
  5211. \racket{We recommend creating an auxiliary function that takes a list
  5212. of instructions and an initial live-after set (typically empty) and
  5213. returns the list of live-after sets.}
  5214. %
  5215. We recommend creating auxiliary functions to (1) compute the set
  5216. of locations that appear in an \Arg{}, (2) compute the locations read
  5217. by an instruction (the $R$ function), and (3) the locations written by
  5218. an instruction (the $W$ function). The \code{callq} instruction should
  5219. include all the caller-saved registers in its write set $W$ because
  5220. the calling convention says that those registers may be written to
  5221. during the function call. Likewise, the \code{callq} instruction
  5222. should include the appropriate argument-passing registers in its
  5223. read set $R$, depending on the arity of the function being
  5224. called. (This is why the abstract syntax for \code{callq} includes the
  5225. arity.)
  5226. \end{exercise}
  5227. %\clearpage
  5228. \section{Build the Interference Graph}
  5229. \label{sec:build-interference}
  5230. {\if\edition\racketEd
  5231. \begin{figure}[tp]
  5232. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5233. \small
  5234. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5235. A \emph{graph} is a collection of vertices and edges where each
  5236. edge connects two vertices. A graph is \emph{directed} if each
  5237. edge points from a source to a target. Otherwise the graph is
  5238. \emph{undirected}.
  5239. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5240. \begin{description}
  5241. %% We currently don't use directed graphs. We instead use
  5242. %% directed multi-graphs. -Jeremy
  5243. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5244. directed graph from a list of edges. Each edge is a list
  5245. containing the source and target vertex.
  5246. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5247. undirected graph from a list of edges. Each edge is represented by
  5248. a list containing two vertices.
  5249. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5250. inserts a vertex into the graph.
  5251. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5252. inserts an edge between the two vertices.
  5253. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5254. returns a sequence of vertices adjacent to the vertex.
  5255. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5256. returns a sequence of all vertices in the graph.
  5257. \end{description}
  5258. \end{tcolorbox}
  5259. %\end{wrapfigure}
  5260. \caption{The Racket \code{graph} package.}
  5261. \label{fig:graph}
  5262. \end{figure}
  5263. \fi}
  5264. On the basis of the liveness analysis, we know where each location is
  5265. live. However, during register allocation, we need to answer
  5266. questions of the specific form: are locations $u$ and $v$ live at the
  5267. same time? (If so, they cannot be assigned to the same register.) To
  5268. make this question more efficient to answer, we create an explicit
  5269. data structure, an \emph{interference
  5270. graph}\index{subject}{interference graph}. An interference graph is
  5271. an undirected graph that has a node for every variable and register
  5272. and has an edge between two nodes if they are
  5273. live at the same time, that is, if they interfere with each other.
  5274. %
  5275. \racket{We recommend using the Racket \code{graph} package
  5276. (figure~\ref{fig:graph}) to represent the interference graph.}
  5277. %
  5278. \python{We provide implementations of directed and undirected graph
  5279. data structures in the file \code{graph.py} of the support code.}
  5280. A straightforward way to compute the interference graph is to look at
  5281. the set of live locations between each instruction and add an edge to
  5282. the graph for every pair of variables in the same set. This approach
  5283. is less than ideal for two reasons. First, it can be expensive because
  5284. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5285. locations. Second, in the special case in which two locations hold the
  5286. same value (because one was assigned to the other), they can be live
  5287. at the same time without interfering with each other.
  5288. A better way to compute the interference graph is to focus on
  5289. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5290. must not overwrite something in a live location. So for each
  5291. instruction, we create an edge between the locations being written to
  5292. and the live locations. (However, a location never interferes with
  5293. itself.) For the \key{callq} instruction, we consider all the
  5294. caller-saved registers to have been written to, so an edge is added
  5295. between every live variable and every caller-saved register. Also, for
  5296. \key{movq} there is the special case of two variables holding the same
  5297. value. If a live variable $v$ is the same as the source of the
  5298. \key{movq}, then there is no need to add an edge between $v$ and the
  5299. destination, because they both hold the same value.
  5300. %
  5301. Hence we have the following two rules:
  5302. \begin{enumerate}
  5303. \item If instruction $I_k$ is a move instruction of the form
  5304. \key{movq} $s$\key{,} $d$, then for every $v \in
  5305. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5306. $(d,v)$.
  5307. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5308. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5309. $(d,v)$.
  5310. \end{enumerate}
  5311. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5312. these rules to each instruction. We highlight a few of the
  5313. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5314. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5315. so \code{v} interferes with \code{rsp}.}
  5316. %
  5317. \python{The first instruction is \lstinline{movq $1, v}, and the
  5318. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5319. no interference because $\ttm{v}$ is the destination of the move.}
  5320. %
  5321. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5322. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5323. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5324. %
  5325. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5326. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5327. $\ttm{x}$ interferes with \ttm{w}.}
  5328. %
  5329. \racket{The next instruction is \lstinline{movq x, y}, and the
  5330. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5331. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5332. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5333. \ttm{x} and \ttm{y} hold the same value.}
  5334. %
  5335. \python{The next instruction is \lstinline{movq x, y}, and the
  5336. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5337. applies, so \ttm{y} interferes with \ttm{w} but not
  5338. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5339. \ttm{x} and \ttm{y} hold the same value.}
  5340. %
  5341. Figure~\ref{fig:interference-results} lists the interference results
  5342. for all the instructions, and the resulting interference graph is
  5343. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5344. the interference graph in figure~\ref{fig:interfere} because there
  5345. were no interference edges involving registers and we did not wish to
  5346. clutter the graph, but in general one needs to include all the
  5347. registers in the interference graph.
  5348. \begin{figure}[tbp]
  5349. \begin{tcolorbox}[colback=white]
  5350. \begin{quote}
  5351. {\if\edition\racketEd
  5352. \begin{tabular}{ll}
  5353. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5354. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5355. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5356. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5357. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5358. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5359. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5360. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5361. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5362. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5363. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5364. \lstinline!jmp conclusion!& no interference.
  5365. \end{tabular}
  5366. \fi}
  5367. {\if\edition\pythonEd\pythonColor
  5368. \begin{tabular}{ll}
  5369. \lstinline!movq $1, v!& no interference\\
  5370. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5371. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5372. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5373. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5374. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5375. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5376. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5377. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5378. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5379. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5380. \lstinline!movq tmp_1, %rdi! & no interference \\
  5381. \lstinline!callq print_int!& no interference.
  5382. \end{tabular}
  5383. \fi}
  5384. \end{quote}
  5385. \end{tcolorbox}
  5386. \caption{Interference results for the running example.}
  5387. \label{fig:interference-results}
  5388. \end{figure}
  5389. \begin{figure}[tbp]
  5390. \begin{tcolorbox}[colback=white]
  5391. \large
  5392. {\if\edition\racketEd
  5393. \[
  5394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5395. \node (rax) at (0,0) {$\ttm{rax}$};
  5396. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5397. \node (t1) at (0,2) {$\ttm{t}$};
  5398. \node (z) at (3,2) {$\ttm{z}$};
  5399. \node (x) at (6,2) {$\ttm{x}$};
  5400. \node (y) at (3,0) {$\ttm{y}$};
  5401. \node (w) at (6,0) {$\ttm{w}$};
  5402. \node (v) at (9,0) {$\ttm{v}$};
  5403. \draw (t1) to (rax);
  5404. \draw (t1) to (z);
  5405. \draw (z) to (y);
  5406. \draw (z) to (w);
  5407. \draw (x) to (w);
  5408. \draw (y) to (w);
  5409. \draw (v) to (w);
  5410. \draw (v) to (rsp);
  5411. \draw (w) to (rsp);
  5412. \draw (x) to (rsp);
  5413. \draw (y) to (rsp);
  5414. \path[-.,bend left=15] (z) edge node {} (rsp);
  5415. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5416. \draw (rax) to (rsp);
  5417. \end{tikzpicture}
  5418. \]
  5419. \fi}
  5420. {\if\edition\pythonEd\pythonColor
  5421. \[
  5422. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5423. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5424. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5425. \node (z) at (3,2) {$\ttm{z}$};
  5426. \node (x) at (6,2) {$\ttm{x}$};
  5427. \node (y) at (3,0) {$\ttm{y}$};
  5428. \node (w) at (6,0) {$\ttm{w}$};
  5429. \node (v) at (9,0) {$\ttm{v}$};
  5430. \draw (t0) to (t1);
  5431. \draw (t0) to (z);
  5432. \draw (z) to (y);
  5433. \draw (z) to (w);
  5434. \draw (x) to (w);
  5435. \draw (y) to (w);
  5436. \draw (v) to (w);
  5437. \end{tikzpicture}
  5438. \]
  5439. \fi}
  5440. \end{tcolorbox}
  5441. \caption{The interference graph of the example program.}
  5442. \label{fig:interfere}
  5443. \end{figure}
  5444. \begin{exercise}\normalfont\normalsize
  5445. \racket{Implement the compiler pass named \code{build\_interference} according
  5446. to the algorithm suggested here. We recommend using the Racket
  5447. \code{graph} package to create and inspect the interference graph.
  5448. The output graph of this pass should be stored in the $\itm{info}$ field of
  5449. the program, under the key \code{conflicts}.}
  5450. %
  5451. \python{Implement a function named \code{build\_interference}
  5452. according to the algorithm suggested above that
  5453. returns the interference graph.}
  5454. \end{exercise}
  5455. \section{Graph Coloring via Sudoku}
  5456. \label{sec:graph-coloring}
  5457. \index{subject}{graph coloring}
  5458. \index{subject}{sudoku}
  5459. \index{subject}{color}
  5460. We come to the main event discussed in this chapter, mapping variables
  5461. to registers and stack locations. Variables that interfere with each
  5462. other must be mapped to different locations. In terms of the
  5463. interference graph, this means that adjacent vertices must be mapped
  5464. to different locations. If we think of locations as colors, the
  5465. register allocation problem becomes the graph coloring
  5466. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5467. The reader may be more familiar with the graph coloring problem than he
  5468. or she realizes; the popular game of sudoku is an instance of the
  5469. graph coloring problem. The following describes how to build a graph
  5470. out of an initial sudoku board.
  5471. \begin{itemize}
  5472. \item There is one vertex in the graph for each sudoku square.
  5473. \item There is an edge between two vertices if the corresponding squares
  5474. are in the same row, in the same column, or in the same $3\times 3$ region.
  5475. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5476. \item On the basis of the initial assignment of numbers to squares on the
  5477. sudoku board, assign the corresponding colors to the corresponding
  5478. vertices in the graph.
  5479. \end{itemize}
  5480. If you can color the remaining vertices in the graph with the nine
  5481. colors, then you have also solved the corresponding game of sudoku.
  5482. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5483. the corresponding graph with colored vertices. Here we use a
  5484. monochrome representation of colors, mapping the sudoku number 1 to
  5485. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5486. of the vertices (the colored ones) because showing edges for all the
  5487. vertices would make the graph unreadable.
  5488. \begin{figure}[tbp]
  5489. \begin{tcolorbox}[colback=white]
  5490. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5491. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5492. \end{tcolorbox}
  5493. \caption{A sudoku game board and the corresponding colored graph.}
  5494. \label{fig:sudoku-graph}
  5495. \end{figure}
  5496. Some techniques for playing sudoku correspond to heuristics used in
  5497. graph coloring algorithms. For example, one of the basic techniques
  5498. for sudoku is called Pencil Marks. The idea is to use a process of
  5499. elimination to determine what numbers are no longer available for a
  5500. square and to write those numbers in the square (writing very
  5501. small). For example, if the number $1$ is assigned to a square, then
  5502. write the pencil mark $1$ in all the squares in the same row, column,
  5503. and region to indicate that $1$ is no longer an option for those other
  5504. squares.
  5505. %
  5506. The Pencil Marks technique corresponds to the notion of
  5507. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5508. saturation of a vertex, in sudoku terms, is the set of numbers that
  5509. are no longer available. In graph terminology, we have the following
  5510. definition:
  5511. \begin{equation*}
  5512. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5513. \text{ and } \mathrm{color}(v) = c \}
  5514. \end{equation*}
  5515. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5516. edge with $u$.
  5517. The Pencil Marks technique leads to a simple strategy for filling in
  5518. numbers: if there is a square with only one possible number left, then
  5519. choose that number! But what if there are no squares with only one
  5520. possibility left? One brute-force approach is to try them all: choose
  5521. the first one, and if that ultimately leads to a solution, great. If
  5522. not, backtrack and choose the next possibility. One good thing about
  5523. Pencil Marks is that it reduces the degree of branching in the search
  5524. tree. Nevertheless, backtracking can be terribly time consuming. One
  5525. way to reduce the amount of backtracking is to use the
  5526. most-constrained-first heuristic (aka minimum remaining
  5527. values)~\citep{Russell2003}. That is, in choosing a square, always
  5528. choose one with the fewest possibilities left (the vertex with the
  5529. highest saturation). The idea is that choosing highly constrained
  5530. squares earlier rather than later is better, because later on there may
  5531. not be any possibilities left in the highly saturated squares.
  5532. However, register allocation is easier than sudoku, because the
  5533. register allocator can fall back to assigning variables to stack
  5534. locations when the registers run out. Thus, it makes sense to replace
  5535. backtracking with greedy search: make the best choice at the time and
  5536. keep going. We still wish to minimize the number of colors needed, so
  5537. we use the most-constrained-first heuristic in the greedy search.
  5538. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5539. algorithm for register allocation based on saturation and the
  5540. most-constrained-first heuristic. It is roughly equivalent to the
  5541. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5542. sudoku, the algorithm represents colors with integers. The integers
  5543. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5544. register allocation. In particular, we recommend the following
  5545. correspondence, with $k=11$.
  5546. \begin{lstlisting}
  5547. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5548. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5549. \end{lstlisting}
  5550. The integers $k$ and larger correspond to stack locations. The
  5551. registers that are not used for register allocation, such as
  5552. \code{rax}, are assigned to negative integers. In particular, we
  5553. recommend the following correspondence.
  5554. \begin{lstlisting}
  5555. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5556. \end{lstlisting}
  5557. \begin{figure}[btp]
  5558. \begin{tcolorbox}[colback=white]
  5559. \centering
  5560. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5561. Algorithm: DSATUR
  5562. Input: A graph |$G$|
  5563. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5564. |$W \gets \mathrm{vertices}(G)$|
  5565. while |$W \neq \emptyset$| do
  5566. pick a vertex |$u$| from |$W$| with the highest saturation,
  5567. breaking ties randomly
  5568. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5569. |$\mathrm{color}[u] \gets c$|
  5570. |$W \gets W - \{u\}$|
  5571. \end{lstlisting}
  5572. \end{tcolorbox}
  5573. \caption{The saturation-based greedy graph coloring algorithm.}
  5574. \label{fig:satur-algo}
  5575. \end{figure}
  5576. {\if\edition\racketEd
  5577. With the DSATUR algorithm in hand, let us return to the running
  5578. example and consider how to color the interference graph shown in
  5579. figure~\ref{fig:interfere}.
  5580. %
  5581. We start by assigning each register node to its own color. For
  5582. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5583. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5584. (To reduce clutter in the interference graph, we elide nodes
  5585. that do not have interference edges, such as \code{rcx}.)
  5586. The variables are not yet colored, so they are annotated with a dash. We
  5587. then update the saturation for vertices that are adjacent to a
  5588. register, obtaining the following annotated graph. For example, the
  5589. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5590. \code{rax} and \code{rsp}.
  5591. \[
  5592. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5593. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5594. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5595. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5596. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5597. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5598. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5599. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5600. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5601. \draw (t1) to (rax);
  5602. \draw (t1) to (z);
  5603. \draw (z) to (y);
  5604. \draw (z) to (w);
  5605. \draw (x) to (w);
  5606. \draw (y) to (w);
  5607. \draw (v) to (w);
  5608. \draw (v) to (rsp);
  5609. \draw (w) to (rsp);
  5610. \draw (x) to (rsp);
  5611. \draw (y) to (rsp);
  5612. \path[-.,bend left=15] (z) edge node {} (rsp);
  5613. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5614. \draw (rax) to (rsp);
  5615. \end{tikzpicture}
  5616. \]
  5617. The algorithm says to select a maximally saturated vertex. So, we pick
  5618. $\ttm{t}$ and color it with the first available integer, which is
  5619. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5620. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5621. \[
  5622. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5623. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5624. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5625. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5626. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5627. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5628. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5629. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5630. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5631. \draw (t1) to (rax);
  5632. \draw (t1) to (z);
  5633. \draw (z) to (y);
  5634. \draw (z) to (w);
  5635. \draw (x) to (w);
  5636. \draw (y) to (w);
  5637. \draw (v) to (w);
  5638. \draw (v) to (rsp);
  5639. \draw (w) to (rsp);
  5640. \draw (x) to (rsp);
  5641. \draw (y) to (rsp);
  5642. \path[-.,bend left=15] (z) edge node {} (rsp);
  5643. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5644. \draw (rax) to (rsp);
  5645. \end{tikzpicture}
  5646. \]
  5647. We repeat the process, selecting a maximally saturated vertex,
  5648. choosing \code{z}, and coloring it with the first available number, which
  5649. is $1$. We add $1$ to the saturation for the neighboring vertices
  5650. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5651. \[
  5652. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5653. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5654. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5655. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5656. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5657. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5658. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5659. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5660. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5661. \draw (t1) to (rax);
  5662. \draw (t1) to (z);
  5663. \draw (z) to (y);
  5664. \draw (z) to (w);
  5665. \draw (x) to (w);
  5666. \draw (y) to (w);
  5667. \draw (v) to (w);
  5668. \draw (v) to (rsp);
  5669. \draw (w) to (rsp);
  5670. \draw (x) to (rsp);
  5671. \draw (y) to (rsp);
  5672. \path[-.,bend left=15] (z) edge node {} (rsp);
  5673. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5674. \draw (rax) to (rsp);
  5675. \end{tikzpicture}
  5676. \]
  5677. The most saturated vertices are now \code{w} and \code{y}. We color
  5678. \code{w} with the first available color, which is $0$.
  5679. \[
  5680. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5681. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5682. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5683. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5684. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5685. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5686. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5687. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5688. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5689. \draw (t1) to (rax);
  5690. \draw (t1) to (z);
  5691. \draw (z) to (y);
  5692. \draw (z) to (w);
  5693. \draw (x) to (w);
  5694. \draw (y) to (w);
  5695. \draw (v) to (w);
  5696. \draw (v) to (rsp);
  5697. \draw (w) to (rsp);
  5698. \draw (x) to (rsp);
  5699. \draw (y) to (rsp);
  5700. \path[-.,bend left=15] (z) edge node {} (rsp);
  5701. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5702. \draw (rax) to (rsp);
  5703. \end{tikzpicture}
  5704. \]
  5705. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5706. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5707. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5708. and \code{z}, whose colors are $0$ and $1$ respectively.
  5709. \[
  5710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5711. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5712. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5713. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5714. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5715. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5716. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5717. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5718. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5719. \draw (t1) to (rax);
  5720. \draw (t1) to (z);
  5721. \draw (z) to (y);
  5722. \draw (z) to (w);
  5723. \draw (x) to (w);
  5724. \draw (y) to (w);
  5725. \draw (v) to (w);
  5726. \draw (v) to (rsp);
  5727. \draw (w) to (rsp);
  5728. \draw (x) to (rsp);
  5729. \draw (y) to (rsp);
  5730. \path[-.,bend left=15] (z) edge node {} (rsp);
  5731. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5732. \draw (rax) to (rsp);
  5733. \end{tikzpicture}
  5734. \]
  5735. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5736. \[
  5737. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5738. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5739. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5740. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5741. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5742. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5743. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5744. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5745. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5746. \draw (t1) to (rax);
  5747. \draw (t1) to (z);
  5748. \draw (z) to (y);
  5749. \draw (z) to (w);
  5750. \draw (x) to (w);
  5751. \draw (y) to (w);
  5752. \draw (v) to (w);
  5753. \draw (v) to (rsp);
  5754. \draw (w) to (rsp);
  5755. \draw (x) to (rsp);
  5756. \draw (y) to (rsp);
  5757. \path[-.,bend left=15] (z) edge node {} (rsp);
  5758. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5759. \draw (rax) to (rsp);
  5760. \end{tikzpicture}
  5761. \]
  5762. In the last step of the algorithm, we color \code{x} with $1$.
  5763. \[
  5764. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5765. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5766. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5767. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5768. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5769. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5770. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5771. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5772. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5773. \draw (t1) to (rax);
  5774. \draw (t1) to (z);
  5775. \draw (z) to (y);
  5776. \draw (z) to (w);
  5777. \draw (x) to (w);
  5778. \draw (y) to (w);
  5779. \draw (v) to (w);
  5780. \draw (v) to (rsp);
  5781. \draw (w) to (rsp);
  5782. \draw (x) to (rsp);
  5783. \draw (y) to (rsp);
  5784. \path[-.,bend left=15] (z) edge node {} (rsp);
  5785. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5786. \draw (rax) to (rsp);
  5787. \end{tikzpicture}
  5788. \]
  5789. So, we obtain the following coloring:
  5790. \[
  5791. \{
  5792. \ttm{rax} \mapsto -1,
  5793. \ttm{rsp} \mapsto -2,
  5794. \ttm{t} \mapsto 0,
  5795. \ttm{z} \mapsto 1,
  5796. \ttm{x} \mapsto 1,
  5797. \ttm{y} \mapsto 2,
  5798. \ttm{w} \mapsto 0,
  5799. \ttm{v} \mapsto 1
  5800. \}
  5801. \]
  5802. \fi}
  5803. %
  5804. {\if\edition\pythonEd\pythonColor
  5805. %
  5806. With the DSATUR algorithm in hand, let us return to the running
  5807. example and consider how to color the interference graph shown in
  5808. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5809. to indicate that it has not yet been assigned a color. Each register
  5810. node (not shown) should be assigned the number that the register
  5811. corresponds to, for example, color \code{rcx} with the number \code{0}
  5812. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5813. each node; all of them start as the empty set.
  5814. %
  5815. \[
  5816. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5817. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5818. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5819. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5820. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5821. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5822. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5823. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5824. \draw (t0) to (t1);
  5825. \draw (t0) to (z);
  5826. \draw (z) to (y);
  5827. \draw (z) to (w);
  5828. \draw (x) to (w);
  5829. \draw (y) to (w);
  5830. \draw (v) to (w);
  5831. \end{tikzpicture}
  5832. \]
  5833. The algorithm says to select a maximally saturated vertex, but they
  5834. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5835. and then we color it with the first available integer, which is $0$. We mark
  5836. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5837. they interfere with $\ttm{tmp\_0}$.
  5838. \[
  5839. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5840. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5841. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5842. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5843. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5844. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5845. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5846. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5847. \draw (t0) to (t1);
  5848. \draw (t0) to (z);
  5849. \draw (z) to (y);
  5850. \draw (z) to (w);
  5851. \draw (x) to (w);
  5852. \draw (y) to (w);
  5853. \draw (v) to (w);
  5854. \end{tikzpicture}
  5855. \]
  5856. We repeat the process. The most saturated vertices are \code{z} and
  5857. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5858. available number, which is $1$. We add $1$ to the saturation for the
  5859. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5860. \[
  5861. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5862. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5863. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5864. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5865. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5866. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5867. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5868. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5869. \draw (t0) to (t1);
  5870. \draw (t0) to (z);
  5871. \draw (z) to (y);
  5872. \draw (z) to (w);
  5873. \draw (x) to (w);
  5874. \draw (y) to (w);
  5875. \draw (v) to (w);
  5876. \end{tikzpicture}
  5877. \]
  5878. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5879. \code{y}. We color \code{w} with the first available color, which
  5880. is $0$.
  5881. \[
  5882. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5883. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5884. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5885. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5886. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5887. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5888. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5889. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5890. \draw (t0) to (t1);
  5891. \draw (t0) to (z);
  5892. \draw (z) to (y);
  5893. \draw (z) to (w);
  5894. \draw (x) to (w);
  5895. \draw (y) to (w);
  5896. \draw (v) to (w);
  5897. \end{tikzpicture}
  5898. \]
  5899. Now \code{y} is the most saturated, so we color it with $2$.
  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,2\}$};
  5905. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5906. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5907. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  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. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5919. We choose to color \code{v} with $1$.
  5920. \[
  5921. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5922. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5923. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5924. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5925. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5926. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5927. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5928. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5929. \draw (t0) to (t1);
  5930. \draw (t0) to (z);
  5931. \draw (z) to (y);
  5932. \draw (z) to (w);
  5933. \draw (x) to (w);
  5934. \draw (y) to (w);
  5935. \draw (v) to (w);
  5936. \end{tikzpicture}
  5937. \]
  5938. We color the remaining two variables, \code{tmp\_1} and \code{x}, 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}: 1, \{0\}$};
  5943. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5944. \node (x) at (6,2) {$\ttm{x}: 1, \{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. So, we obtain the following coloring:
  5958. \[
  5959. \{ \ttm{tmp\_0} \mapsto 0,
  5960. \ttm{tmp\_1} \mapsto 1,
  5961. \ttm{z} \mapsto 1,
  5962. \ttm{x} \mapsto 1,
  5963. \ttm{y} \mapsto 2,
  5964. \ttm{w} \mapsto 0,
  5965. \ttm{v} \mapsto 1 \}
  5966. \]
  5967. \fi}
  5968. We recommend creating an auxiliary function named \code{color\_graph}
  5969. that takes an interference graph and a list of all the variables in
  5970. the program. This function should return a mapping of variables to
  5971. their colors (represented as natural numbers). By creating this helper
  5972. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5973. when we add support for functions.
  5974. To prioritize the processing of highly saturated nodes inside the
  5975. \code{color\_graph} function, we recommend using the priority queue
  5976. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5977. addition, you will need to maintain a mapping from variables to their
  5978. handles in the priority queue so that you can notify the priority
  5979. queue when their saturation changes.}
  5980. {\if\edition\racketEd
  5981. \begin{figure}[tp]
  5982. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5983. \small
  5984. \begin{tcolorbox}[title=Priority Queue]
  5985. A \emph{priority queue}\index{subject}{priority queue}
  5986. is a collection of items in which the
  5987. removal of items is governed by priority. In a \emph{min} queue,
  5988. lower priority items are removed first. An implementation is in
  5989. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  5990. \begin{description}
  5991. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5992. priority queue that uses the $\itm{cmp}$ predicate to determine
  5993. whether its first argument has lower or equal priority to its
  5994. second argument.
  5995. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5996. items in the queue.
  5997. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5998. the item into the queue and returns a handle for the item in the
  5999. queue.
  6000. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6001. the lowest priority.
  6002. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6003. notifies the queue that the priority has decreased for the item
  6004. associated with the given handle.
  6005. \end{description}
  6006. \end{tcolorbox}
  6007. %\end{wrapfigure}
  6008. \caption{The priority queue data structure.}
  6009. \label{fig:priority-queue}
  6010. \end{figure}
  6011. \fi}
  6012. With the coloring complete, we finalize the assignment of variables to
  6013. registers and stack locations. We map the first $k$ colors to the $k$
  6014. registers and the rest of the colors to stack locations. Suppose for
  6015. the moment that we have just one register to use for register
  6016. allocation, \key{rcx}. Then we have the following assignment.
  6017. \[
  6018. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6019. \]
  6020. Composing this mapping with the coloring, we arrive at the following
  6021. assignment of variables to locations.
  6022. {\if\edition\racketEd
  6023. \begin{gather*}
  6024. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6025. \ttm{w} \mapsto \key{\%rcx}, \,
  6026. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6027. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6028. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6029. \ttm{t} \mapsto \key{\%rcx} \}
  6030. \end{gather*}
  6031. \fi}
  6032. {\if\edition\pythonEd\pythonColor
  6033. \begin{gather*}
  6034. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6035. \ttm{w} \mapsto \key{\%rcx}, \,
  6036. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6037. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6038. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6039. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6040. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6041. \end{gather*}
  6042. \fi}
  6043. Adapt the code from the \code{assign\_homes} pass
  6044. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6045. assigned location. Applying this assignment to our running
  6046. example shown next, on the left, yields the program on the right.
  6047. \begin{center}
  6048. {\if\edition\racketEd
  6049. \begin{minipage}{0.35\textwidth}
  6050. \begin{lstlisting}
  6051. movq $1, v
  6052. movq $42, w
  6053. movq v, x
  6054. addq $7, x
  6055. movq x, y
  6056. movq x, z
  6057. addq w, z
  6058. movq y, t
  6059. negq t
  6060. movq z, %rax
  6061. addq t, %rax
  6062. jmp conclusion
  6063. \end{lstlisting}
  6064. \end{minipage}
  6065. $\Rightarrow\qquad$
  6066. \begin{minipage}{0.45\textwidth}
  6067. \begin{lstlisting}
  6068. movq $1, -8(%rbp)
  6069. movq $42, %rcx
  6070. movq -8(%rbp), -8(%rbp)
  6071. addq $7, -8(%rbp)
  6072. movq -8(%rbp), -16(%rbp)
  6073. movq -8(%rbp), -8(%rbp)
  6074. addq %rcx, -8(%rbp)
  6075. movq -16(%rbp), %rcx
  6076. negq %rcx
  6077. movq -8(%rbp), %rax
  6078. addq %rcx, %rax
  6079. jmp conclusion
  6080. \end{lstlisting}
  6081. \end{minipage}
  6082. \fi}
  6083. {\if\edition\pythonEd\pythonColor
  6084. \begin{minipage}{0.35\textwidth}
  6085. \begin{lstlisting}
  6086. movq $1, v
  6087. movq $42, w
  6088. movq v, x
  6089. addq $7, x
  6090. movq x, y
  6091. movq x, z
  6092. addq w, z
  6093. movq y, tmp_0
  6094. negq tmp_0
  6095. movq z, tmp_1
  6096. addq tmp_0, tmp_1
  6097. movq tmp_1, %rdi
  6098. callq print_int
  6099. \end{lstlisting}
  6100. \end{minipage}
  6101. $\Rightarrow\qquad$
  6102. \begin{minipage}{0.45\textwidth}
  6103. \begin{lstlisting}
  6104. movq $1, -8(%rbp)
  6105. movq $42, %rcx
  6106. movq -8(%rbp), -8(%rbp)
  6107. addq $7, -8(%rbp)
  6108. movq -8(%rbp), -16(%rbp)
  6109. movq -8(%rbp), -8(%rbp)
  6110. addq %rcx, -8(%rbp)
  6111. movq -16(%rbp), %rcx
  6112. negq %rcx
  6113. movq -8(%rbp), -8(%rbp)
  6114. addq %rcx, -8(%rbp)
  6115. movq -8(%rbp), %rdi
  6116. callq print_int
  6117. \end{lstlisting}
  6118. \end{minipage}
  6119. \fi}
  6120. \end{center}
  6121. \begin{exercise}\normalfont\normalsize
  6122. Implement the \code{allocate\_registers} pass.
  6123. Create five programs that exercise all aspects of the register
  6124. allocation algorithm, including spilling variables to the stack.
  6125. %
  6126. {\if\edition\racketEd
  6127. Replace \code{assign\_homes} in the list of \code{passes} in the
  6128. \code{run-tests.rkt} script with the three new passes:
  6129. \code{uncover\_live}, \code{build\_interference}, and
  6130. \code{allocate\_registers}.
  6131. Temporarily remove the call to \code{compiler-tests}.
  6132. Run the script to test the register allocator.
  6133. \fi}
  6134. %
  6135. {\if\edition\pythonEd\pythonColor
  6136. Run the \code{run-tests.py} script to check whether the
  6137. output programs produce the same result as the input programs.
  6138. \fi}
  6139. \end{exercise}
  6140. \section{Patch Instructions}
  6141. \label{sec:patch-instructions}
  6142. The remaining step in the compilation to x86 is to ensure that the
  6143. instructions have at most one argument that is a memory access.
  6144. %
  6145. In the running example, the instruction \code{movq -8(\%rbp),
  6146. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6147. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6148. then move \code{rax} into \code{-16(\%rbp)}.
  6149. %
  6150. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6151. problematic, but they can simply be deleted. In general, we recommend
  6152. deleting all the trivial moves whose source and destination are the
  6153. same location.
  6154. %
  6155. The following is the output of \code{patch\_instructions} on the
  6156. running example.
  6157. \begin{center}
  6158. {\if\edition\racketEd
  6159. \begin{minipage}{0.35\textwidth}
  6160. \begin{lstlisting}
  6161. movq $1, -8(%rbp)
  6162. movq $42, %rcx
  6163. movq -8(%rbp), -8(%rbp)
  6164. addq $7, -8(%rbp)
  6165. movq -8(%rbp), -16(%rbp)
  6166. movq -8(%rbp), -8(%rbp)
  6167. addq %rcx, -8(%rbp)
  6168. movq -16(%rbp), %rcx
  6169. negq %rcx
  6170. movq -8(%rbp), %rax
  6171. addq %rcx, %rax
  6172. jmp conclusion
  6173. \end{lstlisting}
  6174. \end{minipage}
  6175. $\Rightarrow\qquad$
  6176. \begin{minipage}{0.45\textwidth}
  6177. \begin{lstlisting}
  6178. movq $1, -8(%rbp)
  6179. movq $42, %rcx
  6180. addq $7, -8(%rbp)
  6181. movq -8(%rbp), %rax
  6182. movq %rax, -16(%rbp)
  6183. addq %rcx, -8(%rbp)
  6184. movq -16(%rbp), %rcx
  6185. negq %rcx
  6186. movq -8(%rbp), %rax
  6187. addq %rcx, %rax
  6188. jmp conclusion
  6189. \end{lstlisting}
  6190. \end{minipage}
  6191. \fi}
  6192. {\if\edition\pythonEd\pythonColor
  6193. \begin{minipage}{0.35\textwidth}
  6194. \begin{lstlisting}
  6195. movq $1, -8(%rbp)
  6196. movq $42, %rcx
  6197. movq -8(%rbp), -8(%rbp)
  6198. addq $7, -8(%rbp)
  6199. movq -8(%rbp), -16(%rbp)
  6200. movq -8(%rbp), -8(%rbp)
  6201. addq %rcx, -8(%rbp)
  6202. movq -16(%rbp), %rcx
  6203. negq %rcx
  6204. movq -8(%rbp), -8(%rbp)
  6205. addq %rcx, -8(%rbp)
  6206. movq -8(%rbp), %rdi
  6207. callq print_int
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. $\Rightarrow\qquad$
  6211. \begin{minipage}{0.45\textwidth}
  6212. \begin{lstlisting}
  6213. movq $1, -8(%rbp)
  6214. movq $42, %rcx
  6215. addq $7, -8(%rbp)
  6216. movq -8(%rbp), %rax
  6217. movq %rax, -16(%rbp)
  6218. addq %rcx, -8(%rbp)
  6219. movq -16(%rbp), %rcx
  6220. negq %rcx
  6221. addq %rcx, -8(%rbp)
  6222. movq -8(%rbp), %rdi
  6223. callq print_int
  6224. \end{lstlisting}
  6225. \end{minipage}
  6226. \fi}
  6227. \end{center}
  6228. \begin{exercise}\normalfont\normalsize
  6229. %
  6230. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6231. %
  6232. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6233. %in the \code{run-tests.rkt} script.
  6234. %
  6235. Run the script to test the \code{patch\_instructions} pass.
  6236. \end{exercise}
  6237. \section{Generate Prelude and Conclusion}
  6238. \label{sec:print-x86-reg-alloc}
  6239. \index{subject}{calling conventions}
  6240. \index{subject}{prelude}\index{subject}{conclusion}
  6241. Recall that this pass generates the prelude and conclusion
  6242. instructions to satisfy the x86 calling conventions
  6243. (section~\ref{sec:calling-conventions}). With the addition of the
  6244. register allocator, the callee-saved registers used by the register
  6245. allocator must be saved in the prelude and restored in the conclusion.
  6246. In the \code{allocate\_registers} pass,
  6247. %
  6248. \racket{add an entry to the \itm{info}
  6249. of \code{X86Program} named \code{used\_callee}}
  6250. %
  6251. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6252. %
  6253. that stores the set of callee-saved registers that were assigned to
  6254. variables. The \code{prelude\_and\_conclusion} pass can then access
  6255. this information to decide which callee-saved registers need to be
  6256. saved and restored.
  6257. %
  6258. When calculating the amount to adjust the \code{rsp} in the prelude,
  6259. make sure to take into account the space used for saving the
  6260. callee-saved registers. Also, remember that the frame needs to be a
  6261. multiple of 16 bytes! We recommend using the following equation for
  6262. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6263. of stack locations used by spilled variables\footnote{Sometimes two or
  6264. more spilled variables are assigned to the same stack location, so
  6265. $S$ can be less than the number of spilled variables.} and $C$ be
  6266. the number of callee-saved registers that were
  6267. allocated\index{subject}{allocate} to
  6268. variables. The $\itm{align}$ function rounds a number up to the
  6269. nearest 16 bytes.
  6270. \[
  6271. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6272. \]
  6273. The reason we subtract $8\itm{C}$ in this equation is that the
  6274. prelude uses \code{pushq} to save each of the callee-saved registers,
  6275. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6276. \racket{An overview of all the passes involved in register
  6277. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6278. {\if\edition\racketEd
  6279. \begin{figure}[tbp]
  6280. \begin{tcolorbox}[colback=white]
  6281. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6282. \node (Lvar) at (0,2) {\large \LangVar{}};
  6283. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6284. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6285. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6286. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6287. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6288. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6289. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6290. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6291. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6292. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6293. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6294. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6295. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6296. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6297. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6298. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6299. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6300. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6301. \end{tikzpicture}
  6302. \end{tcolorbox}
  6303. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6304. \label{fig:reg-alloc-passes}
  6305. \end{figure}
  6306. \fi}
  6307. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6308. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6309. use of registers and the stack, we limit the register allocator for
  6310. this example to use just two registers: \code{rcx} (color $0$) and
  6311. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6312. \code{main} function, we push \code{rbx} onto the stack because it is
  6313. a callee-saved register and it was assigned to a variable by the
  6314. register allocator. We subtract \code{8} from the \code{rsp} at the
  6315. end of the prelude to reserve space for the one spilled variable.
  6316. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6317. Moving on to the program proper, we see how the registers were
  6318. allocated.
  6319. %
  6320. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6321. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6322. %
  6323. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6324. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6325. were assigned to \code{rbx}.}
  6326. %
  6327. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6328. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6329. callee-save register \code{rbx} onto the stack. The spilled variables
  6330. must be placed lower on the stack than the saved callee-save
  6331. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6332. \code{-16(\%rbp)}.
  6333. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6334. done in the prelude. We move the stack pointer up by \code{8} bytes
  6335. (the room for spilled variables), then pop the old values of
  6336. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6337. \code{retq} to return control to the operating system.
  6338. \begin{figure}[tbp]
  6339. \begin{minipage}{0.55\textwidth}
  6340. \begin{tcolorbox}[colback=white]
  6341. % var_test_28.rkt
  6342. % (use-minimal-set-of-registers! #t)
  6343. % 0 -> rcx
  6344. % 1 -> rbx
  6345. %
  6346. % t 0 rcx
  6347. % z 1 rbx
  6348. % w 0 rcx
  6349. % y 2 rbp -16
  6350. % v 1 rbx
  6351. % x 1 rbx
  6352. {\if\edition\racketEd
  6353. \begin{lstlisting}
  6354. start:
  6355. movq $1, %rbx
  6356. movq $42, %rcx
  6357. addq $7, %rbx
  6358. movq %rbx, -16(%rbp)
  6359. addq %rcx, %rbx
  6360. movq -16(%rbp), %rcx
  6361. negq %rcx
  6362. movq %rbx, %rax
  6363. addq %rcx, %rax
  6364. jmp conclusion
  6365. .globl main
  6366. main:
  6367. pushq %rbp
  6368. movq %rsp, %rbp
  6369. pushq %rbx
  6370. subq $8, %rsp
  6371. jmp start
  6372. conclusion:
  6373. addq $8, %rsp
  6374. popq %rbx
  6375. popq %rbp
  6376. retq
  6377. \end{lstlisting}
  6378. \fi}
  6379. {\if\edition\pythonEd\pythonColor
  6380. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6381. \begin{lstlisting}
  6382. .globl main
  6383. main:
  6384. pushq %rbp
  6385. movq %rsp, %rbp
  6386. pushq %rbx
  6387. subq $8, %rsp
  6388. movq $1, %rcx
  6389. movq $42, %rbx
  6390. addq $7, %rcx
  6391. movq %rcx, -16(%rbp)
  6392. addq %rbx, -16(%rbp)
  6393. negq %rcx
  6394. movq -16(%rbp), %rbx
  6395. addq %rcx, %rbx
  6396. movq %rbx, %rdi
  6397. callq print_int
  6398. addq $8, %rsp
  6399. popq %rbx
  6400. popq %rbp
  6401. retq
  6402. \end{lstlisting}
  6403. \fi}
  6404. \end{tcolorbox}
  6405. \end{minipage}
  6406. \caption{The x86 output from the running example
  6407. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6408. and \code{rcx}.}
  6409. \label{fig:running-example-x86}
  6410. \end{figure}
  6411. \begin{exercise}\normalfont\normalsize
  6412. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6413. %
  6414. \racket{
  6415. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6416. list of passes and the call to \code{compiler-tests}.}
  6417. %
  6418. Run the script to test the complete compiler for \LangVar{} that
  6419. performs register allocation.
  6420. \end{exercise}
  6421. \section{Challenge: Move Biasing}
  6422. \label{sec:move-biasing}
  6423. \index{subject}{move biasing}
  6424. This section describes an enhancement to the register allocator,
  6425. called move biasing, for students who are looking for an extra
  6426. challenge.
  6427. {\if\edition\racketEd
  6428. To motivate the need for move biasing we return to the running example,
  6429. but this time we use all the general purpose registers. So, we have
  6430. the following mapping of color numbers to registers.
  6431. \[
  6432. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6433. \]
  6434. Using the same assignment of variables to color numbers that was
  6435. produced by the register allocator described in the last section, we
  6436. get the following program.
  6437. \begin{center}
  6438. \begin{minipage}{0.35\textwidth}
  6439. \begin{lstlisting}
  6440. movq $1, v
  6441. movq $42, w
  6442. movq v, x
  6443. addq $7, x
  6444. movq x, y
  6445. movq x, z
  6446. addq w, z
  6447. movq y, t
  6448. negq t
  6449. movq z, %rax
  6450. addq t, %rax
  6451. jmp conclusion
  6452. \end{lstlisting}
  6453. \end{minipage}
  6454. $\Rightarrow\qquad$
  6455. \begin{minipage}{0.45\textwidth}
  6456. \begin{lstlisting}
  6457. movq $1, %rdx
  6458. movq $42, %rcx
  6459. movq %rdx, %rdx
  6460. addq $7, %rdx
  6461. movq %rdx, %rsi
  6462. movq %rdx, %rdx
  6463. addq %rcx, %rdx
  6464. movq %rsi, %rcx
  6465. negq %rcx
  6466. movq %rdx, %rax
  6467. addq %rcx, %rax
  6468. jmp conclusion
  6469. \end{lstlisting}
  6470. \end{minipage}
  6471. \end{center}
  6472. In this output code there are two \key{movq} instructions that
  6473. can be removed because their source and target are the same. However,
  6474. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6475. register, we could instead remove three \key{movq} instructions. We
  6476. can accomplish this by taking into account which variables appear in
  6477. \key{movq} instructions with which other variables.
  6478. \fi}
  6479. {\if\edition\pythonEd\pythonColor
  6480. %
  6481. To motivate the need for move biasing we return to the running example
  6482. and recall that in section~\ref{sec:patch-instructions} we were able to
  6483. remove three trivial move instructions from the running
  6484. example. However, we could remove another trivial move if we were able
  6485. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6486. We say that two variables $p$ and $q$ are \emph{move
  6487. related}\index{subject}{move related} if they participate together in
  6488. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6489. \key{movq} $q$\key{,} $p$.
  6490. %
  6491. Recall that we color variables that are more saturated before coloring
  6492. variables that are less saturated, and in the case of equally
  6493. saturated variables, we choose randomly. Now we break such ties by
  6494. giving preference to variables that have an available color that is
  6495. the same as the color of a move-related variable.
  6496. %
  6497. Furthermore, when the register allocator chooses a color for a
  6498. variable, it should prefer a color that has already been used for a
  6499. move-related variable if one exists (and assuming that they do not
  6500. interfere). This preference should not override the preference for
  6501. registers over stack locations. So, this preference should be used as
  6502. a tie breaker in choosing between two registers or in choosing between
  6503. two stack locations.
  6504. We recommend representing the move relationships in a graph, similarly
  6505. to how we represented interference. The following is the \emph{move
  6506. graph} for our example.
  6507. {\if\edition\racketEd
  6508. \[
  6509. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6510. \node (rax) at (0,0) {$\ttm{rax}$};
  6511. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6512. \node (t) at (0,2) {$\ttm{t}$};
  6513. \node (z) at (3,2) {$\ttm{z}$};
  6514. \node (x) at (6,2) {$\ttm{x}$};
  6515. \node (y) at (3,0) {$\ttm{y}$};
  6516. \node (w) at (6,0) {$\ttm{w}$};
  6517. \node (v) at (9,0) {$\ttm{v}$};
  6518. \draw (v) to (x);
  6519. \draw (x) to (y);
  6520. \draw (x) to (z);
  6521. \draw (y) to (t);
  6522. \end{tikzpicture}
  6523. \]
  6524. \fi}
  6525. %
  6526. {\if\edition\pythonEd\pythonColor
  6527. \[
  6528. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6529. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6530. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6531. \node (z) at (3,2) {$\ttm{z}$};
  6532. \node (x) at (6,2) {$\ttm{x}$};
  6533. \node (y) at (3,0) {$\ttm{y}$};
  6534. \node (w) at (6,0) {$\ttm{w}$};
  6535. \node (v) at (9,0) {$\ttm{v}$};
  6536. \draw (y) to (t0);
  6537. \draw (z) to (x);
  6538. \draw (z) to (t1);
  6539. \draw (x) to (y);
  6540. \draw (x) to (v);
  6541. \end{tikzpicture}
  6542. \]
  6543. \fi}
  6544. {\if\edition\racketEd
  6545. Now we replay the graph coloring, pausing to see the coloring of
  6546. \code{y}. Recall the following configuration. The most saturated vertices
  6547. were \code{w} and \code{y}.
  6548. \[
  6549. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6550. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6551. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6552. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6553. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6554. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6555. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6556. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6557. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6558. \draw (t1) to (rax);
  6559. \draw (t1) to (z);
  6560. \draw (z) to (y);
  6561. \draw (z) to (w);
  6562. \draw (x) to (w);
  6563. \draw (y) to (w);
  6564. \draw (v) to (w);
  6565. \draw (v) to (rsp);
  6566. \draw (w) to (rsp);
  6567. \draw (x) to (rsp);
  6568. \draw (y) to (rsp);
  6569. \path[-.,bend left=15] (z) edge node {} (rsp);
  6570. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6571. \draw (rax) to (rsp);
  6572. \end{tikzpicture}
  6573. \]
  6574. %
  6575. The last time, we chose to color \code{w} with $0$. This time, we see
  6576. that \code{w} is not move-related to any vertex, but \code{y} is
  6577. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6578. the same color as \code{t}.
  6579. \[
  6580. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6581. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6582. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6583. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6584. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6585. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6586. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6587. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6588. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6589. \draw (t1) to (rax);
  6590. \draw (t1) to (z);
  6591. \draw (z) to (y);
  6592. \draw (z) to (w);
  6593. \draw (x) to (w);
  6594. \draw (y) to (w);
  6595. \draw (v) to (w);
  6596. \draw (v) to (rsp);
  6597. \draw (w) to (rsp);
  6598. \draw (x) to (rsp);
  6599. \draw (y) to (rsp);
  6600. \path[-.,bend left=15] (z) edge node {} (rsp);
  6601. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6602. \draw (rax) to (rsp);
  6603. \end{tikzpicture}
  6604. \]
  6605. Now \code{w} is the most saturated, so we color it $2$.
  6606. \[
  6607. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6608. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6609. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6610. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6611. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6612. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6613. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6614. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6615. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6616. \draw (t1) to (rax);
  6617. \draw (t1) to (z);
  6618. \draw (z) to (y);
  6619. \draw (z) to (w);
  6620. \draw (x) to (w);
  6621. \draw (y) to (w);
  6622. \draw (v) to (w);
  6623. \draw (v) to (rsp);
  6624. \draw (w) to (rsp);
  6625. \draw (x) to (rsp);
  6626. \draw (y) to (rsp);
  6627. \path[-.,bend left=15] (z) edge node {} (rsp);
  6628. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6629. \draw (rax) to (rsp);
  6630. \end{tikzpicture}
  6631. \]
  6632. At this point, vertices \code{x} and \code{v} are most saturated, but
  6633. \code{x} is move related to \code{y} and \code{z}, so we color
  6634. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6635. \[
  6636. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6637. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6638. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6639. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6640. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6641. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6642. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6643. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6644. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6645. \draw (t1) to (rax);
  6646. \draw (t) to (z);
  6647. \draw (z) to (y);
  6648. \draw (z) to (w);
  6649. \draw (x) to (w);
  6650. \draw (y) to (w);
  6651. \draw (v) to (w);
  6652. \draw (v) to (rsp);
  6653. \draw (w) to (rsp);
  6654. \draw (x) to (rsp);
  6655. \draw (y) to (rsp);
  6656. \path[-.,bend left=15] (z) edge node {} (rsp);
  6657. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6658. \draw (rax) to (rsp);
  6659. \end{tikzpicture}
  6660. \]
  6661. \fi}
  6662. %
  6663. {\if\edition\pythonEd\pythonColor
  6664. Now we replay the graph coloring, pausing before the coloring of
  6665. \code{w}. Recall the following configuration. The most saturated vertices
  6666. were \code{tmp\_1}, \code{w}, and \code{y}.
  6667. \[
  6668. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6669. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6670. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6671. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6672. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6673. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6674. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6675. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6676. \draw (t0) to (t1);
  6677. \draw (t0) to (z);
  6678. \draw (z) to (y);
  6679. \draw (z) to (w);
  6680. \draw (x) to (w);
  6681. \draw (y) to (w);
  6682. \draw (v) to (w);
  6683. \end{tikzpicture}
  6684. \]
  6685. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6686. or \code{y}. Note, however, that \code{w} is not move related to any
  6687. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6688. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6689. \code{y} and color it $0$, we can delete another move instruction.
  6690. \[
  6691. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6692. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6693. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6694. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6695. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6696. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6697. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6698. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6699. \draw (t0) to (t1);
  6700. \draw (t0) to (z);
  6701. \draw (z) to (y);
  6702. \draw (z) to (w);
  6703. \draw (x) to (w);
  6704. \draw (y) to (w);
  6705. \draw (v) to (w);
  6706. \end{tikzpicture}
  6707. \]
  6708. Now \code{w} is the most saturated, so we color it $2$.
  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}: -, \{2\}$};
  6715. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6716. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6717. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  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. To finish the coloring, \code{x} and \code{v} get $0$ and
  6728. \code{tmp\_1} gets $1$.
  6729. \[
  6730. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6731. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6732. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6733. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6734. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6735. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6736. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6737. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6738. \draw (t0) to (t1);
  6739. \draw (t0) to (z);
  6740. \draw (z) to (y);
  6741. \draw (z) to (w);
  6742. \draw (x) to (w);
  6743. \draw (y) to (w);
  6744. \draw (v) to (w);
  6745. \end{tikzpicture}
  6746. \]
  6747. \fi}
  6748. So, we have the following assignment of variables to registers.
  6749. {\if\edition\racketEd
  6750. \begin{gather*}
  6751. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6752. \ttm{w} \mapsto \key{\%rsi}, \,
  6753. \ttm{x} \mapsto \key{\%rcx}, \,
  6754. \ttm{y} \mapsto \key{\%rcx}, \,
  6755. \ttm{z} \mapsto \key{\%rdx}, \,
  6756. \ttm{t} \mapsto \key{\%rcx} \}
  6757. \end{gather*}
  6758. \fi}
  6759. {\if\edition\pythonEd\pythonColor
  6760. \begin{gather*}
  6761. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6762. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6763. \ttm{x} \mapsto \key{\%rcx}, \,
  6764. \ttm{y} \mapsto \key{\%rcx}, \\
  6765. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6766. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6767. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6768. \end{gather*}
  6769. \fi}
  6770. %
  6771. We apply this register assignment to the running example shown next,
  6772. on the left, to obtain the code in the middle. The
  6773. \code{patch\_instructions} then deletes the trivial moves to obtain
  6774. the code on the right.
  6775. {\if\edition\racketEd
  6776. \begin{center}
  6777. \begin{minipage}{0.2\textwidth}
  6778. \begin{lstlisting}
  6779. movq $1, v
  6780. movq $42, w
  6781. movq v, x
  6782. addq $7, x
  6783. movq x, y
  6784. movq x, z
  6785. addq w, z
  6786. movq y, t
  6787. negq t
  6788. movq z, %rax
  6789. addq t, %rax
  6790. jmp conclusion
  6791. \end{lstlisting}
  6792. \end{minipage}
  6793. $\Rightarrow\qquad$
  6794. \begin{minipage}{0.25\textwidth}
  6795. \begin{lstlisting}
  6796. movq $1, %rcx
  6797. movq $42, %rsi
  6798. movq %rcx, %rcx
  6799. addq $7, %rcx
  6800. movq %rcx, %rcx
  6801. movq %rcx, %rdx
  6802. addq %rsi, %rdx
  6803. movq %rcx, %rcx
  6804. negq %rcx
  6805. movq %rdx, %rax
  6806. addq %rcx, %rax
  6807. jmp conclusion
  6808. \end{lstlisting}
  6809. \end{minipage}
  6810. $\Rightarrow\qquad$
  6811. \begin{minipage}{0.23\textwidth}
  6812. \begin{lstlisting}
  6813. movq $1, %rcx
  6814. movq $42, %rsi
  6815. addq $7, %rcx
  6816. movq %rcx, %rdx
  6817. addq %rsi, %rdx
  6818. negq %rcx
  6819. movq %rdx, %rax
  6820. addq %rcx, %rax
  6821. jmp conclusion
  6822. \end{lstlisting}
  6823. \end{minipage}
  6824. \end{center}
  6825. \fi}
  6826. {\if\edition\pythonEd\pythonColor
  6827. \begin{center}
  6828. \begin{minipage}{0.20\textwidth}
  6829. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6830. movq $1, v
  6831. movq $42, w
  6832. movq v, x
  6833. addq $7, x
  6834. movq x, y
  6835. movq x, z
  6836. addq w, z
  6837. movq y, tmp_0
  6838. negq tmp_0
  6839. movq z, tmp_1
  6840. addq tmp_0, tmp_1
  6841. movq tmp_1, %rdi
  6842. callq _print_int
  6843. \end{lstlisting}
  6844. \end{minipage}
  6845. ${\Rightarrow\qquad}$
  6846. \begin{minipage}{0.35\textwidth}
  6847. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6848. movq $1, %rcx
  6849. movq $42, -16(%rbp)
  6850. movq %rcx, %rcx
  6851. addq $7, %rcx
  6852. movq %rcx, %rcx
  6853. movq %rcx, -8(%rbp)
  6854. addq -16(%rbp), -8(%rbp)
  6855. movq %rcx, %rcx
  6856. negq %rcx
  6857. movq -8(%rbp), -8(%rbp)
  6858. addq %rcx, -8(%rbp)
  6859. movq -8(%rbp), %rdi
  6860. callq _print_int
  6861. \end{lstlisting}
  6862. \end{minipage}
  6863. ${\Rightarrow\qquad}$
  6864. \begin{minipage}{0.20\textwidth}
  6865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6866. movq $1, %rcx
  6867. movq $42, -16(%rbp)
  6868. addq $7, %rcx
  6869. movq %rcx, -8(%rbp)
  6870. movq -16(%rbp), %rax
  6871. addq %rax, -8(%rbp)
  6872. negq %rcx
  6873. addq %rcx, -8(%rbp)
  6874. movq -8(%rbp), %rdi
  6875. callq print_int
  6876. \end{lstlisting}
  6877. \end{minipage}
  6878. \end{center}
  6879. \fi}
  6880. \begin{exercise}\normalfont\normalsize
  6881. Change your implementation of \code{allocate\_registers} to take move
  6882. biasing into account. Create two new tests that include at least one
  6883. opportunity for move biasing, and visually inspect the output x86
  6884. programs to make sure that your move biasing is working properly. Make
  6885. sure that your compiler still passes all the tests.
  6886. \end{exercise}
  6887. %To do: another neat challenge would be to do
  6888. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6889. %% \subsection{Output of the Running Example}
  6890. %% \label{sec:reg-alloc-output}
  6891. % challenge: prioritize variables based on execution frequencies
  6892. % and the number of uses of a variable
  6893. % challenge: enhance the coloring algorithm using Chaitin's
  6894. % approach of prioritizing high-degree variables
  6895. % by removing low-degree variables (coloring them later)
  6896. % from the interference graph
  6897. \section{Further Reading}
  6898. \label{sec:register-allocation-further-reading}
  6899. Early register allocation algorithms were developed for Fortran
  6900. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6901. of graph coloring began in the late 1970s and early 1980s with the
  6902. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6903. algorithm is based on the following observation of
  6904. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6905. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6906. $v$ removed is also $k$ colorable. To see why, suppose that the
  6907. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6908. different colors, but because there are fewer than $k$ neighbors, there
  6909. will be one or more colors left over to use for coloring $v$ in $G$.
  6910. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6911. less than $k$ from the graph and recursively colors the rest of the
  6912. graph. Upon returning from the recursion, it colors $v$ with one of
  6913. the available colors and returns. \citet{Chaitin:1982vn} augments
  6914. this algorithm to handle spilling as follows. If there are no vertices
  6915. of degree lower than $k$ then pick a vertex at random, spill it,
  6916. remove it from the graph, and proceed recursively to color the rest of
  6917. the graph.
  6918. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6919. move-related and that don't interfere with each other, in a process
  6920. called \emph{coalescing}. Although coalescing decreases the number of
  6921. moves, it can make the graph more difficult to
  6922. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6923. which two variables are merged only if they have fewer than $k$
  6924. neighbors of high degree. \citet{George:1996aa} observes that
  6925. conservative coalescing is sometimes too conservative and made it more
  6926. aggressive by iterating the coalescing with the removal of low-degree
  6927. vertices.
  6928. %
  6929. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6930. also proposed \emph{biased coloring}, in which a variable is assigned to
  6931. the same color as another move-related variable if possible, as
  6932. discussed in section~\ref{sec:move-biasing}.
  6933. %
  6934. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6935. performs coalescing, graph coloring, and spill code insertion until
  6936. all variables have been assigned a location.
  6937. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6938. spilled variables that don't have to be: a high-degree variable can be
  6939. colorable if many of its neighbors are assigned the same color.
  6940. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6941. high-degree vertex is not immediately spilled. Instead the decision is
  6942. deferred until after the recursive call, when it is apparent whether
  6943. there is an available color or not. We observe that this algorithm is
  6944. equivalent to the smallest-last ordering
  6945. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6946. be registers and the rest to be stack locations.
  6947. %% biased coloring
  6948. Earlier editions of the compiler course at Indiana University
  6949. \citep{Dybvig:2010aa} were based on the algorithm of
  6950. \citet{Briggs:1994kx}.
  6951. The smallest-last ordering algorithm is one of many \emph{greedy}
  6952. coloring algorithms. A greedy coloring algorithm visits all the
  6953. vertices in a particular order and assigns each one the first
  6954. available color. An \emph{offline} greedy algorithm chooses the
  6955. ordering up front, prior to assigning colors. The algorithm of
  6956. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6957. ordering does not depend on the colors assigned. Other orderings are
  6958. possible. For example, \citet{Chow:1984ys} ordered variables according
  6959. to an estimate of runtime cost.
  6960. An \emph{online} greedy coloring algorithm uses information about the
  6961. current assignment of colors to influence the order in which the
  6962. remaining vertices are colored. The saturation-based algorithm
  6963. described in this chapter is one such algorithm. We choose to use
  6964. saturation-based coloring because it is fun to introduce graph
  6965. coloring via sudoku!
  6966. A register allocator may choose to map each variable to just one
  6967. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6968. variable to one or more locations. The latter can be achieved by
  6969. \emph{live range splitting}, where a variable is replaced by several
  6970. variables that each handle part of its live
  6971. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6972. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6973. %% replacement algorithm, bottom-up local
  6974. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6975. %% Cooper: top-down (priority bassed), bottom-up
  6976. %% top-down
  6977. %% order variables by priority (estimated cost)
  6978. %% caveat: split variables into two groups:
  6979. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6980. %% color the constrained ones first
  6981. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6982. %% cite J. Cocke for an algorithm that colors variables
  6983. %% in a high-degree first ordering
  6984. %Register Allocation via Usage Counts, Freiburghouse CACM
  6985. \citet{Palsberg:2007si} observes that many of the interference graphs
  6986. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6987. that is, every cycle with four or more edges has an edge that is not
  6988. part of the cycle but that connects two vertices on the cycle. Such
  6989. graphs can be optimally colored by the greedy algorithm with a vertex
  6990. ordering determined by maximum cardinality search.
  6991. In situations in which compile time is of utmost importance, such as
  6992. in just-in-time compilers, graph coloring algorithms can be too
  6993. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6994. be more appropriate.
  6995. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6996. {\if\edition\racketEd
  6997. \addtocontents{toc}{\newpage}
  6998. \fi}
  6999. \chapter{Booleans and Conditionals}
  7000. \label{ch:Lif}
  7001. \setcounter{footnote}{0}
  7002. The \LangVar{} language has only a single kind of value, the
  7003. integers. In this chapter we add a second kind of value, the Booleans,
  7004. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7005. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7006. are written
  7007. \TRUE{}\index{subject}{True@\TRUE{}} and
  7008. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7009. language includes several operations that involve Booleans
  7010. (\key{and}\index{subject}{and@\ANDNAME{}},
  7011. \key{or}\index{subject}{or@\ORNAME{}},
  7012. \key{not}\index{subject}{not@\NOTNAME{}},
  7013. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7014. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7015. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7016. conditional expression\index{subject}{conditional expression}%
  7017. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7018. With the addition of \key{if}, programs can have
  7019. nontrivial control flow\index{subject}{control flow}, which
  7020. %
  7021. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7022. %
  7023. \python{impacts liveness analysis and motivates a new pass named
  7024. \code{explicate\_control}.}
  7025. %
  7026. Also, because we now have two kinds of values, we need to handle
  7027. programs that apply an operation to the wrong kind of value, such as
  7028. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7029. There are two language design options for such situations. One option
  7030. is to signal an error and the other is to provide a wider
  7031. interpretation of the operation. \racket{The Racket
  7032. language}\python{Python} uses a mixture of these two options,
  7033. depending on the operation and the kind of value. For example, the
  7034. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7035. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7036. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7037. %
  7038. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7039. in Racket because \code{car} expects a pair.}
  7040. %
  7041. \python{On the other hand, \code{1[0]} results in a runtime error
  7042. in Python because an ``\code{int} object is not subscriptable.''}
  7043. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7044. design choices as \racket{Racket}\python{Python}, except that much of the
  7045. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7046. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7047. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7048. \python{MyPy} reports a compile-time error
  7049. %
  7050. \racket{because Racket expects the type of the argument to be of the form
  7051. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7052. %
  7053. \python{stating that a ``value of type \code{int} is not indexable.''}
  7054. The \LangIf{} language performs type checking during compilation just as
  7055. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7056. the alternative choice, that is, a dynamically typed language like
  7057. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7058. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7059. restrictive, for example, rejecting \racket{\code{(not
  7060. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7061. fairly simple because the focus of this book is on compilation and not
  7062. type systems, about which there are already several excellent
  7063. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7064. This chapter is organized as follows. We begin by defining the syntax
  7065. and interpreter for the \LangIf{} language
  7066. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7067. checking (aka semantic analysis\index{subject}{semantic analysis})
  7068. and define a type checker for \LangIf{}
  7069. (section~\ref{sec:type-check-Lif}).
  7070. %
  7071. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7072. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7073. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7074. %
  7075. The remaining sections of this chapter discuss how Booleans and
  7076. conditional control flow require changes to the existing compiler
  7077. passes and the addition of new ones. We introduce the \code{shrink}
  7078. pass to translate some operators into others, thereby reducing the
  7079. number of operators that need to be handled in later passes.
  7080. %
  7081. The main event of this chapter is the \code{explicate\_control} pass
  7082. that is responsible for translating \code{if}s into conditional
  7083. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7084. %
  7085. Regarding register allocation, there is the interesting question of
  7086. how to handle conditional \code{goto}s during liveness analysis.
  7087. \section{The \LangIf{} Language}
  7088. \label{sec:lang-if}
  7089. Definitions of the concrete syntax and abstract syntax of the
  7090. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7091. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7092. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7093. literals\index{subject}{literals}
  7094. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7095. \python{, and the \code{if} statement}. We expand the set of
  7096. operators to include
  7097. \begin{enumerate}
  7098. \item the logical operators \key{and}, \key{or}, and \key{not},
  7099. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7100. for comparing integers or Booleans for equality, and
  7101. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7102. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7103. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7104. comparing integers.
  7105. \end{enumerate}
  7106. \racket{We reorganize the abstract syntax for the primitive
  7107. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7108. rule for all of them. This means that the grammar no longer checks
  7109. whether the arity of an operator matches the number of
  7110. arguments. That responsibility is moved to the type checker for
  7111. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7112. \newcommand{\LifGrammarRacket}{
  7113. \begin{array}{lcl}
  7114. \Type &::=& \key{Boolean} \\
  7115. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7116. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7117. \Exp &::=& \itm{bool}
  7118. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7119. \MID (\key{not}\;\Exp) \\
  7120. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7121. \end{array}
  7122. }
  7123. \newcommand{\LifASTRacket}{
  7124. \begin{array}{lcl}
  7125. \Type &::=& \key{Boolean} \\
  7126. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7127. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7128. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7129. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7130. \end{array}
  7131. }
  7132. \newcommand{\LintOpAST}{
  7133. \begin{array}{rcl}
  7134. \Type &::=& \key{Integer} \\
  7135. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7136. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7137. \end{array}
  7138. }
  7139. \newcommand{\LifGrammarPython}{
  7140. \begin{array}{rcl}
  7141. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7142. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7143. \MID \key{not}~\Exp \\
  7144. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7145. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7146. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7147. \end{array}
  7148. }
  7149. \newcommand{\LifASTPython}{
  7150. \begin{array}{lcl}
  7151. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7152. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7153. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7154. \Exp &::=& \BOOL{\itm{bool}}
  7155. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7156. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7157. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7158. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7159. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7160. \end{array}
  7161. }
  7162. \begin{figure}[tp]
  7163. \centering
  7164. \begin{tcolorbox}[colback=white]
  7165. {\if\edition\racketEd
  7166. \[
  7167. \begin{array}{l}
  7168. \gray{\LintGrammarRacket{}} \\ \hline
  7169. \gray{\LvarGrammarRacket{}} \\ \hline
  7170. \LifGrammarRacket{} \\
  7171. \begin{array}{lcl}
  7172. \LangIfM{} &::=& \Exp
  7173. \end{array}
  7174. \end{array}
  7175. \]
  7176. \fi}
  7177. {\if\edition\pythonEd\pythonColor
  7178. \[
  7179. \begin{array}{l}
  7180. \gray{\LintGrammarPython} \\ \hline
  7181. \gray{\LvarGrammarPython} \\ \hline
  7182. \LifGrammarPython \\
  7183. \begin{array}{rcl}
  7184. \LangIfM{} &::=& \Stmt^{*}
  7185. \end{array}
  7186. \end{array}
  7187. \]
  7188. \fi}
  7189. \end{tcolorbox}
  7190. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7191. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7192. \label{fig:Lif-concrete-syntax}
  7193. \end{figure}
  7194. \begin{figure}[tp]
  7195. %\begin{minipage}{0.66\textwidth}
  7196. \begin{tcolorbox}[colback=white]
  7197. \centering
  7198. {\if\edition\racketEd
  7199. \[
  7200. \begin{array}{l}
  7201. \gray{\LintOpAST} \\ \hline
  7202. \gray{\LvarASTRacket{}} \\ \hline
  7203. \LifASTRacket{} \\
  7204. \begin{array}{lcl}
  7205. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7206. \end{array}
  7207. \end{array}
  7208. \]
  7209. \fi}
  7210. {\if\edition\pythonEd\pythonColor
  7211. \[
  7212. \begin{array}{l}
  7213. \gray{\LintASTPython} \\ \hline
  7214. \gray{\LvarASTPython} \\ \hline
  7215. \LifASTPython \\
  7216. \begin{array}{lcl}
  7217. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7218. \end{array}
  7219. \end{array}
  7220. \]
  7221. \fi}
  7222. \end{tcolorbox}
  7223. %\end{minipage}
  7224. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7225. \python{
  7226. \index{subject}{BoolOp@\texttt{BoolOp}}
  7227. \index{subject}{Compare@\texttt{Compare}}
  7228. \index{subject}{Lt@\texttt{Lt}}
  7229. \index{subject}{LtE@\texttt{LtE}}
  7230. \index{subject}{Gt@\texttt{Gt}}
  7231. \index{subject}{GtE@\texttt{GtE}}
  7232. }
  7233. \caption{The abstract syntax of \LangIf{}.}
  7234. \label{fig:Lif-syntax}
  7235. \end{figure}
  7236. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7237. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7238. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7239. evaluate to the corresponding Boolean values, which is
  7240. inherited from the interpreter for \LangInt{} (figure~\ref{fig:interp-Lint-class}).
  7241. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7242. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7243. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7244. \code{and}, \code{or}, and \code{not} behave according to propositional
  7245. logic. In addition, the \code{and} and \code{or} operations perform
  7246. \emph{short-circuit evaluation}.
  7247. %
  7248. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7249. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7250. %
  7251. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7252. evaluated if $e_1$ evaluates to \TRUE{}.
  7253. \racket{With the increase in the number of primitive operations, the
  7254. interpreter would become repetitive without some care. We refactor
  7255. the case for \code{Prim}, moving the code that differs with each
  7256. operation into the \code{interp\_op} method shown in
  7257. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7258. \code{or} operations separately because of their short-circuiting
  7259. behavior.}
  7260. \begin{figure}[tbp]
  7261. \begin{tcolorbox}[colback=white]
  7262. {\if\edition\racketEd
  7263. \begin{lstlisting}
  7264. (define interp-Lif-class
  7265. (class interp-Lvar-class
  7266. (super-new)
  7267. (define/public (interp_op op) ...)
  7268. (define/override ((interp_exp env) e)
  7269. (define recur (interp_exp env))
  7270. (match e
  7271. [(Bool b) b]
  7272. [(If cnd thn els)
  7273. (match (recur cnd)
  7274. [#t (recur thn)]
  7275. [#f (recur els)])]
  7276. [(Prim 'and (list e1 e2))
  7277. (match (recur e1)
  7278. [#t (match (recur e2) [#t #t] [#f #f])]
  7279. [#f #f])]
  7280. [(Prim 'or (list e1 e2))
  7281. (define v1 (recur e1))
  7282. (match v1
  7283. [#t #t]
  7284. [#f (match (recur e2) [#t #t] [#f #f])])]
  7285. [(Prim op args)
  7286. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7287. [else ((super interp_exp env) e)]))
  7288. ))
  7289. (define (interp_Lif p)
  7290. (send (new interp-Lif-class) interp_program p))
  7291. \end{lstlisting}
  7292. \fi}
  7293. {\if\edition\pythonEd\pythonColor
  7294. \begin{lstlisting}
  7295. class InterpLif(InterpLvar):
  7296. def interp_exp(self, e, env):
  7297. match e:
  7298. case IfExp(test, body, orelse):
  7299. if self.interp_exp(test, env):
  7300. return self.interp_exp(body, env)
  7301. else:
  7302. return self.interp_exp(orelse, env)
  7303. case UnaryOp(Not(), v):
  7304. return not self.interp_exp(v, env)
  7305. case BoolOp(And(), values):
  7306. if self.interp_exp(values[0], env):
  7307. return self.interp_exp(values[1], env)
  7308. else:
  7309. return False
  7310. case BoolOp(Or(), values):
  7311. if self.interp_exp(values[0], env):
  7312. return True
  7313. else:
  7314. return self.interp_exp(values[1], env)
  7315. case Compare(left, [cmp], [right]):
  7316. l = self.interp_exp(left, env)
  7317. r = self.interp_exp(right, env)
  7318. return self.interp_cmp(cmp)(l, r)
  7319. case _:
  7320. return super().interp_exp(e, env)
  7321. def interp_stmt(self, s, env, cont):
  7322. match s:
  7323. case If(test, body, orelse):
  7324. match self.interp_exp(test, env):
  7325. case True:
  7326. return self.interp_stmts(body + cont, env)
  7327. case False:
  7328. return self.interp_stmts(orelse + cont, env)
  7329. case _:
  7330. return super().interp_stmt(s, env, cont)
  7331. ...
  7332. \end{lstlisting}
  7333. \fi}
  7334. \end{tcolorbox}
  7335. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7336. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7337. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7338. \label{fig:interp-Lif}
  7339. \end{figure}
  7340. {\if\edition\racketEd
  7341. \begin{figure}[tbp]
  7342. \begin{tcolorbox}[colback=white]
  7343. \begin{lstlisting}
  7344. (define/public (interp_op op)
  7345. (match op
  7346. ['+ fx+]
  7347. ['- fx-]
  7348. ['read read-fixnum]
  7349. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7350. ['eq? (lambda (v1 v2)
  7351. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7352. (and (boolean? v1) (boolean? v2))
  7353. (and (vector? v1) (vector? v2)))
  7354. (eq? v1 v2)]))]
  7355. ['< (lambda (v1 v2)
  7356. (cond [(and (fixnum? v1) (fixnum? v2))
  7357. (< v1 v2)]))]
  7358. ['<= (lambda (v1 v2)
  7359. (cond [(and (fixnum? v1) (fixnum? v2))
  7360. (<= v1 v2)]))]
  7361. ['> (lambda (v1 v2)
  7362. (cond [(and (fixnum? v1) (fixnum? v2))
  7363. (> v1 v2)]))]
  7364. ['>= (lambda (v1 v2)
  7365. (cond [(and (fixnum? v1) (fixnum? v2))
  7366. (>= v1 v2)]))]
  7367. [else (error 'interp_op "unknown operator")]))
  7368. \end{lstlisting}
  7369. \end{tcolorbox}
  7370. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7371. \label{fig:interp-op-Lif}
  7372. \end{figure}
  7373. \fi}
  7374. {\if\edition\pythonEd\pythonColor
  7375. \begin{figure}
  7376. \begin{tcolorbox}[colback=white]
  7377. \begin{lstlisting}
  7378. class InterpLif(InterpLvar):
  7379. ...
  7380. def interp_cmp(self, cmp):
  7381. match cmp:
  7382. case Lt():
  7383. return lambda x, y: x < y
  7384. case LtE():
  7385. return lambda x, y: x <= y
  7386. case Gt():
  7387. return lambda x, y: x > y
  7388. case GtE():
  7389. return lambda x, y: x >= y
  7390. case Eq():
  7391. return lambda x, y: x == y
  7392. case NotEq():
  7393. return lambda x, y: x != y
  7394. \end{lstlisting}
  7395. \end{tcolorbox}
  7396. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7397. \label{fig:interp-cmp-Lif}
  7398. \end{figure}
  7399. \fi}
  7400. \section{Type Checking \LangIf{} Programs}
  7401. \label{sec:type-check-Lif}
  7402. It is helpful to think about type checking\index{subject}{type
  7403. checking} in two complementary ways. A type checker predicts the
  7404. type of value that will be produced by each expression in the program.
  7405. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7406. type checker should predict that {\if\edition\racketEd
  7407. \begin{lstlisting}
  7408. (+ 10 (- (+ 12 20)))
  7409. \end{lstlisting}
  7410. \fi}
  7411. {\if\edition\pythonEd\pythonColor
  7412. \begin{lstlisting}
  7413. 10 + -(12 + 20)
  7414. \end{lstlisting}
  7415. \fi}
  7416. \noindent produces a value of type \INTTY{}, whereas
  7417. {\if\edition\racketEd
  7418. \begin{lstlisting}
  7419. (and (not #f) #t)
  7420. \end{lstlisting}
  7421. \fi}
  7422. {\if\edition\pythonEd\pythonColor
  7423. \begin{lstlisting}
  7424. (not False) and True
  7425. \end{lstlisting}
  7426. \fi}
  7427. \noindent produces a value of type \BOOLTY{}.
  7428. A second way to think about type checking is that it enforces a set of
  7429. rules about which operators can be applied to which kinds of
  7430. values. For example, our type checker for \LangIf{} signals an error
  7431. for the following expression:
  7432. %
  7433. {\if\edition\racketEd
  7434. \begin{lstlisting}
  7435. (not (+ 10 (- (+ 12 20))))
  7436. \end{lstlisting}
  7437. \fi}
  7438. {\if\edition\pythonEd\pythonColor
  7439. \begin{lstlisting}
  7440. not (10 + -(12 + 20))
  7441. \end{lstlisting}
  7442. \fi}
  7443. \noindent The subexpression
  7444. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7445. \python{\code{(10 + -(12 + 20))}}
  7446. has type \INTTY{}, but the type checker enforces the rule that the
  7447. argument of \code{not} must be an expression of type \BOOLTY{}.
  7448. We implement type checking using classes and methods because they
  7449. provide the open recursion needed to reuse code as we extend the type
  7450. checker in subsequent chapters, analogous to the use of classes and methods
  7451. for the interpreters (section~\ref{sec:extensible-interp}).
  7452. We separate the type checker for the \LangVar{} subset into its own
  7453. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7454. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7455. from the type checker for \LangVar{}. These type checkers are in the
  7456. files
  7457. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7458. and
  7459. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7460. of the support code.
  7461. %
  7462. Each type checker is a structurally recursive function over the AST.
  7463. Given an input expression \code{e}, the type checker either signals an
  7464. error or returns \racket{an expression and its type.}\python{its type.}
  7465. %
  7466. \racket{It returns an expression because there are situations in which
  7467. we want to change or update the expression.}
  7468. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7469. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7470. constant is \INTTY{}. To handle variables, the type checker uses the
  7471. environment \code{env} to map variables to types.
  7472. %
  7473. \racket{Consider the case for \key{let}. We type check the
  7474. initializing expression to obtain its type \key{T} and then
  7475. associate type \code{T} with the variable \code{x} in the
  7476. environment used to type check the body of the \key{let}. Thus,
  7477. when the type checker encounters a use of variable \code{x}, it can
  7478. find its type in the environment.}
  7479. %
  7480. \python{Consider the case for assignment. We type check the
  7481. initializing expression to obtain its type \key{t}. If the variable
  7482. \code{id} is already in the environment because there was a
  7483. prior assignment, we check that this initializer has the same type
  7484. as the prior one. If this is the first assignment to the variable,
  7485. we associate type \code{t} with the variable \code{id} in the
  7486. environment. Thus, when the type checker encounters a use of
  7487. variable \code{x}, it can find its type in the environment.}
  7488. %
  7489. \racket{Regarding primitive operators, we recursively analyze the
  7490. arguments and then invoke \code{type\_check\_op} to check whether
  7491. the argument types are allowed.}
  7492. %
  7493. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7494. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7495. \racket{Several auxiliary methods are used in the type checker. The
  7496. method \code{operator-types} defines a dictionary that maps the
  7497. operator names to their parameter and return types. The
  7498. \code{type-equal?} method determines whether two types are equal,
  7499. which for now simply dispatches to \code{equal?} (deep
  7500. equality). The \code{check-type-equal?} method triggers an error if
  7501. the two types are not equal. The \code{type-check-op} method looks
  7502. up the operator in the \code{operator-types} dictionary and then
  7503. checks whether the argument types are equal to the parameter types.
  7504. The result is the return type of the operator.}
  7505. %
  7506. \python{The auxiliary method \code{check\_type\_equal} triggers
  7507. an error if the two types are not equal.}
  7508. \begin{figure}[tbp]
  7509. \begin{tcolorbox}[colback=white]
  7510. {\if\edition\racketEd
  7511. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7512. (define type-check-Lvar-class
  7513. (class object%
  7514. (super-new)
  7515. (define/public (operator-types)
  7516. '((+ . ((Integer Integer) . Integer))
  7517. (- . ((Integer Integer) . Integer))
  7518. (read . (() . Integer))))
  7519. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7520. (define/public (check-type-equal? t1 t2 e)
  7521. (unless (type-equal? t1 t2)
  7522. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7523. (define/public (type-check-op op arg-types e)
  7524. (match (dict-ref (operator-types) op)
  7525. [`(,param-types . ,return-type)
  7526. (for ([at arg-types] [pt param-types])
  7527. (check-type-equal? at pt e))
  7528. return-type]
  7529. [else (error 'type-check-op "unrecognized ~a" op)]))
  7530. (define/public (type-check-exp env)
  7531. (lambda (e)
  7532. (match e
  7533. [(Int n) (values (Int n) 'Integer)]
  7534. [(Var x) (values (Var x) (dict-ref env x))]
  7535. [(Let x e body)
  7536. (define-values (e^ Te) ((type-check-exp env) e))
  7537. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7538. (values (Let x e^ b) Tb)]
  7539. [(Prim op es)
  7540. (define-values (new-es ts)
  7541. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7542. (values (Prim op new-es) (type-check-op op ts e))]
  7543. [else (error 'type-check-exp "couldn't match" e)])))
  7544. (define/public (type-check-program e)
  7545. (match e
  7546. [(Program info body)
  7547. (define-values (body^ Tb) ((type-check-exp '()) body))
  7548. (check-type-equal? Tb 'Integer body)
  7549. (Program info body^)]
  7550. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7551. ))
  7552. (define (type-check-Lvar p)
  7553. (send (new type-check-Lvar-class) type-check-program p))
  7554. \end{lstlisting}
  7555. \fi}
  7556. {\if\edition\pythonEd\pythonColor
  7557. \begin{lstlisting}[escapechar=`]
  7558. class TypeCheckLvar:
  7559. def check_type_equal(self, t1, t2, e):
  7560. if t1 != t2:
  7561. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7562. raise Exception(msg)
  7563. def type_check_exp(self, e, env):
  7564. match e:
  7565. case BinOp(left, (Add() | Sub()), right):
  7566. l = self.type_check_exp(left, env)
  7567. check_type_equal(l, int, left)
  7568. r = self.type_check_exp(right, env)
  7569. check_type_equal(r, int, right)
  7570. return int
  7571. case UnaryOp(USub(), v):
  7572. t = self.type_check_exp(v, env)
  7573. check_type_equal(t, int, v)
  7574. return int
  7575. case Name(id):
  7576. return env[id]
  7577. case Constant(value) if isinstance(value, int):
  7578. return int
  7579. case Call(Name('input_int'), []):
  7580. return int
  7581. def type_check_stmts(self, ss, env):
  7582. if len(ss) == 0:
  7583. return
  7584. match ss[0]:
  7585. case Assign([Name(id)], value):
  7586. t = self.type_check_exp(value, env)
  7587. if id in env:
  7588. check_type_equal(env[id], t, value)
  7589. else:
  7590. env[id] = t
  7591. return self.type_check_stmts(ss[1:], env)
  7592. case Expr(Call(Name('print'), [arg])):
  7593. t = self.type_check_exp(arg, env)
  7594. check_type_equal(t, int, arg)
  7595. return self.type_check_stmts(ss[1:], env)
  7596. case Expr(value):
  7597. self.type_check_exp(value, env)
  7598. return self.type_check_stmts(ss[1:], env)
  7599. def type_check_P(self, p):
  7600. match p:
  7601. case Module(body):
  7602. self.type_check_stmts(body, {})
  7603. \end{lstlisting}
  7604. \fi}
  7605. \end{tcolorbox}
  7606. \caption{Type checker for the \LangVar{} language.}
  7607. \label{fig:type-check-Lvar}
  7608. \end{figure}
  7609. \begin{figure}[tbp]
  7610. \begin{tcolorbox}[colback=white]
  7611. {\if\edition\racketEd
  7612. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7613. (define type-check-Lif-class
  7614. (class type-check-Lvar-class
  7615. (super-new)
  7616. (inherit check-type-equal?)
  7617. (define/override (operator-types)
  7618. (append '((and . ((Boolean Boolean) . Boolean))
  7619. (or . ((Boolean Boolean) . Boolean))
  7620. (< . ((Integer Integer) . Boolean))
  7621. (<= . ((Integer Integer) . Boolean))
  7622. (> . ((Integer Integer) . Boolean))
  7623. (>= . ((Integer Integer) . Boolean))
  7624. (not . ((Boolean) . Boolean)))
  7625. (super operator-types)))
  7626. (define/override (type-check-exp env)
  7627. (lambda (e)
  7628. (match e
  7629. [(Bool b) (values (Bool b) 'Boolean)]
  7630. [(Prim 'eq? (list e1 e2))
  7631. (define-values (e1^ T1) ((type-check-exp env) e1))
  7632. (define-values (e2^ T2) ((type-check-exp env) e2))
  7633. (check-type-equal? T1 T2 e)
  7634. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7635. [(If cnd thn els)
  7636. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7637. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7638. (define-values (els^ Te) ((type-check-exp env) els))
  7639. (check-type-equal? Tc 'Boolean e)
  7640. (check-type-equal? Tt Te e)
  7641. (values (If cnd^ thn^ els^) Te)]
  7642. [else ((super type-check-exp env) e)])))
  7643. ))
  7644. (define (type-check-Lif p)
  7645. (send (new type-check-Lif-class) type-check-program p))
  7646. \end{lstlisting}
  7647. \fi}
  7648. {\if\edition\pythonEd\pythonColor
  7649. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7650. class TypeCheckLif(TypeCheckLvar):
  7651. def type_check_exp(self, e, env):
  7652. match e:
  7653. case Constant(value) if isinstance(value, bool):
  7654. return bool
  7655. case BinOp(left, Sub(), right):
  7656. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7657. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7658. return int
  7659. case UnaryOp(Not(), v):
  7660. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7661. return bool
  7662. case BoolOp(op, values):
  7663. left = values[0] ; right = values[1]
  7664. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7665. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7666. return bool
  7667. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7668. or isinstance(cmp, NotEq):
  7669. l = self.type_check_exp(left, env)
  7670. r = self.type_check_exp(right, env)
  7671. check_type_equal(l, r, e)
  7672. return bool
  7673. case Compare(left, [cmp], [right]):
  7674. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7675. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7676. return bool
  7677. case IfExp(test, body, orelse):
  7678. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7679. b = self.type_check_exp(body, env)
  7680. o = self.type_check_exp(orelse, env)
  7681. check_type_equal(b, o, e)
  7682. return b
  7683. case _:
  7684. return super().type_check_exp(e, env)
  7685. def type_check_stmts(self, ss, env):
  7686. if len(ss) == 0:
  7687. return
  7688. match ss[0]:
  7689. case If(test, body, orelse):
  7690. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7691. b = self.type_check_stmts(body, env)
  7692. o = self.type_check_stmts(orelse, env)
  7693. check_type_equal(b, o, ss[0])
  7694. return self.type_check_stmts(ss[1:], env)
  7695. case _:
  7696. return super().type_check_stmts(ss, env)
  7697. \end{lstlisting}
  7698. \fi}
  7699. \end{tcolorbox}
  7700. \caption{Type checker for the \LangIf{} language.}
  7701. \label{fig:type-check-Lif}
  7702. \end{figure}
  7703. The definition of the type checker for \LangIf{} is shown in
  7704. figure~\ref{fig:type-check-Lif}.
  7705. %
  7706. The type of a Boolean constant is \BOOLTY{}.
  7707. %
  7708. \racket{The \code{operator-types} function adds dictionary entries for
  7709. the new operators.}
  7710. %
  7711. \python{The logical \code{not} operator requires its argument to be a
  7712. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7713. and logical \code{or} operators.}
  7714. %
  7715. The equality operator requires the two arguments to have the same type,
  7716. and therefore we handle it separately from the other operators.
  7717. %
  7718. \python{The other comparisons (less-than, etc.) require their
  7719. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7720. %
  7721. The condition of an \code{if} must
  7722. be of \BOOLTY{} type, and the two branches must have the same type.
  7723. \begin{exercise}\normalfont\normalsize
  7724. Create ten new test programs in \LangIf{}. Half the programs should
  7725. have a type error.
  7726. \racket{For those programs, create an empty file with the
  7727. same base name and with file extension \code{.tyerr}. For example, if
  7728. the test \code{cond\_test\_14.rkt}
  7729. is expected to error, then create
  7730. an empty file named \code{cond\_test\_14.tyerr}.
  7731. This indicates to \code{interp-tests} and
  7732. \code{compiler-tests} that a type error is expected.}
  7733. %
  7734. The other half of the test programs should not have type errors.
  7735. %
  7736. \racket{In the \code{run-tests.rkt} script, change the second argument
  7737. of \code{interp-tests} and \code{compiler-tests} to
  7738. \code{type-check-Lif}, which causes the type checker to run prior to
  7739. the compiler passes. Temporarily change the \code{passes} to an
  7740. empty list and run the script, thereby checking that the new test
  7741. programs either type check or do not, as intended.}
  7742. %
  7743. Run the test script to check that these test programs type check as
  7744. expected.
  7745. \end{exercise}
  7746. \clearpage
  7747. \section{The \LangCIf{} Intermediate Language}
  7748. \label{sec:Cif}
  7749. {\if\edition\racketEd
  7750. %
  7751. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7752. comparison operators to the \Exp{} nonterminal and the literals
  7753. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7754. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7755. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7756. comparison operation and the branches are \code{goto} statements,
  7757. making it straightforward to compile \code{if} statements to x86. The
  7758. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7759. expressions. A \code{goto} statement transfers control to the $\Tail$
  7760. expression corresponding to its label.
  7761. %
  7762. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7763. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7764. defines its abstract syntax.
  7765. %
  7766. \fi}
  7767. %
  7768. {\if\edition\pythonEd\pythonColor
  7769. %
  7770. The output of \key{explicate\_control} is a language similar to the
  7771. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7772. \code{goto} statements, so we name it \LangCIf{}.
  7773. %
  7774. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7775. the arguments of operators are restricted to atomic expressions. The
  7776. \LangCIf{} language does not include \code{if} expressions, but it does
  7777. include a restricted form of \code{if} statement. The condition must be
  7778. a comparison, and the two branches may contain only \code{goto}
  7779. statements. These restrictions make it easier to translate \code{if}
  7780. statements to x86. The \LangCIf{} language also adds a \code{return}
  7781. statement to finish the program with a specified value.
  7782. %
  7783. The \key{CProgram} construct contains a dictionary mapping labels to
  7784. lists of statements that end with a \emph{tail} statement, which is
  7785. either a \code{return} statement, a \code{goto}, or an
  7786. \code{if} statement.
  7787. %
  7788. A \code{goto} transfers control to the sequence of statements
  7789. associated with its label.
  7790. %
  7791. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7792. and figure~\ref{fig:c1-syntax} shows its
  7793. abstract syntax.
  7794. %
  7795. \fi}
  7796. %
  7797. \newcommand{\CifGrammarRacket}{
  7798. \begin{array}{lcl}
  7799. \Atm &::=& \itm{bool} \\
  7800. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7801. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7802. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7803. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7804. \end{array}
  7805. }
  7806. \newcommand{\CifASTRacket}{
  7807. \begin{array}{lcl}
  7808. \Atm &::=& \BOOL{\itm{bool}} \\
  7809. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7810. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7811. \Tail &::= & \GOTO{\itm{label}} \\
  7812. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7813. \end{array}
  7814. }
  7815. \newcommand{\CifGrammarPython}{
  7816. \begin{array}{lcl}
  7817. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7818. \Exp &::= & \Atm \MID \CREAD{}
  7819. \MID \CUNIOP{\key{-}}{\Atm}
  7820. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7821. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7822. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7823. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7824. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7825. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7826. \end{array}
  7827. }
  7828. \newcommand{\CifASTPython}{
  7829. \begin{array}{lcl}
  7830. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7831. \Exp &::= & \Atm \MID \READ{}
  7832. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7833. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7834. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7835. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7836. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7837. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7838. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7839. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7840. \end{array}
  7841. }
  7842. \begin{figure}[tbp]
  7843. \begin{tcolorbox}[colback=white]
  7844. \small
  7845. {\if\edition\racketEd
  7846. \[
  7847. \begin{array}{l}
  7848. \gray{\CvarGrammarRacket} \\ \hline
  7849. \CifGrammarRacket \\
  7850. \begin{array}{lcl}
  7851. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7852. \end{array}
  7853. \end{array}
  7854. \]
  7855. \fi}
  7856. {\if\edition\pythonEd\pythonColor
  7857. \[
  7858. \begin{array}{l}
  7859. \CifGrammarPython \\
  7860. \begin{array}{lcl}
  7861. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7862. \end{array}
  7863. \end{array}
  7864. \]
  7865. \fi}
  7866. \end{tcolorbox}
  7867. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7868. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7869. \label{fig:c1-concrete-syntax}
  7870. \end{figure}
  7871. \begin{figure}[tp]
  7872. \begin{tcolorbox}[colback=white]
  7873. \small
  7874. {\if\edition\racketEd
  7875. \[
  7876. \begin{array}{l}
  7877. \gray{\CvarASTRacket} \\ \hline
  7878. \CifASTRacket \\
  7879. \begin{array}{lcl}
  7880. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7881. \end{array}
  7882. \end{array}
  7883. \]
  7884. \fi}
  7885. {\if\edition\pythonEd\pythonColor
  7886. \[
  7887. \begin{array}{l}
  7888. \CifASTPython \\
  7889. \begin{array}{lcl}
  7890. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7891. \end{array}
  7892. \end{array}
  7893. \]
  7894. \fi}
  7895. \end{tcolorbox}
  7896. \racket{
  7897. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7898. }
  7899. \index{subject}{Goto@\texttt{Goto}}
  7900. \index{subject}{Return@\texttt{Return}}
  7901. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7902. (figure~\ref{fig:c0-syntax})}.}
  7903. \label{fig:c1-syntax}
  7904. \end{figure}
  7905. \section{The \LangXIf{} Language}
  7906. \label{sec:x86-if}
  7907. \index{subject}{x86}
  7908. To implement Booleans, the new logical operations, the
  7909. comparison operations, and the \key{if} expression\python{ and
  7910. statement}, we delve further into the x86
  7911. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7912. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7913. subset of x86, which includes instructions for logical operations,
  7914. comparisons, and \racket{conditional} jumps.
  7915. %
  7916. \python{The abstract syntax for an \LangXIf{} program contains a
  7917. dictionary mapping labels to sequences of instructions, each of
  7918. which we refer to as a \emph{basic block}\index{subject}{basic
  7919. block}.}
  7920. As x86 does not provide direct support for Booleans, we take the usual
  7921. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7922. \code{False} as $0$.
  7923. Furthermore, x86 does not provide an instruction that directly
  7924. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7925. However, the \code{xorq} instruction can be used to encode \code{not}.
  7926. The \key{xorq} instruction takes two arguments, performs a pairwise
  7927. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7928. and writes the results into its second argument. Recall the following
  7929. truth table for exclusive-or:
  7930. \begin{center}
  7931. \begin{tabular}{l|cc}
  7932. & 0 & 1 \\ \hline
  7933. 0 & 0 & 1 \\
  7934. 1 & 1 & 0
  7935. \end{tabular}
  7936. \end{center}
  7937. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7938. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7939. for the bit $1$, the result is the opposite of the second bit. Thus,
  7940. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7941. the first argument, as follows, where $\Arg$ is the translation of
  7942. $\Atm$ to x86:
  7943. \[
  7944. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7945. \qquad\Rightarrow\qquad
  7946. \begin{array}{l}
  7947. \key{movq}~ \Arg\key{,} \Var\\
  7948. \key{xorq}~ \key{\$1,} \Var
  7949. \end{array}
  7950. \]
  7951. \newcommand{\GrammarXIf}{
  7952. \begin{array}{lcl}
  7953. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7954. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7955. \Arg &::=& \key{\%}\itm{bytereg}\\
  7956. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7957. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7958. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7959. \MID \key{set}cc~\Arg
  7960. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7961. &\MID& \key{j}cc~\itm{label} \\
  7962. \end{array}
  7963. }
  7964. \begin{figure}[tp]
  7965. \begin{tcolorbox}[colback=white]
  7966. \[
  7967. \begin{array}{l}
  7968. \gray{\GrammarXInt} \\ \hline
  7969. \GrammarXIf \\
  7970. \begin{array}{lcl}
  7971. \LangXIfM{} &::= & \key{.globl main} \\
  7972. & & \key{main:} \; \Instr\ldots
  7973. \end{array}
  7974. \end{array}
  7975. \]
  7976. \end{tcolorbox}
  7977. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7978. \label{fig:x86-1-concrete}
  7979. \end{figure}
  7980. \newcommand{\ASTXIfRacket}{
  7981. \begin{array}{lcl}
  7982. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7983. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7984. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7985. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7986. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7987. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7988. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7989. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7990. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  7991. \end{array}
  7992. }
  7993. \newcommand{\ASTXIfPython}{
  7994. \begin{array}{lcl}
  7995. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7996. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7997. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7998. \MID \BYTEREG{\itm{bytereg}} \\
  7999. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8000. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8001. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8002. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8003. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8004. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8005. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8006. \end{array}
  8007. }
  8008. \begin{figure}[tp]
  8009. \begin{tcolorbox}[colback=white]
  8010. \small
  8011. {\if\edition\racketEd
  8012. \[\arraycolsep=3pt
  8013. \begin{array}{l}
  8014. \gray{\ASTXIntRacket} \\ \hline
  8015. \ASTXIfRacket \\
  8016. \begin{array}{lcl}
  8017. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8018. \end{array}
  8019. \end{array}
  8020. \]
  8021. \fi}
  8022. %
  8023. {\if\edition\pythonEd\pythonColor
  8024. \[
  8025. \begin{array}{l}
  8026. \gray{\ASTXIntPython} \\ \hline
  8027. \ASTXIfPython \\
  8028. \begin{array}{lcl}
  8029. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8030. \end{array}
  8031. \end{array}
  8032. \]
  8033. \fi}
  8034. \end{tcolorbox}
  8035. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8036. \label{fig:x86-1}
  8037. \end{figure}
  8038. Next we consider the x86 instructions that are relevant for compiling
  8039. the comparison operations. The \key{cmpq} instruction compares its two
  8040. arguments to determine whether one argument is less than, equal to, or
  8041. greater than the other argument. The \key{cmpq} instruction is unusual
  8042. regarding the order of its arguments and where the result is
  8043. placed. The argument order is backward: if you want to test whether
  8044. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8045. \key{cmpq} is placed in the special EFLAGS register. This register
  8046. cannot be accessed directly, but it can be queried by a number of
  8047. instructions, including the \key{set} instruction. The instruction
  8048. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8049. depending on whether the contents of the EFLAGS register matches the
  8050. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8051. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8052. The \key{set} instruction has a quirk in that its destination argument
  8053. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8054. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8055. register. Thankfully, the \key{movzbq} instruction can be used to
  8056. move from a single-byte register to a normal 64-bit register. The
  8057. abstract syntax for the \code{set} instruction differs from the
  8058. concrete syntax in that it separates the instruction name from the
  8059. condition code.
  8060. \python{The x86 instructions for jumping are relevant to the
  8061. compilation of \key{if} expressions.}
  8062. %
  8063. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8064. counter to the address of the instruction after the specified
  8065. label.}
  8066. %
  8067. \racket{The x86 instruction for conditional jump is relevant to the
  8068. compilation of \key{if} expressions.}
  8069. %
  8070. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8071. counter to point to the instruction after \itm{label}, depending on
  8072. whether the result in the EFLAGS register matches the condition code
  8073. \itm{cc}; otherwise, the jump instruction falls through to the next
  8074. instruction. Like the abstract syntax for \code{set}, the abstract
  8075. syntax for conditional jump separates the instruction name from the
  8076. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8077. corresponds to \code{jle foo}. Because the conditional jump instruction
  8078. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8079. a \key{cmpq} instruction to set the EFLAGS register.
  8080. \section{Shrink the \LangIf{} Language}
  8081. \label{sec:shrink-Lif}
  8082. The \code{shrink} pass translates some of the language features into
  8083. other features, thereby reducing the kinds of expressions in the
  8084. language. For example, the short-circuiting nature of the \code{and}
  8085. and \code{or} logical operators can be expressed using \code{if} as
  8086. follows.
  8087. \begin{align*}
  8088. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8089. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8090. \end{align*}
  8091. By performing these translations in the front end of the compiler,
  8092. subsequent passes of the compiler can be shorter.
  8093. On the other hand, translations sometimes reduce the efficiency of the
  8094. generated code by increasing the number of instructions. For example,
  8095. expressing subtraction in terms of addition and negation
  8096. \[
  8097. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8098. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8099. \]
  8100. produces code with two x86 instructions (\code{negq} and \code{addq})
  8101. instead of just one (\code{subq}). Thus, we do not recommend
  8102. translating subtraction into addition and negation.
  8103. \begin{exercise}\normalfont\normalsize
  8104. %
  8105. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8106. the language by translating them to \code{if} expressions in \LangIf{}.
  8107. %
  8108. Create four test programs that involve these operators.
  8109. %
  8110. {\if\edition\racketEd
  8111. In the \code{run-tests.rkt} script, add the following entry for
  8112. \code{shrink} to the list of passes (it should be the only pass at
  8113. this point).
  8114. \begin{lstlisting}
  8115. (list "shrink" shrink interp_Lif type-check-Lif)
  8116. \end{lstlisting}
  8117. This instructs \code{interp-tests} to run the interpreter
  8118. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8119. output of \code{shrink}.
  8120. \fi}
  8121. %
  8122. Run the script to test your compiler on all the test programs.
  8123. \end{exercise}
  8124. {\if\edition\racketEd
  8125. \section{Uniquify Variables}
  8126. \label{sec:uniquify-Lif}
  8127. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8128. \code{if} expressions.
  8129. \begin{exercise}\normalfont\normalsize
  8130. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8131. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8132. \begin{lstlisting}
  8133. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8134. \end{lstlisting}
  8135. Run the script to test your compiler.
  8136. \end{exercise}
  8137. \fi}
  8138. \section{Remove Complex Operands}
  8139. \label{sec:remove-complex-opera-Lif}
  8140. The output language of \code{remove\_complex\_operands} is
  8141. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8142. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8143. but the \code{if} expression is not. All three subexpressions of an
  8144. \code{if} are allowed to be complex expressions, but the operands of
  8145. the \code{not} operator and comparison operators must be atomic.
  8146. %
  8147. \python{We add a new language form, the \code{Begin} expression, to aid
  8148. in the translation of \code{if} expressions. When we recursively
  8149. process the two branches of the \code{if}, we generate temporary
  8150. variables and their initializing expressions. However, these
  8151. expressions may contain side effects and should be executed only
  8152. when the condition of the \code{if} is true (for the ``then''
  8153. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8154. provides a way to initialize the temporary variables within the two branches
  8155. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8156. form executes the statements $ss$ and then returns the result of
  8157. expression $e$.}
  8158. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8159. the new features in \LangIf{}. In recursively processing
  8160. subexpressions, recall that you should invoke \code{rco\_atom} when
  8161. the output needs to be an \Atm{} (as specified in the grammar for
  8162. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8163. \Exp{}. Regarding \code{if}, it is particularly important
  8164. \emph{not} to replace its condition with a temporary variable, because
  8165. that would interfere with the generation of high-quality output in the
  8166. upcoming \code{explicate\_control} pass.
  8167. \newcommand{\LifMonadASTRacket}{
  8168. \begin{array}{rcl}
  8169. \Atm &::=& \BOOL{\itm{bool}}\\
  8170. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8171. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8172. \MID \IF{\Exp}{\Exp}{\Exp}
  8173. \end{array}
  8174. }
  8175. \newcommand{\LifMonadASTPython}{
  8176. \begin{array}{rcl}
  8177. \Atm &::=& \BOOL{\itm{bool}}\\
  8178. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8179. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8180. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8181. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8182. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8183. \end{array}
  8184. }
  8185. \begin{figure}[tp]
  8186. \centering
  8187. \begin{tcolorbox}[colback=white]
  8188. {\if\edition\racketEd
  8189. \[
  8190. \begin{array}{l}
  8191. \gray{\LvarMonadASTRacket} \\ \hline
  8192. \LifMonadASTRacket \\
  8193. \begin{array}{rcl}
  8194. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8195. \end{array}
  8196. \end{array}
  8197. \]
  8198. \fi}
  8199. {\if\edition\pythonEd\pythonColor
  8200. \[
  8201. \begin{array}{l}
  8202. \gray{\LvarMonadASTPython} \\ \hline
  8203. \LifMonadASTPython \\
  8204. \begin{array}{rcl}
  8205. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8206. \end{array}
  8207. \end{array}
  8208. \]
  8209. \fi}
  8210. \end{tcolorbox}
  8211. \python{\index{subject}{Begin@\texttt{Begin}}}
  8212. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8213. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8214. \label{fig:Lif-anf-syntax}
  8215. \end{figure}
  8216. \begin{exercise}\normalfont\normalsize
  8217. %
  8218. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8219. and \code{rco\_exp} functions.
  8220. %
  8221. Create three new \LangIf{} programs that exercise the interesting
  8222. code in this pass.
  8223. %
  8224. {\if\edition\racketEd
  8225. In the \code{run-tests.rkt} script, add the following entry to the
  8226. list of \code{passes} and then run the script to test your compiler.
  8227. \begin{lstlisting}
  8228. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8229. \end{lstlisting}
  8230. \fi}
  8231. \end{exercise}
  8232. \section{Explicate Control}
  8233. \label{sec:explicate-control-Lif}
  8234. \racket{Recall that the purpose of \code{explicate\_control} is to
  8235. make the order of evaluation explicit in the syntax of the program.
  8236. With the addition of \key{if}, this becomes more interesting.}
  8237. %
  8238. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8239. %
  8240. The main challenge to overcome is that the condition of an \key{if}
  8241. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8242. condition must be a comparison.
  8243. As a motivating example, consider the following program that has an
  8244. \key{if} expression nested in the condition of another \key{if}:%
  8245. \python{\footnote{Programmers rarely write nested \code{if}
  8246. expressions, but they do write nested expressions involving
  8247. logical \code{and}, which, as we have seen, translates to
  8248. \code{if}.}}
  8249. % cond_test_41.rkt, if_lt_eq.py
  8250. \begin{center}
  8251. \begin{minipage}{0.96\textwidth}
  8252. {\if\edition\racketEd
  8253. \begin{lstlisting}
  8254. (let ([x (read)])
  8255. (let ([y (read)])
  8256. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8257. (+ y 2)
  8258. (+ y 10))))
  8259. \end{lstlisting}
  8260. \fi}
  8261. {\if\edition\pythonEd\pythonColor
  8262. \begin{lstlisting}
  8263. x = input_int()
  8264. y = input_int()
  8265. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8266. \end{lstlisting}
  8267. \fi}
  8268. \end{minipage}
  8269. \end{center}
  8270. %
  8271. The naive way to compile \key{if} and the comparison operations would
  8272. be to handle each of them in isolation, regardless of their context.
  8273. Each comparison would be translated into a \key{cmpq} instruction
  8274. followed by several instructions to move the result from the EFLAGS
  8275. register into a general purpose register or stack location. Each
  8276. \key{if} would be translated into a \key{cmpq} instruction followed by
  8277. a conditional jump. The generated code for the inner \key{if} in this
  8278. example would be as follows:
  8279. \begin{center}
  8280. \begin{minipage}{0.96\textwidth}
  8281. \begin{lstlisting}
  8282. cmpq $1, x
  8283. setl %al
  8284. movzbq %al, tmp
  8285. cmpq $1, tmp
  8286. je then_branch_1
  8287. jmp else_branch_1
  8288. \end{lstlisting}
  8289. \end{minipage}
  8290. \end{center}
  8291. Notice that the three instructions starting with \code{setl} are
  8292. redundant; the conditional jump could come immediately after the first
  8293. \code{cmpq}.
  8294. Our goal is to compile \key{if} expressions so that the relevant
  8295. comparison instruction appears directly before the conditional jump.
  8296. For example, we want to generate the following code for the inner
  8297. \code{if}:
  8298. \begin{center}
  8299. \begin{minipage}{0.96\textwidth}
  8300. \begin{lstlisting}
  8301. cmpq $1, x
  8302. jl then_branch_1
  8303. jmp else_branch_1
  8304. \end{lstlisting}
  8305. \end{minipage}
  8306. \end{center}
  8307. One way to achieve this goal is to reorganize the code at the level of
  8308. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8309. the following code:
  8310. \begin{center}
  8311. \begin{minipage}{0.96\textwidth}
  8312. {\if\edition\racketEd
  8313. \begin{lstlisting}
  8314. (let ([x (read)])
  8315. (let ([y (read)])
  8316. (if (< x 1)
  8317. (if (eq? x 0)
  8318. (+ y 2)
  8319. (+ y 10))
  8320. (if (eq? x 2)
  8321. (+ y 2)
  8322. (+ y 10)))))
  8323. \end{lstlisting}
  8324. \fi}
  8325. {\if\edition\pythonEd\pythonColor
  8326. \begin{lstlisting}
  8327. x = input_int()
  8328. y = input_int()
  8329. print(((y + 2) if x == 0 else (y + 10)) \
  8330. if (x < 1) \
  8331. else ((y + 2) if (x == 2) else (y + 10)))
  8332. \end{lstlisting}
  8333. \fi}
  8334. \end{minipage}
  8335. \end{center}
  8336. Unfortunately, this approach duplicates the two branches from the
  8337. outer \code{if}, and a compiler must never duplicate code! After all,
  8338. the two branches could be very large expressions.
  8339. How can we apply this transformation without duplicating code? In
  8340. other words, how can two different parts of a program refer to one
  8341. piece of code?
  8342. %
  8343. The answer is that we must move away from abstract syntax \emph{trees}
  8344. and instead use \emph{graphs}.
  8345. %
  8346. At the level of x86 assembly, this is straightforward because we can
  8347. label the code for each branch and insert jumps in all the places that
  8348. need to execute the branch. In this way, jump instructions are edges
  8349. in the graph and the basic blocks are the nodes.
  8350. %
  8351. Likewise, our language \LangCIf{} provides the ability to label a
  8352. sequence of statements and to jump to a label via \code{goto}.
  8353. As a preview of what \code{explicate\_control} will do,
  8354. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8355. \code{explicate\_control} on this example. Note how the condition of
  8356. every \code{if} is a comparison operation and that we have not
  8357. duplicated any code but instead have used labels and \code{goto} to
  8358. enable sharing of code.
  8359. \begin{figure}[tbp]
  8360. \begin{tcolorbox}[colback=white]
  8361. {\if\edition\racketEd
  8362. \begin{tabular}{lll}
  8363. \begin{minipage}{0.4\textwidth}
  8364. % cond_test_41.rkt
  8365. \begin{lstlisting}
  8366. (let ([x (read)])
  8367. (let ([y (read)])
  8368. (if (if (< x 1)
  8369. (eq? x 0)
  8370. (eq? x 2))
  8371. (+ y 2)
  8372. (+ y 10))))
  8373. \end{lstlisting}
  8374. \end{minipage}
  8375. &
  8376. $\Rightarrow$
  8377. &
  8378. \begin{minipage}{0.55\textwidth}
  8379. \begin{lstlisting}
  8380. start:
  8381. x = (read);
  8382. y = (read);
  8383. if (< x 1)
  8384. goto block_4;
  8385. else
  8386. goto block_5;
  8387. block_4:
  8388. if (eq? x 0)
  8389. goto block_2;
  8390. else
  8391. goto block_3;
  8392. block_5:
  8393. if (eq? x 2)
  8394. goto block_2;
  8395. else
  8396. goto block_3;
  8397. block_2:
  8398. return (+ y 2);
  8399. block_3:
  8400. return (+ y 10);
  8401. \end{lstlisting}
  8402. \end{minipage}
  8403. \end{tabular}
  8404. \fi}
  8405. {\if\edition\pythonEd\pythonColor
  8406. \begin{tabular}{lll}
  8407. \begin{minipage}{0.4\textwidth}
  8408. % tests/if/if_lt_eq.py
  8409. \begin{lstlisting}
  8410. x = input_int()
  8411. y = input_int()
  8412. print(y + 2 \
  8413. if (x == 0 \
  8414. if x < 1 \
  8415. else x == 2) \
  8416. else y + 10)
  8417. \end{lstlisting}
  8418. \end{minipage}
  8419. &
  8420. $\Rightarrow\qquad$
  8421. &
  8422. \begin{minipage}{0.55\textwidth}
  8423. \begin{lstlisting}
  8424. start:
  8425. x = input_int()
  8426. y = input_int()
  8427. if x < 1:
  8428. goto block_6
  8429. else:
  8430. goto block_7
  8431. block_6:
  8432. if x == 0:
  8433. goto block_4
  8434. else:
  8435. goto block_5
  8436. block_7:
  8437. if x == 2:
  8438. goto block_4
  8439. else:
  8440. goto block_5
  8441. block_4:
  8442. tmp.82 = (y + 2)
  8443. goto block_3
  8444. block_5:
  8445. tmp.82 = (y + 10)
  8446. goto block_3
  8447. block_3:
  8448. print(tmp.82)
  8449. return 0
  8450. \end{lstlisting}
  8451. \end{minipage}
  8452. \end{tabular}
  8453. \fi}
  8454. \end{tcolorbox}
  8455. \caption{Translation from \LangIf{} to \LangCIf{}
  8456. via the \code{explicate\_control}.}
  8457. \label{fig:explicate-control-s1-38}
  8458. \end{figure}
  8459. {\if\edition\racketEd
  8460. %
  8461. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8462. \code{explicate\_control} for \LangVar{} using two recursive
  8463. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8464. former function translates expressions in tail position, whereas the
  8465. latter function translates expressions on the right-hand side of a
  8466. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8467. have a new kind of position to deal with: the predicate position of
  8468. the \key{if}. We need another function, \code{explicate\_pred}, that
  8469. decides how to compile an \key{if} by analyzing its condition. So,
  8470. \code{explicate\_pred} takes an \LangIf{} expression and two
  8471. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8472. and outputs a tail. In the following paragraphs we discuss specific
  8473. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8474. \code{explicate\_pred} functions.
  8475. %
  8476. \fi}
  8477. %
  8478. {\if\edition\pythonEd\pythonColor
  8479. %
  8480. We recommend implementing \code{explicate\_control} using the
  8481. following four auxiliary functions.
  8482. \begin{description}
  8483. \item[\code{explicate\_effect}] generates code for expressions as
  8484. statements, so their result is ignored and only their side effects
  8485. matter.
  8486. \item[\code{explicate\_assign}] generates code for expressions
  8487. on the right-hand side of an assignment.
  8488. \item[\code{explicate\_pred}] generates code for an \code{if}
  8489. expression or statement by analyzing the condition expression.
  8490. \item[\code{explicate\_stmt}] generates code for statements.
  8491. \end{description}
  8492. These four functions should build the dictionary of basic blocks. The
  8493. following auxiliary function \code{create\_block} is used to create a
  8494. new basic block from a list of statements. If the list just contains a
  8495. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8496. \code{create\_block} creates a new basic block and returns a
  8497. \code{goto} to its label.
  8498. \begin{center}
  8499. \begin{minipage}{\textwidth}
  8500. \begin{lstlisting}
  8501. def create_block(stmts, basic_blocks):
  8502. match stmts:
  8503. case [Goto(l)]:
  8504. return stmts
  8505. case _:
  8506. label = label_name(generate_name('block'))
  8507. basic_blocks[label] = stmts
  8508. return [Goto(label)]
  8509. \end{lstlisting}
  8510. \end{minipage}
  8511. \end{center}
  8512. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8513. \code{explicate\_control} pass.
  8514. The \code{explicate\_effect} function has three parameters: (1) the
  8515. expression to be compiled; (2) the already-compiled code for this
  8516. expression's \emph{continuation}, that is, the list of statements that
  8517. should execute after this expression; and (3) the dictionary of
  8518. generated basic blocks. The \code{explicate\_effect} function returns
  8519. a list of \LangCIf{} statements and it may add to the dictionary of
  8520. basic blocks.
  8521. %
  8522. Let's consider a few of the cases for the expression to be compiled.
  8523. If the expression to be compiled is a constant, then it can be
  8524. discarded because it has no side effects. If it's a \CREAD{}, then it
  8525. has a side effect and should be preserved. So the expression should be
  8526. translated into a statement using the \code{Expr} AST class. If the
  8527. expression to be compiled is an \code{if} expression, we translate the
  8528. two branches using \code{explicate\_effect} and then translate the
  8529. condition expression using \code{explicate\_pred}, which generates
  8530. code for the entire \code{if}.
  8531. The \code{explicate\_assign} function has four parameters: (1) the
  8532. right-hand side of the assignment, (2) the left-hand side of the
  8533. assignment (the variable), (3) the continuation, and (4) the dictionary
  8534. of basic blocks. The \code{explicate\_assign} function returns a list
  8535. of \LangCIf{} statements, and it may add to the dictionary of basic
  8536. blocks.
  8537. When the right-hand side is an \code{if} expression, there is some
  8538. work to do. In particular, the two branches should be translated using
  8539. \code{explicate\_assign}, and the condition expression should be
  8540. translated using \code{explicate\_pred}. Otherwise we can simply
  8541. generate an assignment statement, with the given left- and right-hand
  8542. sides, concatenated with its continuation.
  8543. \begin{figure}[tbp]
  8544. \begin{tcolorbox}[colback=white]
  8545. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8546. def explicate_effect(e, cont, basic_blocks):
  8547. match e:
  8548. case IfExp(test, body, orelse):
  8549. ...
  8550. case Call(func, args):
  8551. ...
  8552. case Begin(body, result):
  8553. ...
  8554. case _:
  8555. ...
  8556. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8557. match rhs:
  8558. case IfExp(test, body, orelse):
  8559. ...
  8560. case Begin(body, result):
  8561. ...
  8562. case _:
  8563. return [Assign([lhs], rhs)] + cont
  8564. def explicate_pred(cnd, thn, els, basic_blocks):
  8565. match cnd:
  8566. case Compare(left, [op], [right]):
  8567. goto_thn = create_block(thn, basic_blocks)
  8568. goto_els = create_block(els, basic_blocks)
  8569. return [If(cnd, goto_thn, goto_els)]
  8570. case Constant(True):
  8571. return thn;
  8572. case Constant(False):
  8573. return els;
  8574. case UnaryOp(Not(), operand):
  8575. ...
  8576. case IfExp(test, body, orelse):
  8577. ...
  8578. case Begin(body, result):
  8579. ...
  8580. case _:
  8581. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8582. create_block(els, basic_blocks),
  8583. create_block(thn, basic_blocks))]
  8584. def explicate_stmt(s, cont, basic_blocks):
  8585. match s:
  8586. case Assign([lhs], rhs):
  8587. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8588. case Expr(value):
  8589. return explicate_effect(value, cont, basic_blocks)
  8590. case If(test, body, orelse):
  8591. ...
  8592. def explicate_control(p):
  8593. match p:
  8594. case Module(body):
  8595. new_body = [Return(Constant(0))]
  8596. basic_blocks = {}
  8597. for s in reversed(body):
  8598. new_body = explicate_stmt(s, new_body, basic_blocks)
  8599. basic_blocks[label_name('start')] = new_body
  8600. return CProgram(basic_blocks)
  8601. \end{lstlisting}
  8602. \end{tcolorbox}
  8603. \caption{Skeleton for the \code{explicate\_control} pass.}
  8604. \label{fig:explicate-control-Lif}
  8605. \end{figure}
  8606. \fi}
  8607. {\if\edition\racketEd
  8608. \subsection{Explicate Tail and Assign}
  8609. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8610. additional cases for Boolean constants and \key{if}. The cases for
  8611. \code{if} should recursively compile the two branches using either
  8612. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8613. cases should then invoke \code{explicate\_pred} on the condition
  8614. expression, passing in the generated code for the two branches. For
  8615. example, consider the following program with an \code{if} in tail
  8616. position.
  8617. % cond_test_6.rkt
  8618. \begin{lstlisting}
  8619. (let ([x (read)])
  8620. (if (eq? x 0) 42 777))
  8621. \end{lstlisting}
  8622. The two branches are recursively compiled to return statements. We
  8623. then delegate to \code{explicate\_pred}, passing the condition
  8624. \code{(eq? x 0)} and the two return statements. We return to this
  8625. example shortly when we discuss \code{explicate\_pred}.
  8626. Next let us consider a program with an \code{if} on the right-hand
  8627. side of a \code{let}.
  8628. \begin{lstlisting}
  8629. (let ([y (read)])
  8630. (let ([x (if (eq? y 0) 40 777)])
  8631. (+ x 2)))
  8632. \end{lstlisting}
  8633. Note that the body of the inner \code{let} will have already been
  8634. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8635. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8636. to recursively process both branches of the \code{if}, and we do not
  8637. want to duplicate code, so we generate the following block using an
  8638. auxiliary function named \code{create\_block}, discussed in the next
  8639. section.
  8640. \begin{lstlisting}
  8641. block_6:
  8642. return (+ x 2)
  8643. \end{lstlisting}
  8644. We then use \code{goto block\_6;} as the \code{cont} argument for
  8645. compiling the branches. So the two branches compile to
  8646. \begin{center}
  8647. \begin{minipage}{0.2\textwidth}
  8648. \begin{lstlisting}
  8649. x = 40;
  8650. goto block_6;
  8651. \end{lstlisting}
  8652. \end{minipage}
  8653. \hspace{0.5in} and \hspace{0.5in}
  8654. \begin{minipage}{0.2\textwidth}
  8655. \begin{lstlisting}
  8656. x = 777;
  8657. goto block_6;
  8658. \end{lstlisting}
  8659. \end{minipage}
  8660. \end{center}
  8661. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8662. \code{(eq? y 0)} and the previously presented code for the branches.
  8663. \subsection{Create Block}
  8664. We recommend implementing the \code{create\_block} auxiliary function
  8665. as follows, using a global variable \code{basic-blocks} to store a
  8666. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8667. that \code{create\_block} generates a new label and then associates
  8668. the given \code{tail} with the new label in the \code{basic-blocks}
  8669. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8670. new label. However, if the given \code{tail} is already a \code{Goto},
  8671. then there is no need to generate a new label and entry in
  8672. \code{basic-blocks}; we can simply return that \code{Goto}.
  8673. %
  8674. \begin{lstlisting}
  8675. (define (create_block tail)
  8676. (match tail
  8677. [(Goto label) (Goto label)]
  8678. [else
  8679. (let ([label (gensym 'block)])
  8680. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8681. (Goto label))]))
  8682. \end{lstlisting}
  8683. \fi}
  8684. {\if\edition\racketEd
  8685. \subsection{Explicate Predicate}
  8686. The skeleton for the \code{explicate\_pred} function is given in
  8687. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8688. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8689. the code generated by explicate for the \emph{then} branch; and (3)
  8690. \code{els}, the code generated by explicate for the \emph{else}
  8691. branch. The \code{explicate\_pred} function should match on
  8692. \code{cnd} with a case for every kind of expression that can have type
  8693. \BOOLTY{}.
  8694. \begin{figure}[tbp]
  8695. \begin{tcolorbox}[colback=white]
  8696. \begin{lstlisting}
  8697. (define (explicate_pred cnd thn els)
  8698. (match cnd
  8699. [(Var x) ___]
  8700. [(Let x rhs body) ___]
  8701. [(Prim 'not (list e)) ___]
  8702. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8703. (IfStmt (Prim op es) (create_block thn)
  8704. (create_block els))]
  8705. [(Bool b) (if b thn els)]
  8706. [(If cnd^ thn^ els^) ___]
  8707. [else (error "explicate_pred unhandled case" cnd)]))
  8708. \end{lstlisting}
  8709. \end{tcolorbox}
  8710. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8711. \label{fig:explicate-pred}
  8712. \end{figure}
  8713. \fi}
  8714. %
  8715. {\if\edition\pythonEd\pythonColor
  8716. The \code{explicate\_pred} function has four parameters: (1) the
  8717. condition expression, (2) the generated statements for the \emph{then}
  8718. branch, (3) the generated statements for the \emph{else} branch, and
  8719. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8720. function returns a list of statements, and it adds to the dictionary
  8721. of basic blocks.
  8722. \fi}
  8723. Consider the case for comparison operators. We translate the
  8724. comparison to an \code{if} statement whose branches are \code{goto}
  8725. statements created by applying \code{create\_block} to the \code{thn}
  8726. and \code{els} parameters. Let us illustrate this translation by
  8727. returning to the program with an \code{if} expression in tail
  8728. position, shown next. We invoke \code{explicate\_pred} on its
  8729. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8730. %
  8731. {\if\edition\racketEd
  8732. \begin{lstlisting}
  8733. (let ([x (read)])
  8734. (if (eq? x 0) 42 777))
  8735. \end{lstlisting}
  8736. \fi}
  8737. %
  8738. {\if\edition\pythonEd\pythonColor
  8739. \begin{lstlisting}
  8740. x = input_int()
  8741. 42 if x == 0 else 777
  8742. \end{lstlisting}
  8743. \fi}
  8744. %
  8745. \noindent The two branches \code{42} and \code{777} were already
  8746. compiled to \code{return} statements, from which we now create the
  8747. following blocks:
  8748. %
  8749. \begin{center}
  8750. \begin{minipage}{\textwidth}
  8751. \begin{lstlisting}
  8752. block_1:
  8753. return 42;
  8754. block_2:
  8755. return 777;
  8756. \end{lstlisting}
  8757. \end{minipage}
  8758. \end{center}
  8759. %
  8760. After that, \code{explicate\_pred} compiles the comparison
  8761. \racket{\code{(eq? x 0)}}
  8762. \python{\code{x == 0}}
  8763. to the following \code{if} statement:
  8764. %
  8765. {\if\edition\racketEd
  8766. \begin{center}
  8767. \begin{minipage}{\textwidth}
  8768. \begin{lstlisting}
  8769. if (eq? x 0)
  8770. goto block_1;
  8771. else
  8772. goto block_2;
  8773. \end{lstlisting}
  8774. \end{minipage}
  8775. \end{center}
  8776. \fi}
  8777. {\if\edition\pythonEd\pythonColor
  8778. \begin{center}
  8779. \begin{minipage}{\textwidth}
  8780. \begin{lstlisting}
  8781. if x == 0:
  8782. goto block_1;
  8783. else
  8784. goto block_2;
  8785. \end{lstlisting}
  8786. \end{minipage}
  8787. \end{center}
  8788. \fi}
  8789. Next consider the case for Boolean constants. We perform a kind of
  8790. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8791. either the \code{thn} or \code{els} parameter, depending on whether the
  8792. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8793. following program:
  8794. {\if\edition\racketEd
  8795. \begin{lstlisting}
  8796. (if #t 42 777)
  8797. \end{lstlisting}
  8798. \fi}
  8799. {\if\edition\pythonEd\pythonColor
  8800. \begin{lstlisting}
  8801. 42 if True else 777
  8802. \end{lstlisting}
  8803. \fi}
  8804. %
  8805. \noindent Again, the two branches \code{42} and \code{777} were
  8806. compiled to \code{return} statements, so \code{explicate\_pred}
  8807. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8808. code for the \emph{then} branch.
  8809. \begin{lstlisting}
  8810. return 42;
  8811. \end{lstlisting}
  8812. This case demonstrates that we sometimes discard the \code{thn} or
  8813. \code{els} blocks that are input to \code{explicate\_pred}.
  8814. The case for \key{if} expressions in \code{explicate\_pred} is
  8815. particularly illuminating because it deals with the challenges
  8816. discussed previously regarding nested \key{if} expressions
  8817. (figure~\ref{fig:explicate-control-s1-38}). The
  8818. \racket{\lstinline{thn^}}\python{\code{body}} and
  8819. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8820. \key{if} inherit their context from the current one, that is,
  8821. predicate context. So, you should recursively apply
  8822. \code{explicate\_pred} to the
  8823. \racket{\lstinline{thn^}}\python{\code{body}} and
  8824. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8825. those recursive calls, pass \code{thn} and \code{els} as the extra
  8826. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8827. inside each recursive call. As discussed previously, to avoid
  8828. duplicating code, we need to add them to the dictionary of basic
  8829. blocks so that we can instead refer to them by name and execute them
  8830. with a \key{goto}.
  8831. {\if\edition\pythonEd\pythonColor
  8832. %
  8833. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8834. three parameters: (1) the statement to be compiled, (2) the code for its
  8835. continuation, and (3) the dictionary of basic blocks. The
  8836. \code{explicate\_stmt} returns a list of statements, and it may add to
  8837. the dictionary of basic blocks. The cases for assignment and an
  8838. expression-statement are given in full in the skeleton code: they
  8839. simply dispatch to \code{explicate\_assign} and
  8840. \code{explicate\_effect}, respectively. The case for \code{if}
  8841. statements is not given; it is similar to the case for \code{if}
  8842. expressions.
  8843. The \code{explicate\_control} function itself is given in
  8844. figure~\ref{fig:explicate-control-Lif}. It applies
  8845. \code{explicate\_stmt} to each statement in the program, from back to
  8846. front. Thus, the result so far, stored in \code{new\_body}, can be
  8847. used as the continuation parameter in the next call to
  8848. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8849. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8850. the dictionary of basic blocks, labeling it the ``start'' block.
  8851. %
  8852. \fi}
  8853. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8854. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8855. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8856. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8857. %% results from the two recursive calls. We complete the case for
  8858. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8859. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8860. %% the result $B_5$.
  8861. %% \[
  8862. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8863. %% \quad\Rightarrow\quad
  8864. %% B_5
  8865. %% \]
  8866. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8867. %% inherit the current context, so they are in tail position. Thus, the
  8868. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8869. %% \code{explicate\_tail}.
  8870. %% %
  8871. %% We need to pass $B_0$ as the accumulator argument for both of these
  8872. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8873. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8874. %% to the control-flow graph and obtain a promised goto $G_0$.
  8875. %% %
  8876. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8877. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8878. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8879. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8880. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8881. %% \[
  8882. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8883. %% \]
  8884. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8885. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8886. %% should not be confused with the labels for the blocks that appear in
  8887. %% the generated code. We initially construct unlabeled blocks; we only
  8888. %% attach labels to blocks when we add them to the control-flow graph, as
  8889. %% we see in the next case.
  8890. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8891. %% function. The context of the \key{if} is an assignment to some
  8892. %% variable $x$ and then the control continues to some promised block
  8893. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8894. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8895. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8896. %% branches of the \key{if} inherit the current context, so they are in
  8897. %% assignment positions. Let $B_2$ be the result of applying
  8898. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8899. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8900. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8901. %% the result of applying \code{explicate\_pred} to the predicate
  8902. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8903. %% translates to the promise $B_4$.
  8904. %% \[
  8905. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8906. %% \]
  8907. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8908. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8909. \code{remove\_complex\_operands} pass and then the
  8910. \code{explicate\_control} pass on the example program. We walk through
  8911. the output program.
  8912. %
  8913. Following the order of evaluation in the output of
  8914. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8915. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8916. in the predicate of the inner \key{if}. In the output of
  8917. \code{explicate\_control}, in the
  8918. block labeled \code{start}, two assignment statements are followed by an
  8919. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8920. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8921. The blocks associated with those labels contain the
  8922. translations of the code
  8923. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8924. and
  8925. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8926. respectively. In particular, we start
  8927. \racket{\code{block\_4}}\python{\code{block\_6}}
  8928. with the comparison
  8929. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8930. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8931. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8932. which correspond to the two branches of the outer \key{if}, that is,
  8933. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8934. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8935. %
  8936. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8937. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8938. %
  8939. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8940. {\if\edition\racketEd
  8941. \subsection{Interactions between Explicate and Shrink}
  8942. The way in which the \code{shrink} pass transforms logical operations
  8943. such as \code{and} and \code{or} can impact the quality of code
  8944. generated by \code{explicate\_control}. For example, consider the
  8945. following program:
  8946. % cond_test_21.rkt, and_eq_input.py
  8947. \begin{lstlisting}
  8948. (if (and (eq? (read) 0) (eq? (read) 1))
  8949. 0
  8950. 42)
  8951. \end{lstlisting}
  8952. The \code{and} operation should transform into something that the
  8953. \code{explicate\_pred} function can analyze and descend through to
  8954. reach the underlying \code{eq?} conditions. Ideally, for this program
  8955. your \code{explicate\_control} pass should generate code similar to
  8956. the following:
  8957. \begin{center}
  8958. \begin{minipage}{\textwidth}
  8959. \begin{lstlisting}
  8960. start:
  8961. tmp1 = (read);
  8962. if (eq? tmp1 0) goto block40;
  8963. else goto block39;
  8964. block40:
  8965. tmp2 = (read);
  8966. if (eq? tmp2 1) goto block38;
  8967. else goto block39;
  8968. block38:
  8969. return 0;
  8970. block39:
  8971. return 42;
  8972. \end{lstlisting}
  8973. \end{minipage}
  8974. \end{center}
  8975. \fi}
  8976. \begin{exercise}\normalfont\normalsize
  8977. \racket{
  8978. Implement the pass \code{explicate\_control} by adding the cases for
  8979. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8980. \code{explicate\_assign} functions. Implement the auxiliary function
  8981. \code{explicate\_pred} for predicate contexts.}
  8982. \python{Implement \code{explicate\_control} pass with its
  8983. four auxiliary functions.}
  8984. %
  8985. Create test cases that exercise all the new cases in the code for
  8986. this pass.
  8987. %
  8988. {\if\edition\racketEd
  8989. Add the following entry to the list of \code{passes} in
  8990. \code{run-tests.rkt}:
  8991. \begin{lstlisting}
  8992. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8993. \end{lstlisting}
  8994. and then run \code{run-tests.rkt} to test your compiler.
  8995. \fi}
  8996. \end{exercise}
  8997. \section{Select Instructions}
  8998. \label{sec:select-Lif}
  8999. \index{subject}{select instructions}
  9000. The \code{select\_instructions} pass translates \LangCIf{} to
  9001. \LangXIfVar{}.
  9002. %
  9003. \racket{Recall that we implement this pass using three auxiliary
  9004. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9005. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9006. %
  9007. \racket{For $\Atm$, we have new cases for the Booleans.}
  9008. %
  9009. \python{We begin with the Boolean constants.}
  9010. As previously discussed, we encode them as integers.
  9011. \[
  9012. \TRUE{} \quad\Rightarrow\quad \key{1}
  9013. \qquad\qquad
  9014. \FALSE{} \quad\Rightarrow\quad \key{0}
  9015. \]
  9016. For translating statements, we discuss some of the cases. The
  9017. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9018. discussed at the beginning of this section. Given an assignment, if
  9019. the left-hand-side variable is the same as the argument of \code{not},
  9020. then just the \code{xorq} instruction suffices.
  9021. \[
  9022. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9023. \quad\Rightarrow\quad
  9024. \key{xorq}~\key{\$}1\key{,}~\Var
  9025. \]
  9026. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9027. semantics of x86. In the following translation, let $\Arg$ be the
  9028. result of translating $\Atm$ to x86.
  9029. \[
  9030. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9031. \quad\Rightarrow\quad
  9032. \begin{array}{l}
  9033. \key{movq}~\Arg\key{,}~\Var\\
  9034. \key{xorq}~\key{\$}1\key{,}~\Var
  9035. \end{array}
  9036. \]
  9037. Next consider the cases for equality comparisons. Translating this
  9038. operation to x86 is slightly involved due to the unusual nature of the
  9039. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9040. We recommend translating an assignment with an equality on the
  9041. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9042. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9043. \begin{tabular}{lll}
  9044. \begin{minipage}{0.4\textwidth}
  9045. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9046. \end{minipage}
  9047. &
  9048. $\Rightarrow$
  9049. &
  9050. \begin{minipage}{0.4\textwidth}
  9051. \begin{lstlisting}
  9052. cmpq |$\Arg_2$|, |$\Arg_1$|
  9053. sete %al
  9054. movzbq %al, |$\Var$|
  9055. \end{lstlisting}
  9056. \end{minipage}
  9057. \end{tabular} \\
  9058. The translations for the other comparison operators are similar to
  9059. this but use different condition codes for the \code{set} instruction.
  9060. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9061. \key{goto} and \key{if} statements. Both are straightforward to
  9062. translate to x86.}
  9063. %
  9064. A \key{goto} statement becomes a jump instruction.
  9065. \[
  9066. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9067. \]
  9068. %
  9069. An \key{if} statement becomes a compare instruction followed by a
  9070. conditional jump (for the \emph{then} branch), and the fall-through is to
  9071. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9072. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9073. \begin{tabular}{lll}
  9074. \begin{minipage}{0.4\textwidth}
  9075. \begin{lstlisting}
  9076. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9077. goto |$\ell_1$||$\racket{\key{;}}$|
  9078. else|$\python{\key{:}}$|
  9079. goto |$\ell_2$||$\racket{\key{;}}$|
  9080. \end{lstlisting}
  9081. \end{minipage}
  9082. &
  9083. $\Rightarrow$
  9084. &
  9085. \begin{minipage}{0.4\textwidth}
  9086. \begin{lstlisting}
  9087. cmpq |$\Arg_2$|, |$\Arg_1$|
  9088. je |$\ell_1$|
  9089. jmp |$\ell_2$|
  9090. \end{lstlisting}
  9091. \end{minipage}
  9092. \end{tabular} \\
  9093. Again, the translations for the other comparison operators are similar to this
  9094. but use different condition codes for the conditional jump instruction.
  9095. \python{Regarding the \key{return} statement, we recommend treating it
  9096. as an assignment to the \key{rax} register followed by a jump to the
  9097. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9098. \begin{exercise}\normalfont\normalsize
  9099. Expand your \code{select\_instructions} pass to handle the new
  9100. features of the \LangCIf{} language.
  9101. %
  9102. {\if\edition\racketEd
  9103. Add the following entry to the list of \code{passes} in
  9104. \code{run-tests.rkt}
  9105. \begin{lstlisting}
  9106. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9107. \end{lstlisting}
  9108. \fi}
  9109. %
  9110. Run the script to test your compiler on all the test programs.
  9111. \end{exercise}
  9112. \section{Register Allocation}
  9113. \label{sec:register-allocation-Lif}
  9114. \index{subject}{register allocation}
  9115. The changes required for compiling \LangIf{} affect liveness analysis,
  9116. building the interference graph, and assigning homes, but the graph
  9117. coloring algorithm itself does not change.
  9118. \subsection{Liveness Analysis}
  9119. \label{sec:liveness-analysis-Lif}
  9120. \index{subject}{liveness analysis}
  9121. Recall that for \LangVar{} we implemented liveness analysis for a
  9122. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9123. the addition of \key{if} expressions to \LangIf{},
  9124. \code{explicate\_control} produces many basic blocks.
  9125. %% We recommend that you create a new auxiliary function named
  9126. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9127. %% control-flow graph.
  9128. The first question is, in what order should we process the basic blocks?
  9129. Recall that to perform liveness analysis on a basic block we need to
  9130. know the live-after set for the last instruction in the block. If a
  9131. basic block has no successors (i.e., contains no jumps to other
  9132. blocks), then it has an empty live-after set and we can immediately
  9133. apply liveness analysis to it. If a basic block has some successors,
  9134. then we need to complete liveness analysis on those blocks
  9135. first. These ordering constraints are the reverse of a
  9136. \emph{topological order}\index{subject}{topological order} on a graph
  9137. representation of the program. In particular, the \emph{control flow
  9138. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9139. of a program has a node for each basic block and an edge for each jump
  9140. from one block to another. It is straightforward to generate a CFG
  9141. from the dictionary of basic blocks. One then transposes the CFG and
  9142. applies the topological sort algorithm.
  9143. %
  9144. %
  9145. \racket{We recommend using the \code{tsort} and \code{transpose}
  9146. functions of the Racket \code{graph} package to accomplish this.}
  9147. %
  9148. \python{We provide implementations of \code{topological\_sort} and
  9149. \code{transpose} in the file \code{graph.py} of the support code.}
  9150. %
  9151. As an aside, a topological ordering is only guaranteed to exist if the
  9152. graph does not contain any cycles. This is the case for the
  9153. control-flow graphs that we generate from \LangIf{} programs.
  9154. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9155. and learn how to handle cycles in the control-flow graph.
  9156. \racket{You need to construct a directed graph to represent the
  9157. control-flow graph. Do not use the \code{directed-graph} of the
  9158. \code{graph} package because that allows at most one edge
  9159. between each pair of vertices, whereas a control-flow graph may have
  9160. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9161. file in the support code implements a graph representation that
  9162. allows multiple edges between a pair of vertices.}
  9163. {\if\edition\racketEd
  9164. The next question is how to analyze jump instructions. Recall that in
  9165. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9166. \code{label->live} that maps each label to the set of live locations
  9167. at the beginning of its block. We use \code{label->live} to determine
  9168. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9169. that we have many basic blocks, \code{label->live} needs to be updated
  9170. as we process the blocks. In particular, after performing liveness
  9171. analysis on a block, we take the live-before set of its first
  9172. instruction and associate that with the block's label in the
  9173. \code{label->live} alist.
  9174. \fi}
  9175. %
  9176. {\if\edition\pythonEd\pythonColor
  9177. %
  9178. The next question is how to analyze jump instructions. The locations
  9179. that are live before a \code{jmp} should be the locations in
  9180. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9181. maintaining a dictionary named \code{live\_before\_block} that maps each
  9182. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9183. block. After performing liveness analysis on each block, we take the
  9184. live-before set of its first instruction and associate that with the
  9185. block's label in the \code{live\_before\_block} dictionary.
  9186. %
  9187. \fi}
  9188. In \LangXIfVar{} we also have the conditional jump
  9189. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9190. this instruction is particularly interesting because during
  9191. compilation, we do not know which way a conditional jump will go. Thus
  9192. we do not know whether to use the live-before set for the block
  9193. associated with the $\itm{label}$ or the live-before set for the
  9194. following instruction. So we use both, by taking the union of the
  9195. live-before sets from the following instruction and from the mapping
  9196. for $\itm{label}$ in
  9197. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9198. The auxiliary functions for computing the variables in an
  9199. instruction's argument and for computing the variables read-from ($R$)
  9200. or written-to ($W$) by an instruction need to be updated to handle the
  9201. new kinds of arguments and instructions in \LangXIfVar{}.
  9202. \begin{exercise}\normalfont\normalsize
  9203. {\if\edition\racketEd
  9204. %
  9205. Update the \code{uncover\_live} pass to apply liveness analysis to
  9206. every basic block in the program.
  9207. %
  9208. Add the following entry to the list of \code{passes} in the
  9209. \code{run-tests.rkt} script:
  9210. \begin{lstlisting}
  9211. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9212. \end{lstlisting}
  9213. \fi}
  9214. {\if\edition\pythonEd\pythonColor
  9215. %
  9216. Update the \code{uncover\_live} function to perform liveness analysis,
  9217. in reverse topological order, on all the basic blocks in the
  9218. program.
  9219. %
  9220. \fi}
  9221. % Check that the live-after sets that you generate for
  9222. % example X matches the following... -Jeremy
  9223. \end{exercise}
  9224. \subsection{Build the Interference Graph}
  9225. \label{sec:build-interference-Lif}
  9226. Many of the new instructions in \LangXIfVar{} can be handled in the
  9227. same way as the instructions in \LangXVar{}.
  9228. % Thus, if your code was
  9229. % already quite general, it will not need to be changed to handle the
  9230. % new instructions. If your code is not general enough, we recommend that
  9231. % you change your code to be more general. For example, you can factor
  9232. % out the computing of the the read and write sets for each kind of
  9233. % instruction into auxiliary functions.
  9234. %
  9235. Some instructions, such as the \key{movzbq} instruction, require special care,
  9236. similar to the \key{movq} instruction. Refer to rule number 1 in
  9237. section~\ref{sec:build-interference}.
  9238. \begin{exercise}\normalfont\normalsize
  9239. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9240. {\if\edition\racketEd
  9241. Add the following entries to the list of \code{passes} in the
  9242. \code{run-tests.rkt} script:
  9243. \begin{lstlisting}
  9244. (list "build_interference" build_interference interp-pseudo-x86-1)
  9245. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9246. \end{lstlisting}
  9247. \fi}
  9248. % Check that the interference graph that you generate for
  9249. % example X matches the following graph G... -Jeremy
  9250. \end{exercise}
  9251. \section{Patch Instructions}
  9252. The new instructions \key{cmpq} and \key{movzbq} have some special
  9253. restrictions that need to be handled in the \code{patch\_instructions}
  9254. pass.
  9255. %
  9256. The second argument of the \key{cmpq} instruction must not be an
  9257. immediate value (such as an integer). So, if you are comparing two
  9258. immediates, we recommend inserting a \key{movq} instruction to put the
  9259. second argument in \key{rax}. On the other hand, if you implemented
  9260. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9261. update it for \LangIf{} and then this situation would not arise.
  9262. %
  9263. As usual, \key{cmpq} may have at most one memory reference.
  9264. %
  9265. The second argument of the \key{movzbq} must be a register.
  9266. \begin{exercise}\normalfont\normalsize
  9267. %
  9268. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9269. %
  9270. {\if\edition\racketEd
  9271. Add the following entry to the list of \code{passes} in
  9272. \code{run-tests.rkt}, and then run this script to test your compiler.
  9273. \begin{lstlisting}
  9274. (list "patch_instructions" patch_instructions interp-x86-1)
  9275. \end{lstlisting}
  9276. \fi}
  9277. \end{exercise}
  9278. {\if\edition\pythonEd\pythonColor
  9279. \section{Generate Prelude and Conclusion}
  9280. \label{sec:prelude-conclusion-cond}
  9281. The generation of the \code{main} function with its prelude and
  9282. conclusion must change to accommodate how the program now consists of
  9283. one or more basic blocks. After the prelude in \code{main}, jump to
  9284. the \code{start} block. Place the conclusion in a basic block labeled
  9285. with \code{conclusion}.
  9286. \fi}
  9287. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9288. \LangIf{} translated to x86, showing the results of
  9289. \code{explicate\_control}, \code{select\_instructions}, and the final
  9290. x86 assembly.
  9291. \begin{figure}[tbp]
  9292. \begin{tcolorbox}[colback=white]
  9293. {\if\edition\racketEd
  9294. \begin{tabular}{lll}
  9295. \begin{minipage}{0.4\textwidth}
  9296. % cond_test_20.rkt, eq_input.py
  9297. \begin{lstlisting}
  9298. (if (eq? (read) 1) 42 0)
  9299. \end{lstlisting}
  9300. $\Downarrow$
  9301. \begin{lstlisting}
  9302. start:
  9303. tmp7951 = (read);
  9304. if (eq? tmp7951 1)
  9305. goto block7952;
  9306. else
  9307. goto block7953;
  9308. block7952:
  9309. return 42;
  9310. block7953:
  9311. return 0;
  9312. \end{lstlisting}
  9313. $\Downarrow$
  9314. \begin{lstlisting}
  9315. start:
  9316. callq read_int
  9317. movq %rax, tmp7951
  9318. cmpq $1, tmp7951
  9319. je block7952
  9320. jmp block7953
  9321. block7953:
  9322. movq $0, %rax
  9323. jmp conclusion
  9324. block7952:
  9325. movq $42, %rax
  9326. jmp conclusion
  9327. \end{lstlisting}
  9328. \end{minipage}
  9329. &
  9330. $\Rightarrow\qquad$
  9331. \begin{minipage}{0.4\textwidth}
  9332. \begin{lstlisting}
  9333. start:
  9334. callq read_int
  9335. movq %rax, %rcx
  9336. cmpq $1, %rcx
  9337. je block7952
  9338. jmp block7953
  9339. block7953:
  9340. movq $0, %rax
  9341. jmp conclusion
  9342. block7952:
  9343. movq $42, %rax
  9344. jmp conclusion
  9345. .globl main
  9346. main:
  9347. pushq %rbp
  9348. movq %rsp, %rbp
  9349. pushq %r13
  9350. pushq %r12
  9351. pushq %rbx
  9352. pushq %r14
  9353. subq $0, %rsp
  9354. jmp start
  9355. conclusion:
  9356. addq $0, %rsp
  9357. popq %r14
  9358. popq %rbx
  9359. popq %r12
  9360. popq %r13
  9361. popq %rbp
  9362. retq
  9363. \end{lstlisting}
  9364. \end{minipage}
  9365. \end{tabular}
  9366. \fi}
  9367. {\if\edition\pythonEd\pythonColor
  9368. \begin{tabular}{lll}
  9369. \begin{minipage}{0.4\textwidth}
  9370. % cond_test_20.rkt, eq_input.py
  9371. \begin{lstlisting}
  9372. print(42 if input_int() == 1 else 0)
  9373. \end{lstlisting}
  9374. $\Downarrow$
  9375. \begin{lstlisting}
  9376. start:
  9377. tmp_0 = input_int()
  9378. if tmp_0 == 1:
  9379. goto block_3
  9380. else:
  9381. goto block_4
  9382. block_3:
  9383. tmp_1 = 42
  9384. goto block_2
  9385. block_4:
  9386. tmp_1 = 0
  9387. goto block_2
  9388. block_2:
  9389. print(tmp_1)
  9390. return 0
  9391. \end{lstlisting}
  9392. $\Downarrow$
  9393. \begin{lstlisting}
  9394. start:
  9395. callq read_int
  9396. movq %rax, tmp_0
  9397. cmpq 1, tmp_0
  9398. je block_3
  9399. jmp block_4
  9400. block_3:
  9401. movq 42, tmp_1
  9402. jmp block_2
  9403. block_4:
  9404. movq 0, tmp_1
  9405. jmp block_2
  9406. block_2:
  9407. movq tmp_1, %rdi
  9408. callq print_int
  9409. movq 0, %rax
  9410. jmp conclusion
  9411. \end{lstlisting}
  9412. \end{minipage}
  9413. &
  9414. $\Rightarrow\qquad$
  9415. \begin{minipage}{0.4\textwidth}
  9416. \begin{lstlisting}
  9417. .globl main
  9418. main:
  9419. pushq %rbp
  9420. movq %rsp, %rbp
  9421. subq $0, %rsp
  9422. jmp start
  9423. start:
  9424. callq read_int
  9425. movq %rax, %rcx
  9426. cmpq $1, %rcx
  9427. je block_3
  9428. jmp block_4
  9429. block_3:
  9430. movq $42, %rcx
  9431. jmp block_2
  9432. block_4:
  9433. movq $0, %rcx
  9434. jmp block_2
  9435. block_2:
  9436. movq %rcx, %rdi
  9437. callq print_int
  9438. movq $0, %rax
  9439. jmp conclusion
  9440. conclusion:
  9441. addq $0, %rsp
  9442. popq %rbp
  9443. retq
  9444. \end{lstlisting}
  9445. \end{minipage}
  9446. \end{tabular}
  9447. \fi}
  9448. \end{tcolorbox}
  9449. \caption{Example compilation of an \key{if} expression to x86, showing
  9450. the results of \code{explicate\_control},
  9451. \code{select\_instructions}, and the final x86 assembly code. }
  9452. \label{fig:if-example-x86}
  9453. \end{figure}
  9454. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9455. compilation of \LangIf{}.
  9456. \begin{figure}[htbp]
  9457. \begin{tcolorbox}[colback=white]
  9458. {\if\edition\racketEd
  9459. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9460. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9461. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9462. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9463. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9464. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9465. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9466. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9467. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9468. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9469. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9470. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9471. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9472. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9473. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9474. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9475. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9476. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9477. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9478. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9479. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9480. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9481. \end{tikzpicture}
  9482. \fi}
  9483. {\if\edition\pythonEd\pythonColor
  9484. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9485. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9486. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9487. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9488. \node (C-1) at (0,0) {\large \LangCIf{}};
  9489. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9490. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9491. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9492. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9493. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9494. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9495. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9496. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9497. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9498. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9499. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9500. \end{tikzpicture}
  9501. \fi}
  9502. \end{tcolorbox}
  9503. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9504. \label{fig:Lif-passes}
  9505. \end{figure}
  9506. \section{Challenge: Optimize Blocks and Remove Jumps}
  9507. \label{sec:opt-jumps}
  9508. We discuss two challenges that involve optimizing the control-flow of
  9509. the program.
  9510. \subsection{Optimize Blocks}
  9511. The algorithm for \code{explicate\_control} that we discussed in
  9512. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9513. blocks. It creates a block whenever a continuation \emph{might} get
  9514. used more than once (for example, whenever the \code{cont} parameter
  9515. is passed into two or more recursive calls). However, some
  9516. continuation arguments may not be used at all. Consider the case for
  9517. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9518. the \code{els} continuation.
  9519. %
  9520. {\if\edition\racketEd
  9521. The following example program falls into this
  9522. case, and it creates two unused blocks.
  9523. \begin{center}
  9524. \begin{tabular}{lll}
  9525. \begin{minipage}{0.4\textwidth}
  9526. % cond_test_82.rkt
  9527. \begin{lstlisting}
  9528. (let ([y (if #t
  9529. (read)
  9530. (if (eq? (read) 0)
  9531. 777
  9532. (let ([x (read)])
  9533. (+ 1 x))))])
  9534. (+ y 2))
  9535. \end{lstlisting}
  9536. \end{minipage}
  9537. &
  9538. $\Rightarrow$
  9539. &
  9540. \begin{minipage}{0.4\textwidth}
  9541. \begin{lstlisting}
  9542. start:
  9543. y = (read);
  9544. goto block_5;
  9545. block_5:
  9546. return (+ y 2);
  9547. block_6:
  9548. y = 777;
  9549. goto block_5;
  9550. block_7:
  9551. x = (read);
  9552. y = (+ 1 x2);
  9553. goto block_5;
  9554. \end{lstlisting}
  9555. \end{minipage}
  9556. \end{tabular}
  9557. \end{center}
  9558. \fi}
  9559. {\if\edition\pythonEd
  9560. The following example program falls into this
  9561. case, and it creates the unused \code{block\_9}.
  9562. \begin{center}
  9563. \begin{minipage}{0.4\textwidth}
  9564. % if/if_true.py
  9565. \begin{lstlisting}
  9566. if True:
  9567. print(0)
  9568. else:
  9569. x = 1 if False else 2
  9570. print(x)
  9571. \end{lstlisting}
  9572. \end{minipage}
  9573. $\Rightarrow\qquad\qquad$
  9574. \begin{minipage}{0.4\textwidth}
  9575. \begin{lstlisting}
  9576. start:
  9577. print(0)
  9578. goto block_8
  9579. block_9:
  9580. print(x)
  9581. goto block_8
  9582. block_8:
  9583. return 0
  9584. \end{lstlisting}
  9585. \end{minipage}
  9586. \end{center}
  9587. \fi}
  9588. The question is, how can we decide whether to create a basic block?
  9589. \emph{Lazy evaluation}\index{subject}{lazy
  9590. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9591. delaying the creation of a basic block until the point in time at which
  9592. we know that it will be used.
  9593. %
  9594. {\if\edition\racketEd
  9595. %
  9596. Racket provides support for
  9597. lazy evaluation with the
  9598. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9599. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9600. \index{subject}{delay} creates a
  9601. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9602. expressions is postponed. When \key{(force}
  9603. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9604. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9605. result of $e_n$ is cached in the promise and returned. If \code{force}
  9606. is applied again to the same promise, then the cached result is
  9607. returned. If \code{force} is applied to an argument that is not a
  9608. promise, \code{force} simply returns the argument.
  9609. %
  9610. \fi}
  9611. %
  9612. {\if\edition\pythonEd\pythonColor
  9613. %
  9614. Although Python does not provide direct support for lazy evaluation,
  9615. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9616. by wrapping it inside a function with no parameters. We \emph{force}
  9617. its evaluation by calling the function. However, we might need to
  9618. force multiple times, so we store the result of calling the
  9619. function instead of recomputing it each time. The following
  9620. \code{Promise} class handles this memoization process.
  9621. \begin{minipage}{0.8\textwidth}
  9622. \begin{lstlisting}
  9623. @dataclass
  9624. class Promise:
  9625. fun : typing.Any
  9626. cache : list[stmt] = None
  9627. def force(self):
  9628. if self.cache is None:
  9629. self.cache = self.fun(); return self.cache
  9630. else:
  9631. return self.cache
  9632. \end{lstlisting}
  9633. \end{minipage}
  9634. \noindent However, in some cases of \code{explicate\_pred}, we return
  9635. a list of statements, and in other cases we return a function that
  9636. computes a list of statements. To uniformly deal with both regular
  9637. data and promises, we define the following \code{force} function that
  9638. checks whether its input is delayed (i.e., whether it is a
  9639. \code{Promise}) and then either (1) forces the promise or (2) returns
  9640. the input.
  9641. %
  9642. \begin{lstlisting}
  9643. def force(promise):
  9644. if isinstance(promise, Promise):
  9645. return promise.force()
  9646. else:
  9647. return promise
  9648. \end{lstlisting}
  9649. %
  9650. \fi}
  9651. We use promises for the input and output of the functions
  9652. \code{explicate\_pred}, \code{explicate\_assign},
  9653. %
  9654. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9655. %
  9656. So, instead of taking and returning \racket{$\Tail$
  9657. expressions}\python{lists of statements}, they take and return
  9658. promises. Furthermore, when we come to a situation in which a
  9659. continuation might be used more than once, as in the case for
  9660. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9661. that creates a basic block for each continuation (if there is not
  9662. already one) and then returns a \code{goto} statement to that basic
  9663. block. When we come to a situation in which we have a promise but need an
  9664. actual piece of code, for example, to create a larger piece of code with a
  9665. constructor such as \code{Seq}, then insert a call to \code{force}.
  9666. %
  9667. {\if\edition\racketEd
  9668. %
  9669. Also, we must modify the \code{create\_block} function to begin with
  9670. \code{delay} to create a promise. When forced, this promise forces the
  9671. original promise. If that returns a \code{Goto} (because the block was
  9672. already added to \code{basic-blocks}), then we return the
  9673. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9674. return a \code{Goto} to the new label.
  9675. \begin{center}
  9676. \begin{minipage}{\textwidth}
  9677. \begin{lstlisting}
  9678. (define (create_block tail)
  9679. (delay
  9680. (define t (force tail))
  9681. (match t
  9682. [(Goto label) (Goto label)]
  9683. [else
  9684. (let ([label (gensym 'block)])
  9685. (set! basic-blocks (cons (cons label t) basic-blocks))
  9686. (Goto label))])))
  9687. \end{lstlisting}
  9688. \end{minipage}
  9689. \end{center}
  9690. \fi}
  9691. {\if\edition\pythonEd\pythonColor
  9692. %
  9693. Here is the new version of the \code{create\_block} auxiliary function
  9694. that delays the creation of the new basic block.\\
  9695. \begin{minipage}{\textwidth}
  9696. \begin{lstlisting}
  9697. def create_block(promise, basic_blocks):
  9698. def delay():
  9699. stmts = force(promise)
  9700. match stmts:
  9701. case [Goto(l)]:
  9702. return [Goto(l)]
  9703. case _:
  9704. label = label_name(generate_name('block'))
  9705. basic_blocks[label] = stmts
  9706. return [Goto(label)]
  9707. return Promise(delay)
  9708. \end{lstlisting}
  9709. \end{minipage}
  9710. \fi}
  9711. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9712. improved \code{explicate\_control} on this example.
  9713. \racket{As you can see, the number of basic blocks has been reduced
  9714. from four blocks to two blocks.}%
  9715. \python{As you can see, the number of basic blocks has been reduced
  9716. from three blocks to two blocks.}
  9717. \begin{figure}[tbp]
  9718. \begin{tcolorbox}[colback=white]
  9719. {\if\edition\racketEd
  9720. \begin{tabular}{lll}
  9721. \begin{minipage}{0.45\textwidth}
  9722. % cond_test_82.rkt
  9723. \begin{lstlisting}
  9724. (let ([y (if #t
  9725. (read)
  9726. (if (eq? (read) 0)
  9727. 777
  9728. (let ([x (read)])
  9729. (+ 1 x))))])
  9730. (+ y 2))
  9731. \end{lstlisting}
  9732. \end{minipage}
  9733. &
  9734. $\quad\Rightarrow\quad$
  9735. &
  9736. \begin{minipage}{0.4\textwidth}
  9737. \begin{lstlisting}
  9738. start:
  9739. y = (read);
  9740. goto block_5;
  9741. block_5:
  9742. return (+ y 2);
  9743. \end{lstlisting}
  9744. \end{minipage}
  9745. \end{tabular}
  9746. \fi}
  9747. {\if\edition\pythonEd\pythonColor
  9748. \begin{tabular}{lll}
  9749. \begin{minipage}{0.4\textwidth}
  9750. % if/if_true.py
  9751. \begin{lstlisting}
  9752. if True:
  9753. print(0)
  9754. else:
  9755. x = 1 if False else 2
  9756. print(x)
  9757. \end{lstlisting}
  9758. \end{minipage}
  9759. &
  9760. $\Rightarrow$
  9761. &
  9762. \begin{minipage}{0.55\textwidth}
  9763. \begin{lstlisting}
  9764. start:
  9765. print(0)
  9766. goto block_4
  9767. block_4:
  9768. return 0
  9769. \end{lstlisting}
  9770. \end{minipage}
  9771. \end{tabular}
  9772. \fi}
  9773. \end{tcolorbox}
  9774. \caption{Translation from \LangIf{} to \LangCIf{}
  9775. via the improved \code{explicate\_control}.}
  9776. \label{fig:explicate-control-challenge}
  9777. \end{figure}
  9778. %% Recall that in the example output of \code{explicate\_control} in
  9779. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9780. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9781. %% block. The first goal of this challenge assignment is to remove those
  9782. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9783. %% \code{explicate\_control} on the left and shows the result of bypassing
  9784. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9785. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9786. %% \code{block55}. The optimized code on the right of
  9787. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9788. %% \code{then} branch jumping directly to \code{block55}. The story is
  9789. %% similar for the \code{else} branch, as well as for the two branches in
  9790. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9791. %% have been optimized in this way, there are no longer any jumps to
  9792. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9793. %% \begin{figure}[tbp]
  9794. %% \begin{tabular}{lll}
  9795. %% \begin{minipage}{0.4\textwidth}
  9796. %% \begin{lstlisting}
  9797. %% block62:
  9798. %% tmp54 = (read);
  9799. %% if (eq? tmp54 2) then
  9800. %% goto block59;
  9801. %% else
  9802. %% goto block60;
  9803. %% block61:
  9804. %% tmp53 = (read);
  9805. %% if (eq? tmp53 0) then
  9806. %% goto block57;
  9807. %% else
  9808. %% goto block58;
  9809. %% block60:
  9810. %% goto block56;
  9811. %% block59:
  9812. %% goto block55;
  9813. %% block58:
  9814. %% goto block56;
  9815. %% block57:
  9816. %% goto block55;
  9817. %% block56:
  9818. %% return (+ 700 77);
  9819. %% block55:
  9820. %% return (+ 10 32);
  9821. %% start:
  9822. %% tmp52 = (read);
  9823. %% if (eq? tmp52 1) then
  9824. %% goto block61;
  9825. %% else
  9826. %% goto block62;
  9827. %% \end{lstlisting}
  9828. %% \end{minipage}
  9829. %% &
  9830. %% $\Rightarrow$
  9831. %% &
  9832. %% \begin{minipage}{0.55\textwidth}
  9833. %% \begin{lstlisting}
  9834. %% block62:
  9835. %% tmp54 = (read);
  9836. %% if (eq? tmp54 2) then
  9837. %% goto block55;
  9838. %% else
  9839. %% goto block56;
  9840. %% block61:
  9841. %% tmp53 = (read);
  9842. %% if (eq? tmp53 0) then
  9843. %% goto block55;
  9844. %% else
  9845. %% goto block56;
  9846. %% block56:
  9847. %% return (+ 700 77);
  9848. %% block55:
  9849. %% return (+ 10 32);
  9850. %% start:
  9851. %% tmp52 = (read);
  9852. %% if (eq? tmp52 1) then
  9853. %% goto block61;
  9854. %% else
  9855. %% goto block62;
  9856. %% \end{lstlisting}
  9857. %% \end{minipage}
  9858. %% \end{tabular}
  9859. %% \caption{Optimize jumps by removing trivial blocks.}
  9860. %% \label{fig:optimize-jumps}
  9861. %% \end{figure}
  9862. %% The name of this pass is \code{optimize-jumps}. We recommend
  9863. %% implementing this pass in two phases. The first phrase builds a hash
  9864. %% table that maps labels to possibly improved labels. The second phase
  9865. %% changes the target of each \code{goto} to use the improved label. If
  9866. %% the label is for a trivial block, then the hash table should map the
  9867. %% label to the first non-trivial block that can be reached from this
  9868. %% label by jumping through trivial blocks. If the label is for a
  9869. %% non-trivial block, then the hash table should map the label to itself;
  9870. %% we do not want to change jumps to non-trivial blocks.
  9871. %% The first phase can be accomplished by constructing an empty hash
  9872. %% table, call it \code{short-cut}, and then iterating over the control
  9873. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9874. %% then update the hash table, mapping the block's source to the target
  9875. %% of the \code{goto}. Also, the hash table may already have mapped some
  9876. %% labels to the block's source, to you must iterate through the hash
  9877. %% table and update all of those so that they instead map to the target
  9878. %% of the \code{goto}.
  9879. %% For the second phase, we recommend iterating through the $\Tail$ of
  9880. %% each block in the program, updating the target of every \code{goto}
  9881. %% according to the mapping in \code{short-cut}.
  9882. \begin{exercise}\normalfont\normalsize
  9883. Implement the improvements to the \code{explicate\_control} pass.
  9884. Check that it removes trivial blocks in a few example programs. Then
  9885. check that your compiler still passes all your tests.
  9886. \end{exercise}
  9887. \subsection{Remove Jumps}
  9888. There is an opportunity for removing jumps that is apparent in the
  9889. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9890. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9891. and there are no other jumps to
  9892. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9893. In this situation we can avoid the runtime overhead of this jump by merging
  9894. \racket{\code{block\_5}}\python{\code{block\_4}}
  9895. into the preceding block, which in this case is the \code{start} block.
  9896. Figure~\ref{fig:remove-jumps} shows the output of
  9897. \code{allocate\_registers} on the left and the result of this
  9898. optimization on the right.
  9899. \begin{figure}[tbp]
  9900. \begin{tcolorbox}[colback=white]
  9901. {\if\edition\racketEd
  9902. \begin{tabular}{lll}
  9903. \begin{minipage}{0.5\textwidth}
  9904. % cond_test_82.rkt
  9905. \begin{lstlisting}
  9906. start:
  9907. callq read_int
  9908. movq %rax, %rcx
  9909. jmp block_5
  9910. block_5:
  9911. movq %rcx, %rax
  9912. addq $2, %rax
  9913. jmp conclusion
  9914. \end{lstlisting}
  9915. \end{minipage}
  9916. &
  9917. $\Rightarrow\qquad$
  9918. \begin{minipage}{0.4\textwidth}
  9919. \begin{lstlisting}
  9920. start:
  9921. callq read_int
  9922. movq %rax, %rcx
  9923. movq %rcx, %rax
  9924. addq $2, %rax
  9925. jmp conclusion
  9926. \end{lstlisting}
  9927. \end{minipage}
  9928. \end{tabular}
  9929. \fi}
  9930. {\if\edition\pythonEd\pythonColor
  9931. \begin{tabular}{lll}
  9932. \begin{minipage}{0.5\textwidth}
  9933. % cond_test_20.rkt
  9934. \begin{lstlisting}
  9935. start:
  9936. callq read_int
  9937. movq %rax, tmp_0
  9938. cmpq 1, tmp_0
  9939. je block_3
  9940. jmp block_4
  9941. block_3:
  9942. movq 42, tmp_1
  9943. jmp block_2
  9944. block_4:
  9945. movq 0, tmp_1
  9946. jmp block_2
  9947. block_2:
  9948. movq tmp_1, %rdi
  9949. callq print_int
  9950. movq 0, %rax
  9951. jmp conclusion
  9952. \end{lstlisting}
  9953. \end{minipage}
  9954. &
  9955. $\Rightarrow\qquad$
  9956. \begin{minipage}{0.4\textwidth}
  9957. \begin{lstlisting}
  9958. start:
  9959. callq read_int
  9960. movq %rax, tmp_0
  9961. cmpq 1, tmp_0
  9962. je block_3
  9963. movq 0, tmp_1
  9964. jmp block_2
  9965. block_3:
  9966. movq 42, tmp_1
  9967. jmp block_2
  9968. block_2:
  9969. movq tmp_1, %rdi
  9970. callq print_int
  9971. movq 0, %rax
  9972. jmp conclusion
  9973. \end{lstlisting}
  9974. \end{minipage}
  9975. \end{tabular}
  9976. \fi}
  9977. \end{tcolorbox}
  9978. \caption{Merging basic blocks by removing unnecessary jumps.}
  9979. \label{fig:remove-jumps}
  9980. \end{figure}
  9981. \begin{exercise}\normalfont\normalsize
  9982. %
  9983. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9984. into their preceding basic block, when there is only one preceding
  9985. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9986. %
  9987. {\if\edition\racketEd
  9988. In the \code{run-tests.rkt} script, add the following entry to the
  9989. list of \code{passes} between \code{allocate\_registers}
  9990. and \code{patch\_instructions}:
  9991. \begin{lstlisting}
  9992. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9993. \end{lstlisting}
  9994. \fi}
  9995. %
  9996. Run the script to test your compiler.
  9997. %
  9998. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9999. blocks on several test programs.
  10000. \end{exercise}
  10001. \section{Further Reading}
  10002. \label{sec:cond-further-reading}
  10003. The algorithm for the \code{explicate\_control} pass is based on the
  10004. \code{expose-basic-blocks} pass in the course notes of
  10005. \citet{Dybvig:2010aa}.
  10006. %
  10007. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10008. \citet{Appel:2003fk}, and is related to translations into continuation
  10009. passing
  10010. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10011. %
  10012. The treatment of conditionals in the \code{explicate\_control} pass is
  10013. similar to short-cut Boolean
  10014. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10015. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10016. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10017. \chapter{Loops and Dataflow Analysis}
  10018. \label{ch:Lwhile}
  10019. \setcounter{footnote}{0}
  10020. % TODO: define R'_8
  10021. % TODO: multi-graph
  10022. {\if\edition\racketEd
  10023. %
  10024. In this chapter we study two features that are the hallmarks of
  10025. imperative programming languages: loops and assignments to local
  10026. variables. The following example demonstrates these new features by
  10027. computing the sum of the first five positive integers:
  10028. % similar to loop_test_1.rkt
  10029. \begin{lstlisting}
  10030. (let ([sum 0])
  10031. (let ([i 5])
  10032. (begin
  10033. (while (> i 0)
  10034. (begin
  10035. (set! sum (+ sum i))
  10036. (set! i (- i 1))))
  10037. sum)))
  10038. \end{lstlisting}
  10039. The \code{while} loop consists of a condition and a
  10040. body.\footnote{The \code{while} loop is not a built-in
  10041. feature of the Racket language, but Racket includes many looping
  10042. constructs and it is straightforward to define \code{while} as a
  10043. macro.} The body is evaluated repeatedly so long as the condition
  10044. remains true.
  10045. %
  10046. The \code{set!} consists of a variable and a right-hand side
  10047. expression. The \code{set!} updates value of the variable to the
  10048. value of the right-hand side.
  10049. %
  10050. The primary purpose of both the \code{while} loop and \code{set!} is
  10051. to cause side effects, so they do not give a meaningful result
  10052. value. Instead, their result is the \code{\#<void>} value. The
  10053. expression \code{(void)} is an explicit way to create the
  10054. \code{\#<void>} value, and it has type \code{Void}. The
  10055. \code{\#<void>} value can be passed around just like other values
  10056. inside an \LangLoop{} program, and it can be compared for equality with
  10057. another \code{\#<void>} value. However, there are no other operations
  10058. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10059. Racket defines the \code{void?} predicate that returns \code{\#t}
  10060. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10061. %
  10062. \footnote{Racket's \code{Void} type corresponds to what is often
  10063. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10064. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10065. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10066. %
  10067. With the addition of side effect-producing features such as
  10068. \code{while} loop and \code{set!}, it is helpful to include a language
  10069. feature for sequencing side effects: the \code{begin} expression. It
  10070. consists of one or more subexpressions that are evaluated
  10071. left to right.
  10072. %
  10073. \fi}
  10074. {\if\edition\pythonEd\pythonColor
  10075. %
  10076. In this chapter we study loops, one of the hallmarks of imperative
  10077. programming languages. The following example demonstrates the
  10078. \code{while} loop by computing the sum of the first five positive
  10079. integers.
  10080. \begin{lstlisting}
  10081. sum = 0
  10082. i = 5
  10083. while i > 0:
  10084. sum = sum + i
  10085. i = i - 1
  10086. print(sum)
  10087. \end{lstlisting}
  10088. The \code{while} loop consists of a condition and a body (a sequence
  10089. of statements). The body is evaluated repeatedly so long as the
  10090. condition remains true.
  10091. %
  10092. \fi}
  10093. \section{The \LangLoop{} Language}
  10094. \newcommand{\LwhileGrammarRacket}{
  10095. \begin{array}{lcl}
  10096. \Type &::=& \key{Void}\\
  10097. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10098. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10099. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10100. \end{array}
  10101. }
  10102. \newcommand{\LwhileASTRacket}{
  10103. \begin{array}{lcl}
  10104. \Type &::=& \key{Void}\\
  10105. \Exp &::=& \SETBANG{\Var}{\Exp}
  10106. \MID \BEGIN{\Exp^{*}}{\Exp}
  10107. \MID \WHILE{\Exp}{\Exp}
  10108. \MID \VOID{}
  10109. \end{array}
  10110. }
  10111. \newcommand{\LwhileGrammarPython}{
  10112. \begin{array}{rcl}
  10113. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10114. \end{array}
  10115. }
  10116. \newcommand{\LwhileASTPython}{
  10117. \begin{array}{lcl}
  10118. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10119. \end{array}
  10120. }
  10121. \begin{figure}[tp]
  10122. \centering
  10123. \begin{tcolorbox}[colback=white]
  10124. \small
  10125. {\if\edition\racketEd
  10126. \[
  10127. \begin{array}{l}
  10128. \gray{\LintGrammarRacket{}} \\ \hline
  10129. \gray{\LvarGrammarRacket{}} \\ \hline
  10130. \gray{\LifGrammarRacket{}} \\ \hline
  10131. \LwhileGrammarRacket \\
  10132. \begin{array}{lcl}
  10133. \LangLoopM{} &::=& \Exp
  10134. \end{array}
  10135. \end{array}
  10136. \]
  10137. \fi}
  10138. {\if\edition\pythonEd\pythonColor
  10139. \[
  10140. \begin{array}{l}
  10141. \gray{\LintGrammarPython} \\ \hline
  10142. \gray{\LvarGrammarPython} \\ \hline
  10143. \gray{\LifGrammarPython} \\ \hline
  10144. \LwhileGrammarPython \\
  10145. \begin{array}{rcl}
  10146. \LangLoopM{} &::=& \Stmt^{*}
  10147. \end{array}
  10148. \end{array}
  10149. \]
  10150. \fi}
  10151. \end{tcolorbox}
  10152. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10153. \label{fig:Lwhile-concrete-syntax}
  10154. \end{figure}
  10155. \begin{figure}[tp]
  10156. \centering
  10157. \begin{tcolorbox}[colback=white]
  10158. \small
  10159. {\if\edition\racketEd
  10160. \[
  10161. \begin{array}{l}
  10162. \gray{\LintOpAST} \\ \hline
  10163. \gray{\LvarASTRacket{}} \\ \hline
  10164. \gray{\LifASTRacket{}} \\ \hline
  10165. \LwhileASTRacket{} \\
  10166. \begin{array}{lcl}
  10167. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10168. \end{array}
  10169. \end{array}
  10170. \]
  10171. \fi}
  10172. {\if\edition\pythonEd\pythonColor
  10173. \[
  10174. \begin{array}{l}
  10175. \gray{\LintASTPython} \\ \hline
  10176. \gray{\LvarASTPython} \\ \hline
  10177. \gray{\LifASTPython} \\ \hline
  10178. \LwhileASTPython \\
  10179. \begin{array}{lcl}
  10180. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10181. \end{array}
  10182. \end{array}
  10183. \]
  10184. \fi}
  10185. \end{tcolorbox}
  10186. \python{
  10187. \index{subject}{While@\texttt{While}}
  10188. }
  10189. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10190. \label{fig:Lwhile-syntax}
  10191. \end{figure}
  10192. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10193. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10194. shows the definition of its abstract syntax.
  10195. %
  10196. The definitional interpreter for \LangLoop{} is shown in
  10197. figure~\ref{fig:interp-Lwhile}.
  10198. %
  10199. {\if\edition\racketEd
  10200. %
  10201. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10202. and \code{Void}, and we make changes to the cases for \code{Var} and
  10203. \code{Let} regarding variables. To support assignment to variables and
  10204. to make their lifetimes indefinite (see the second example in
  10205. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10206. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10207. value.
  10208. %
  10209. Now we discuss the new cases. For \code{SetBang}, we find the
  10210. variable in the environment to obtain a boxed value, and then we change
  10211. it using \code{set-box!} to the result of evaluating the right-hand
  10212. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10213. %
  10214. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10215. if the result is true, (2) evaluate the body.
  10216. The result value of a \code{while} loop is also \code{\#<void>}.
  10217. %
  10218. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10219. subexpressions \itm{es} for their effects and then evaluates
  10220. and returns the result from \itm{body}.
  10221. %
  10222. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10223. %
  10224. \fi}
  10225. {\if\edition\pythonEd\pythonColor
  10226. %
  10227. We add a new case for \code{While} in the \code{interp\_stmts}
  10228. function, in which we repeatedly interpret the \code{body} so long as the
  10229. \code{test} expression remains true.
  10230. %
  10231. \fi}
  10232. \begin{figure}[tbp]
  10233. \begin{tcolorbox}[colback=white]
  10234. {\if\edition\racketEd
  10235. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10236. (define interp-Lwhile-class
  10237. (class interp-Lif-class
  10238. (super-new)
  10239. (define/override ((interp-exp env) e)
  10240. (define recur (interp-exp env))
  10241. (match e
  10242. [(Let x e body)
  10243. (define new-env (dict-set env x (box (recur e))))
  10244. ((interp-exp new-env) body)]
  10245. [(Var x) (unbox (dict-ref env x))]
  10246. [(SetBang x rhs)
  10247. (set-box! (dict-ref env x) (recur rhs))]
  10248. [(WhileLoop cnd body)
  10249. (define (loop)
  10250. (cond [(recur cnd) (recur body) (loop)]
  10251. [else (void)]))
  10252. (loop)]
  10253. [(Begin es body)
  10254. (for ([e es]) (recur e))
  10255. (recur body)]
  10256. [(Void) (void)]
  10257. [else ((super interp-exp env) e)]))
  10258. ))
  10259. (define (interp-Lwhile p)
  10260. (send (new interp-Lwhile-class) interp-program p))
  10261. \end{lstlisting}
  10262. \fi}
  10263. {\if\edition\pythonEd\pythonColor
  10264. \begin{lstlisting}
  10265. class InterpLwhile(InterpLif):
  10266. def interp_stmt(self, s, env, cont):
  10267. match s:
  10268. case While(test, body, []):
  10269. if self.interp_exp(test, env):
  10270. self.interp_stmts(body + [s] + cont, env)
  10271. else:
  10272. return self.interp_stmts(cont, env)
  10273. case _:
  10274. return super().interp_stmt(s, env, cont)
  10275. \end{lstlisting}
  10276. \fi}
  10277. \end{tcolorbox}
  10278. \caption{Interpreter for \LangLoop{}.}
  10279. \label{fig:interp-Lwhile}
  10280. \end{figure}
  10281. The definition of the type checker for \LangLoop{} is shown in
  10282. figure~\ref{fig:type-check-Lwhile}.
  10283. %
  10284. {\if\edition\racketEd
  10285. %
  10286. The type checking of the \code{SetBang} expression requires the type
  10287. of the variable and the right-hand side to agree. The result type is
  10288. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10289. and the result type is \code{Void}. For \code{Begin}, the result type
  10290. is the type of its last subexpression.
  10291. %
  10292. \fi}
  10293. %
  10294. {\if\edition\pythonEd\pythonColor
  10295. %
  10296. A \code{while} loop is well typed if the type of the \code{test}
  10297. expression is \code{bool} and the statements in the \code{body} are
  10298. well typed.
  10299. %
  10300. \fi}
  10301. \begin{figure}[tbp]
  10302. \begin{tcolorbox}[colback=white]
  10303. {\if\edition\racketEd
  10304. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10305. (define type-check-Lwhile-class
  10306. (class type-check-Lif-class
  10307. (super-new)
  10308. (inherit check-type-equal?)
  10309. (define/override (type-check-exp env)
  10310. (lambda (e)
  10311. (define recur (type-check-exp env))
  10312. (match e
  10313. [(SetBang x rhs)
  10314. (define-values (rhs^ rhsT) (recur rhs))
  10315. (define varT (dict-ref env x))
  10316. (check-type-equal? rhsT varT e)
  10317. (values (SetBang x rhs^) 'Void)]
  10318. [(WhileLoop cnd body)
  10319. (define-values (cnd^ Tc) (recur cnd))
  10320. (check-type-equal? Tc 'Boolean e)
  10321. (define-values (body^ Tbody) ((type-check-exp env) body))
  10322. (values (WhileLoop cnd^ body^) 'Void)]
  10323. [(Begin es body)
  10324. (define-values (es^ ts)
  10325. (for/lists (l1 l2) ([e es]) (recur e)))
  10326. (define-values (body^ Tbody) (recur body))
  10327. (values (Begin es^ body^) Tbody)]
  10328. [else ((super type-check-exp env) e)])))
  10329. ))
  10330. (define (type-check-Lwhile p)
  10331. (send (new type-check-Lwhile-class) type-check-program p))
  10332. \end{lstlisting}
  10333. \fi}
  10334. {\if\edition\pythonEd\pythonColor
  10335. \begin{lstlisting}
  10336. class TypeCheckLwhile(TypeCheckLif):
  10337. def type_check_stmts(self, ss, env):
  10338. if len(ss) == 0:
  10339. return
  10340. match ss[0]:
  10341. case While(test, body, []):
  10342. test_t = self.type_check_exp(test, env)
  10343. check_type_equal(bool, test_t, test)
  10344. body_t = self.type_check_stmts(body, env)
  10345. return self.type_check_stmts(ss[1:], env)
  10346. case _:
  10347. return super().type_check_stmts(ss, env)
  10348. \end{lstlisting}
  10349. \fi}
  10350. \end{tcolorbox}
  10351. \caption{Type checker for the \LangLoop{} language.}
  10352. \label{fig:type-check-Lwhile}
  10353. \end{figure}
  10354. {\if\edition\racketEd
  10355. %
  10356. At first glance, the translation of these language features to x86
  10357. seems straightforward because the \LangCIf{} intermediate language
  10358. already supports all the ingredients that we need: assignment,
  10359. \code{goto}, conditional branching, and sequencing. However,
  10360. complications arise, which we discuss in the next section. After
  10361. that we introduce the changes necessary to the existing passes.
  10362. %
  10363. \fi}
  10364. {\if\edition\pythonEd\pythonColor
  10365. %
  10366. At first glance, the translation of \code{while} loops to x86 seems
  10367. straightforward because the \LangCIf{} intermediate language already
  10368. supports \code{goto} and conditional branching. However, there are
  10369. complications that arise, which we discuss in the next section. After
  10370. that we introduce the changes necessary to the existing passes.
  10371. %
  10372. \fi}
  10373. \section{Cyclic Control Flow and Dataflow Analysis}
  10374. \label{sec:dataflow-analysis}
  10375. Up until this point, the programs generated in
  10376. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10377. \code{while} loop introduces a cycle. Does that matter?
  10378. %
  10379. Indeed, it does. Recall that for register allocation, the compiler
  10380. performs liveness analysis to determine which variables can share the
  10381. same register. To accomplish this, we analyzed the control-flow graph
  10382. in reverse topological order
  10383. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10384. well defined only for acyclic graphs.
  10385. Let us return to the example of computing the sum of the first five
  10386. positive integers. Here is the program after instruction
  10387. selection\index{subject}{instruction selection} but before register
  10388. allocation.
  10389. \begin{center}
  10390. {\if\edition\racketEd
  10391. \begin{minipage}{0.45\textwidth}
  10392. \begin{lstlisting}
  10393. (define (main) : Integer
  10394. mainstart:
  10395. movq $0, sum
  10396. movq $5, i
  10397. jmp block5
  10398. block5:
  10399. movq i, tmp3
  10400. cmpq tmp3, $0
  10401. jl block7
  10402. jmp block8
  10403. \end{lstlisting}
  10404. \end{minipage}
  10405. \begin{minipage}{0.45\textwidth}
  10406. \begin{lstlisting}
  10407. block7:
  10408. addq i, sum
  10409. movq $1, tmp4
  10410. negq tmp4
  10411. addq tmp4, i
  10412. jmp block5
  10413. block8:
  10414. movq $27, %rax
  10415. addq sum, %rax
  10416. jmp mainconclusion)
  10417. \end{lstlisting}
  10418. \end{minipage}
  10419. \fi}
  10420. {\if\edition\pythonEd\pythonColor
  10421. \begin{minipage}{0.45\textwidth}
  10422. \begin{lstlisting}
  10423. mainstart:
  10424. movq $0, sum
  10425. movq $5, i
  10426. jmp block5
  10427. block5:
  10428. cmpq $0, i
  10429. jg block7
  10430. jmp block8
  10431. \end{lstlisting}
  10432. \end{minipage}
  10433. \begin{minipage}{0.45\textwidth}
  10434. \begin{lstlisting}
  10435. block7:
  10436. addq i, sum
  10437. subq $1, i
  10438. jmp block5
  10439. block8:
  10440. movq sum, %rdi
  10441. callq print_int
  10442. movq $0, %rax
  10443. jmp mainconclusion
  10444. \end{lstlisting}
  10445. \end{minipage}
  10446. \fi}
  10447. \end{center}
  10448. Recall that liveness analysis works backward, starting at the end
  10449. of each function. For this example we could start with \code{block8}
  10450. because we know what is live at the beginning of the conclusion:
  10451. only \code{rax} and \code{rsp}. So the live-before set
  10452. for \code{block8} is \code{\{rsp,sum\}}.
  10453. %
  10454. Next we might try to analyze \code{block5} or \code{block7}, but
  10455. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10456. we are stuck.
  10457. The way out of this impasse is to realize that we can compute an
  10458. underapproximation of each live-before set by starting with empty
  10459. live-after sets. By \emph{underapproximation}, we mean that the set
  10460. contains only variables that are live for some execution of the
  10461. program, but the set may be missing some variables that are live.
  10462. Next, the underapproximations for each block can be improved by (1)
  10463. updating the live-after set for each block using the approximate
  10464. live-before sets from the other blocks, and (2) performing liveness
  10465. analysis again on each block. In fact, by iterating this process, the
  10466. underapproximations eventually become the correct solutions!
  10467. %
  10468. This approach of iteratively analyzing a control-flow graph is
  10469. applicable to many static analysis problems and goes by the name
  10470. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10471. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10472. Washington.
  10473. Let us apply this approach to the previously presented example. We use
  10474. the empty set for the initial live-before set for each block. Let
  10475. $m_0$ be the following mapping from label names to sets of locations
  10476. (variables and registers):
  10477. \begin{center}
  10478. \begin{lstlisting}
  10479. mainstart: {}, block5: {}, block7: {}, block8: {}
  10480. \end{lstlisting}
  10481. \end{center}
  10482. Using the above live-before approximations, we determine the
  10483. live-after for each block and then apply liveness analysis to each
  10484. block. This produces our next approximation $m_1$ of the live-before
  10485. sets.
  10486. \begin{center}
  10487. \begin{lstlisting}
  10488. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10489. \end{lstlisting}
  10490. \end{center}
  10491. For the second round, the live-after for \code{mainstart} is the
  10492. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10493. the liveness analysis for \code{mainstart} computes the empty set. The
  10494. live-after for \code{block5} is the union of the live-before sets for
  10495. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10496. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10497. sum\}}. The live-after for \code{block7} is the live-before for
  10498. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10499. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10500. Together these yield the following approximation $m_2$ of
  10501. the live-before sets:
  10502. \begin{center}
  10503. \begin{lstlisting}
  10504. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10505. \end{lstlisting}
  10506. \end{center}
  10507. In the preceding iteration, only \code{block5} changed, so we can
  10508. limit our attention to \code{mainstart} and \code{block7}, the two
  10509. blocks that jump to \code{block5}. As a result, the live-before sets
  10510. for \code{mainstart} and \code{block7} are updated to include
  10511. \code{rsp}, yielding the following approximation $m_3$:
  10512. \begin{center}
  10513. \begin{lstlisting}
  10514. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10515. \end{lstlisting}
  10516. \end{center}
  10517. Because \code{block7} changed, we analyze \code{block5} once more, but
  10518. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10519. our approximations have converged, so $m_3$ is the solution.
  10520. This iteration process is guaranteed to converge to a solution by the
  10521. Kleene fixed-point theorem, a general theorem about functions on
  10522. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10523. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10524. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10525. join operator
  10526. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10527. will be working with join semilattices.} When two elements are
  10528. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10529. as much information as $m_i$, so we can think of $m_j$ as a
  10530. better-than-or-equal-to approximation in relation to $m_i$. The
  10531. bottom element $\bot$ represents the complete lack of information,
  10532. that is, the worst approximation. The join operator takes two lattice
  10533. elements and combines their information; that is, it produces the
  10534. least upper bound of the two.\index{subject}{least upper bound}
  10535. A dataflow analysis typically involves two lattices: one lattice to
  10536. represent abstract states and another lattice that aggregates the
  10537. abstract states of all the blocks in the control-flow graph. For
  10538. liveness analysis, an abstract state is a set of locations. We form
  10539. the lattice $L$ by taking its elements to be sets of locations, the
  10540. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10541. set, and the join operator to be set union.
  10542. %
  10543. We form a second lattice $M$ by taking its elements to be mappings
  10544. from the block labels to sets of locations (elements of $L$). We
  10545. order the mappings point-wise, using the ordering of $L$. So, given any
  10546. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10547. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10548. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10549. to the empty set, $\bot_M(\ell) = \emptyset$.
  10550. We can think of one iteration of liveness analysis applied to the
  10551. whole program as being a function $f$ on the lattice $M$. It takes a
  10552. mapping as input and computes a new mapping.
  10553. \[
  10554. f(m_i) = m_{i+1}
  10555. \]
  10556. Next let us think for a moment about what a final solution $m_s$
  10557. should look like. If we perform liveness analysis using the solution
  10558. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10559. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10560. \[
  10561. f(m_s) = m_s
  10562. \]
  10563. Furthermore, the solution should include only locations that are
  10564. forced to be there by performing liveness analysis on the program, so
  10565. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10566. The Kleene fixed-point theorem states that if a function $f$ is
  10567. monotone (better inputs produce better outputs), then the least fixed
  10568. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10569. chain} that starts at $\bot$ and iterates $f$ as
  10570. follows:\index{subject}{Kleene fixed-point theorem}
  10571. \[
  10572. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10573. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10574. \]
  10575. When a lattice contains only finitely long ascending chains, then
  10576. every Kleene chain tops out at some fixed point after some number of
  10577. iterations of $f$.
  10578. \[
  10579. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10580. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10581. \]
  10582. The liveness analysis is indeed a monotone function and the lattice
  10583. $M$ has finitely long ascending chains because there are only a
  10584. finite number of variables and blocks in the program. Thus we are
  10585. guaranteed that iteratively applying liveness analysis to all blocks
  10586. in the program will eventually produce the least fixed point solution.
  10587. Next let us consider dataflow analysis in general and discuss the
  10588. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10589. %
  10590. The algorithm has four parameters: the control-flow graph \code{G}, a
  10591. function \code{transfer} that applies the analysis to one block, and the
  10592. \code{bottom} and \code{join} operators for the lattice of abstract
  10593. states. The \code{analyze\_dataflow} function is formulated as a
  10594. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10595. function come from the predecessor nodes in the control-flow
  10596. graph. However, liveness analysis is a \emph{backward} dataflow
  10597. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10598. function with the transpose of the control-flow graph.
  10599. The algorithm begins by creating the bottom mapping, represented by a
  10600. hash table. It then pushes all the nodes in the control-flow graph
  10601. onto the work list (a queue). The algorithm repeats the \code{while}
  10602. loop as long as there are items in the work list. In each iteration, a
  10603. node is popped from the work list and processed. The \code{input} for
  10604. the node is computed by taking the join of the abstract states of all
  10605. the predecessor nodes. The \code{transfer} function is then applied to
  10606. obtain the \code{output} abstract state. If the output differs from
  10607. the previous state for this block, the mapping for this block is
  10608. updated and its successor nodes are pushed onto the work list.
  10609. \begin{figure}[tb]
  10610. \begin{tcolorbox}[colback=white]
  10611. {\if\edition\racketEd
  10612. \begin{lstlisting}
  10613. (define (analyze_dataflow G transfer bottom join)
  10614. (define mapping (make-hash))
  10615. (for ([v (in-vertices G)])
  10616. (dict-set! mapping v bottom))
  10617. (define worklist (make-queue))
  10618. (for ([v (in-vertices G)])
  10619. (enqueue! worklist v))
  10620. (define trans-G (transpose G))
  10621. (while (not (queue-empty? worklist))
  10622. (define node (dequeue! worklist))
  10623. (define input (for/fold ([state bottom])
  10624. ([pred (in-neighbors trans-G node)])
  10625. (join state (dict-ref mapping pred))))
  10626. (define output (transfer node input))
  10627. (cond [(not (equal? output (dict-ref mapping node)))
  10628. (dict-set! mapping node output)
  10629. (for ([v (in-neighbors G node)])
  10630. (enqueue! worklist v))]))
  10631. mapping)
  10632. \end{lstlisting}
  10633. \fi}
  10634. {\if\edition\pythonEd\pythonColor
  10635. \begin{lstlisting}
  10636. def analyze_dataflow(G, transfer, bottom, join):
  10637. trans_G = transpose(G)
  10638. mapping = dict((v, bottom) for v in G.vertices())
  10639. worklist = deque(G.vertices)
  10640. while worklist:
  10641. node = worklist.pop()
  10642. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10643. input = reduce(join, inputs, bottom)
  10644. output = transfer(node, input)
  10645. if output != mapping[node]:
  10646. mapping[node] = output
  10647. worklist.extend(G.adjacent(node))
  10648. \end{lstlisting}
  10649. \fi}
  10650. \end{tcolorbox}
  10651. \caption{Generic work list algorithm for dataflow analysis.}
  10652. \label{fig:generic-dataflow}
  10653. \end{figure}
  10654. {\if\edition\racketEd
  10655. \section{Mutable Variables and Remove Complex Operands}
  10656. There is a subtle interaction between the
  10657. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10658. and the left-to-right order of evaluation of Racket. Consider the
  10659. following example:
  10660. \begin{lstlisting}
  10661. (let ([x 2])
  10662. (+ x (begin (set! x 40) x)))
  10663. \end{lstlisting}
  10664. The result of this program is \code{42} because the first read from
  10665. \code{x} produces \code{2} and the second produces \code{40}. However,
  10666. if we naively apply the \code{remove\_complex\_operands} pass to this
  10667. example we obtain the following program whose result is \code{80}!
  10668. \begin{lstlisting}
  10669. (let ([x 2])
  10670. (let ([tmp (begin (set! x 40) x)])
  10671. (+ x tmp)))
  10672. \end{lstlisting}
  10673. The problem is that with mutable variables, the ordering between
  10674. reads and writes is important, and the
  10675. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10676. before the first read of \code{x}.
  10677. We recommend solving this problem by giving special treatment to reads
  10678. from mutable variables, that is, variables that occur on the left-hand
  10679. side of a \code{set!}. We mark each read from a mutable variable with
  10680. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10681. that the read operation is effectful in that it can produce different
  10682. results at different points in time. Let's apply this idea to the
  10683. following variation that also involves a variable that is not mutated:
  10684. % loop_test_24.rkt
  10685. \begin{lstlisting}
  10686. (let ([x 2])
  10687. (let ([y 0])
  10688. (+ y (+ x (begin (set! x 40) x)))))
  10689. \end{lstlisting}
  10690. We first analyze this program to discover that variable \code{x}
  10691. is mutable but \code{y} is not. We then transform the program as
  10692. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10693. \begin{lstlisting}
  10694. (let ([x 2])
  10695. (let ([y 0])
  10696. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10697. \end{lstlisting}
  10698. Now that we have a clear distinction between reads from mutable and
  10699. immutable variables, we can apply the \code{remove\_complex\_operands}
  10700. pass, where reads from immutable variables are still classified as
  10701. atomic expressions but reads from mutable variables are classified as
  10702. complex. Thus, \code{remove\_complex\_operands} yields the following
  10703. program:\\
  10704. \begin{minipage}{\textwidth}
  10705. \begin{lstlisting}
  10706. (let ([x 2])
  10707. (let ([y 0])
  10708. (let ([t1 x])
  10709. (let ([t2 (begin (set! x 40) x)])
  10710. (let ([t3 (+ t1 t2)])
  10711. (+ y t3))))))
  10712. \end{lstlisting}
  10713. \end{minipage}
  10714. The temporary variable \code{t1} gets the value of \code{x} before the
  10715. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10716. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10717. do not generate a temporary variable for the occurrence of \code{y}
  10718. because it's an immutable variable. We want to avoid such unnecessary
  10719. extra temporaries because they would needlessly increase the number of
  10720. variables, making it more likely for some of them to be spilled. The
  10721. result of this program is \code{42}, the same as the result prior to
  10722. \code{remove\_complex\_operands}.
  10723. The approach that we've sketched requires only a small
  10724. modification to \code{remove\_complex\_operands} to handle
  10725. \code{get!}. However, it requires a new pass, called
  10726. \code{uncover-get!}, that we discuss in
  10727. section~\ref{sec:uncover-get-bang}.
  10728. As an aside, this problematic interaction between \code{set!} and the
  10729. pass \code{remove\_complex\_operands} is particular to Racket and not
  10730. its predecessor, the Scheme language. The key difference is that
  10731. Scheme does not specify an order of evaluation for the arguments of an
  10732. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10733. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10734. would be correct results for the example program. Interestingly,
  10735. Racket is implemented on top of the Chez Scheme
  10736. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10737. presented in this section (using extra \code{let} bindings to control
  10738. the order of evaluation) is used in the translation from Racket to
  10739. Scheme~\citep{Flatt:2019tb}.
  10740. \fi} % racket
  10741. Having discussed the complications that arise from adding support for
  10742. assignment and loops, we turn to discussing the individual compilation
  10743. passes.
  10744. {\if\edition\racketEd
  10745. \section{Uncover \texttt{get!}}
  10746. \label{sec:uncover-get-bang}
  10747. The goal of this pass is to mark uses of mutable variables so that
  10748. \code{remove\_complex\_operands} can treat them as complex expressions
  10749. and thereby preserve their ordering relative to the side effects in
  10750. other operands. So, the first step is to collect all the mutable
  10751. variables. We recommend creating an auxiliary function for this,
  10752. named \code{collect-set!}, that recursively traverses expressions,
  10753. returning the set of all variables that occur on the left-hand side of a
  10754. \code{set!}. Here's an excerpt of its implementation.
  10755. \begin{center}
  10756. \begin{minipage}{\textwidth}
  10757. \begin{lstlisting}
  10758. (define (collect-set! e)
  10759. (match e
  10760. [(Var x) (set)]
  10761. [(Int n) (set)]
  10762. [(Let x rhs body)
  10763. (set-union (collect-set! rhs) (collect-set! body))]
  10764. [(SetBang var rhs)
  10765. (set-union (set var) (collect-set! rhs))]
  10766. ...))
  10767. \end{lstlisting}
  10768. \end{minipage}
  10769. \end{center}
  10770. By placing this pass after \code{uniquify}, we need not worry about
  10771. variable shadowing, and our logic for \code{Let} can remain simple, as
  10772. in this excerpt.
  10773. The second step is to mark the occurrences of the mutable variables
  10774. with the new \code{GetBang} AST node (\code{get!} in concrete
  10775. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10776. function, which takes two parameters: the set of mutable variables
  10777. \code{set!-vars} and the expression \code{e} to be processed. The
  10778. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10779. mutable variable or leaves it alone if not.
  10780. \begin{center}
  10781. \begin{minipage}{\textwidth}
  10782. \begin{lstlisting}
  10783. (define ((uncover-get!-exp set!-vars) e)
  10784. (match e
  10785. [(Var x)
  10786. (if (set-member? set!-vars x)
  10787. (GetBang x)
  10788. (Var x))]
  10789. ...))
  10790. \end{lstlisting}
  10791. \end{minipage}
  10792. \end{center}
  10793. To wrap things up, define the \code{uncover-get!} function for
  10794. processing a whole program, using \code{collect-set!} to obtain the
  10795. set of mutable variables and then \code{uncover-get!-exp} to replace
  10796. their occurrences with \code{GetBang}.
  10797. \fi}
  10798. \section{Remove Complex Operands}
  10799. \label{sec:rco-loop}
  10800. {\if\edition\racketEd
  10801. %
  10802. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10803. \code{while} are all complex expressions. The subexpressions of
  10804. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10805. %
  10806. \fi}
  10807. {\if\edition\pythonEd\pythonColor
  10808. %
  10809. The change needed for this pass is to add a case for the \code{while}
  10810. statement. The condition of a loop is allowed to be a complex
  10811. expression, just like the condition of the \code{if} statement.
  10812. %
  10813. \fi}
  10814. %
  10815. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10816. \LangLoopANF{} of this pass.
  10817. \newcommand{\LwhileMonadASTRacket}{
  10818. \begin{array}{rcl}
  10819. \Atm &::=& \VOID{} \\
  10820. \Exp &::=& \GETBANG{\Var}
  10821. \MID \SETBANG{\Var}{\Exp}
  10822. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10823. &\MID& \WHILE{\Exp}{\Exp}
  10824. \end{array}
  10825. }
  10826. \newcommand{\LwhileMonadASTPython}{
  10827. \begin{array}{rcl}
  10828. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10829. \end{array}
  10830. }
  10831. \begin{figure}[tp]
  10832. \centering
  10833. \begin{tcolorbox}[colback=white]
  10834. \small
  10835. {\if\edition\racketEd
  10836. \[
  10837. \begin{array}{l}
  10838. \gray{\LvarMonadASTRacket} \\ \hline
  10839. \gray{\LifMonadASTRacket} \\ \hline
  10840. \LwhileMonadASTRacket \\
  10841. \begin{array}{rcl}
  10842. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10843. \end{array}
  10844. \end{array}
  10845. \]
  10846. \fi}
  10847. {\if\edition\pythonEd\pythonColor
  10848. \[
  10849. \begin{array}{l}
  10850. \gray{\LvarMonadASTPython} \\ \hline
  10851. \gray{\LifMonadASTPython} \\ \hline
  10852. \LwhileMonadASTPython \\
  10853. \begin{array}{rcl}
  10854. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10855. \end{array}
  10856. \end{array}
  10857. \]
  10858. \fi}
  10859. \end{tcolorbox}
  10860. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10861. \label{fig:Lwhile-anf-syntax}
  10862. \end{figure}
  10863. {\if\edition\racketEd
  10864. %
  10865. As usual, when a complex expression appears in a grammar position that
  10866. needs to be atomic, such as the argument of a primitive operator, we
  10867. must introduce a temporary variable and bind it to the complex
  10868. expression. This approach applies, unchanged, to handle the new
  10869. language forms. For example, in the following code there are two
  10870. \code{begin} expressions appearing as arguments to the \code{+}
  10871. operator. The output of \code{rco\_exp} is then shown, in which the
  10872. \code{begin} expressions have been bound to temporary
  10873. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10874. allowed to have arbitrary expressions in their right-hand side
  10875. expression, so it is fine to place \code{begin} there.
  10876. %
  10877. \begin{center}
  10878. \begin{tabular}{lcl}
  10879. \begin{minipage}{0.4\textwidth}
  10880. \begin{lstlisting}
  10881. (let ([x2 10])
  10882. (let ([y3 0])
  10883. (+ (+ (begin
  10884. (set! y3 (read))
  10885. (get! x2))
  10886. (begin
  10887. (set! x2 (read))
  10888. (get! y3)))
  10889. (get! x2))))
  10890. \end{lstlisting}
  10891. \end{minipage}
  10892. &
  10893. $\Rightarrow$
  10894. &
  10895. \begin{minipage}{0.4\textwidth}
  10896. \begin{lstlisting}
  10897. (let ([x2 10])
  10898. (let ([y3 0])
  10899. (let ([tmp4 (begin
  10900. (set! y3 (read))
  10901. x2)])
  10902. (let ([tmp5 (begin
  10903. (set! x2 (read))
  10904. y3)])
  10905. (let ([tmp6 (+ tmp4 tmp5)])
  10906. (let ([tmp7 x2])
  10907. (+ tmp6 tmp7)))))))
  10908. \end{lstlisting}
  10909. \end{minipage}
  10910. \end{tabular}
  10911. \end{center}
  10912. \fi}
  10913. \section{Explicate Control \racket{and \LangCLoop{}}}
  10914. \label{sec:explicate-loop}
  10915. \newcommand{\CloopASTRacket}{
  10916. \begin{array}{lcl}
  10917. \Atm &::=& \VOID \\
  10918. \Stmt &::=& \READ{}
  10919. \end{array}
  10920. }
  10921. {\if\edition\racketEd
  10922. Recall that in the \code{explicate\_control} pass we define one helper
  10923. function for each kind of position in the program. For the \LangVar{}
  10924. language of integers and variables, we needed assignment and tail
  10925. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10926. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10927. another kind of position: effect position. Except for the last
  10928. subexpression, the subexpressions inside a \code{begin} are evaluated
  10929. only for their effect. Their result values are discarded. We can
  10930. generate better code by taking this fact into account.
  10931. The output language of \code{explicate\_control} is \LangCLoop{}
  10932. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10933. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10934. and that \code{read} may appear as a statement. The most significant
  10935. difference between the programs generated by \code{explicate\_control}
  10936. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10937. chapter is that the control-flow graphs of the latter may contain
  10938. cycles.
  10939. \begin{figure}[tp]
  10940. \begin{tcolorbox}[colback=white]
  10941. \small
  10942. \[
  10943. \begin{array}{l}
  10944. \gray{\CvarASTRacket} \\ \hline
  10945. \gray{\CifASTRacket} \\ \hline
  10946. \CloopASTRacket \\
  10947. \begin{array}{lcl}
  10948. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10949. \end{array}
  10950. \end{array}
  10951. \]
  10952. \end{tcolorbox}
  10953. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10954. \label{fig:c7-syntax}
  10955. \end{figure}
  10956. The new auxiliary function \code{explicate\_effect} takes an
  10957. expression (in an effect position) and the code for its
  10958. continuation. The function returns a $\Tail$ that includes the
  10959. generated code for the input expression followed by the
  10960. continuation. If the expression is obviously pure, that is, never
  10961. causes side effects, then the expression can be removed, so the result
  10962. is just the continuation.
  10963. %
  10964. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10965. interesting; the generated code is depicted in the following diagram:
  10966. \begin{center}
  10967. \begin{minipage}{0.3\textwidth}
  10968. \xymatrix{
  10969. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10970. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10971. & *+[F]{\txt{\itm{cont}}} \\
  10972. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10973. }
  10974. \end{minipage}
  10975. \end{center}
  10976. We start by creating a fresh label $\itm{loop}$ for the top of the
  10977. loop. Next, recursively process the \itm{body} (in effect position)
  10978. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10979. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10980. \itm{body'} as the \emph{then} branch and the continuation block as the
  10981. \emph{else} branch. The result should be added to the dictionary of
  10982. \code{basic-blocks} with the label \itm{loop}. The result for the
  10983. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10984. The auxiliary functions for tail, assignment, and predicate positions
  10985. need to be updated. The three new language forms, \code{while},
  10986. \code{set!}, and \code{begin}, can appear in assignment and tail
  10987. positions. Only \code{begin} may appear in predicate positions; the
  10988. other two have result type \code{Void}.
  10989. \fi}
  10990. %
  10991. {\if\edition\pythonEd\pythonColor
  10992. %
  10993. The output of this pass is the language \LangCIf{}. No new language
  10994. features are needed in the output, because a \code{while} loop can be
  10995. expressed in terms of \code{goto} and \code{if} statements, which are
  10996. already in \LangCIf{}.
  10997. %
  10998. Add a case for the \code{while} statement to the
  10999. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11000. the condition expression.
  11001. %
  11002. \fi}
  11003. {\if\edition\racketEd
  11004. \section{Select Instructions}
  11005. \label{sec:select-instructions-loop}
  11006. \index{subject}{select instructions}
  11007. Only two small additions are needed in the \code{select\_instructions}
  11008. pass to handle the changes to \LangCLoop{}. First, to handle the
  11009. addition of \VOID{} we simply translate it to \code{0}. Second,
  11010. \code{read} may appear as a stand-alone statement instead of
  11011. appearing only on the right-hand side of an assignment statement. The code
  11012. generation is nearly identical to the one for assignment; just leave
  11013. off the instruction for moving the result into the left-hand side.
  11014. \fi}
  11015. \section{Register Allocation}
  11016. \label{sec:register-allocation-loop}
  11017. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11018. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11019. which complicates the liveness analysis needed for register
  11020. allocation.
  11021. %
  11022. We recommend using the generic \code{analyze\_dataflow} function that
  11023. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11024. perform liveness analysis, replacing the code in
  11025. \code{uncover\_live} that processed the basic blocks in topological
  11026. order (section~\ref{sec:liveness-analysis-Lif}).
  11027. The \code{analyze\_dataflow} function has the following four parameters.
  11028. \begin{enumerate}
  11029. \item The first parameter \code{G} should be passed the transpose
  11030. of the control-flow graph.
  11031. \item The second parameter \code{transfer} should be passed a function
  11032. that applies liveness analysis to a basic block. It takes two
  11033. parameters: the label for the block to analyze and the live-after
  11034. set for that block. The transfer function should return the
  11035. live-before set for the block.
  11036. %
  11037. \racket{Also, as a side effect, it should update the block's
  11038. $\itm{info}$ with the liveness information for each instruction.}
  11039. %
  11040. \python{Also, as a side effect, it should update the live-before and
  11041. live-after sets for each instruction.}
  11042. %
  11043. To implement the \code{transfer} function, you should be able to
  11044. reuse the code you already have for analyzing basic blocks.
  11045. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11046. \code{bottom} and \code{join} for the lattice of abstract states,
  11047. that is, sets of locations. For liveness analysis, the bottom of the
  11048. lattice is the empty set, and the join operator is set union.
  11049. \end{enumerate}
  11050. \begin{figure}[tp]
  11051. \begin{tcolorbox}[colback=white]
  11052. {\if\edition\racketEd
  11053. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11054. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11055. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11056. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11057. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11058. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11059. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11060. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11061. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11062. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11063. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11064. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11065. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11066. \path[->,bend left=15] (Lfun) edge [above] node
  11067. {\ttfamily\footnotesize shrink} (Lfun-2);
  11068. \path[->,bend left=15] (Lfun-2) edge [above] node
  11069. {\ttfamily\footnotesize uniquify} (F1-4);
  11070. \path[->,bend left=15] (F1-4) edge [above] node
  11071. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11072. \path[->,bend left=15] (F1-5) edge [left] node
  11073. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11074. \path[->,bend left=10] (F1-6) edge [above] node
  11075. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11076. \path[->,bend left=15] (C3-2) edge [right] node
  11077. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11078. \path[->,bend right=15] (x86-2) edge [right] node
  11079. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11080. \path[->,bend right=15] (x86-2-1) edge [below] node
  11081. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11082. \path[->,bend right=15] (x86-2-2) edge [right] node
  11083. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11084. \path[->,bend left=15] (x86-3) edge [above] node
  11085. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11086. \path[->,bend left=15] (x86-4) edge [right] node
  11087. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11088. \end{tikzpicture}
  11089. \fi}
  11090. {\if\edition\pythonEd\pythonColor
  11091. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11092. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11093. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11094. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11095. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11096. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11097. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11098. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11099. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11100. \path[->,bend left=15] (Lfun) edge [above] node
  11101. {\ttfamily\footnotesize shrink} (Lfun-2);
  11102. \path[->,bend left=15] (Lfun-2) edge [above] node
  11103. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11104. \path[->,bend left=10] (F1-6) edge [right] node
  11105. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11106. \path[->,bend right=15] (C3-2) edge [right] node
  11107. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11108. \path[->,bend right=15] (x86-2) edge [below] node
  11109. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11110. \path[->,bend left=15] (x86-3) edge [above] node
  11111. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11112. \path[->,bend right=15] (x86-4) edge [below] node
  11113. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11114. \end{tikzpicture}
  11115. \fi}
  11116. \end{tcolorbox}
  11117. \caption{Diagram of the passes for \LangLoop{}.}
  11118. \label{fig:Lwhile-passes}
  11119. \end{figure}
  11120. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11121. for the compilation of \LangLoop{}.
  11122. % Further Reading: dataflow analysis
  11123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11124. \chapter{Tuples and Garbage Collection}
  11125. \label{ch:Lvec}
  11126. \index{subject}{tuple}
  11127. \index{subject}{vector}
  11128. \setcounter{footnote}{0}
  11129. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11130. %% all the IR grammars are spelled out! \\ --Jeremy}
  11131. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11132. %% the root stack. \\ --Jeremy}
  11133. In this chapter we study the implementation of tuples\racket{, called
  11134. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11135. in which each element may have a different type.
  11136. %
  11137. This language feature is the first to use the computer's
  11138. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11139. indefinite; that is, a tuple lives forever from the programmer's
  11140. viewpoint. Of course, from an implementer's viewpoint, it is important
  11141. to reclaim the space associated with a tuple when it is no longer
  11142. needed, which is why we also study \emph{garbage collection}
  11143. \index{subject}{garbage collection} techniques in this chapter.
  11144. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11145. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11146. language (chapter~\ref{ch:Lwhile}) with tuples.
  11147. %
  11148. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11149. copying live tuples back and forth between two halves of the heap. The
  11150. garbage collector requires coordination with the compiler so that it
  11151. can find all the live tuples.
  11152. %
  11153. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11154. discuss the necessary changes and additions to the compiler passes,
  11155. including a new compiler pass named \code{expose\_allocation}.
  11156. \section{The \LangVec{} Language}
  11157. \label{sec:r3}
  11158. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11159. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11160. the definition of the abstract syntax.
  11161. %
  11162. \racket{The \LangVec{} language includes the forms \code{vector} for
  11163. creating a tuple, \code{vector-ref} for reading an element of a
  11164. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11165. \code{vector-length} for obtaining the number of elements of a
  11166. tuple.}
  11167. %
  11168. \python{The \LangVec{} language adds (1) tuple creation via a
  11169. comma-separated list of expressions; (2) accessing an element of a
  11170. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11171. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11172. comparison operator; and (4) obtaining the number of elements (the
  11173. length) of a tuple. In this chapter, we restrict access indices to
  11174. constant integers.}
  11175. %
  11176. The following program shows an example of the use of tuples. It creates a tuple
  11177. \code{t} containing the elements \code{40},
  11178. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11179. contains just \code{2}. The element at index $1$ of \code{t} is
  11180. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11181. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11182. to which we add \code{2}, the element at index $0$ of the tuple.
  11183. The result of the program is \code{42}.
  11184. %
  11185. {\if\edition\racketEd
  11186. \begin{lstlisting}
  11187. (let ([t (vector 40 #t (vector 2))])
  11188. (if (vector-ref t 1)
  11189. (+ (vector-ref t 0)
  11190. (vector-ref (vector-ref t 2) 0))
  11191. 44))
  11192. \end{lstlisting}
  11193. \fi}
  11194. {\if\edition\pythonEd\pythonColor
  11195. \begin{lstlisting}
  11196. t = 40, True, (2,)
  11197. print(t[0] + t[2][0] if t[1] else 44)
  11198. \end{lstlisting}
  11199. \fi}
  11200. \newcommand{\LtupGrammarRacket}{
  11201. \begin{array}{lcl}
  11202. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11203. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11204. \MID \LP\key{vector-length}\;\Exp\RP \\
  11205. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11206. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11207. \end{array}
  11208. }
  11209. \newcommand{\LtupASTRacket}{
  11210. \begin{array}{lcl}
  11211. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11212. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11213. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11214. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11215. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11216. \end{array}
  11217. }
  11218. \newcommand{\LtupGrammarPython}{
  11219. \begin{array}{rcl}
  11220. \itm{cmp} &::= & \key{is} \\
  11221. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11222. \end{array}
  11223. }
  11224. \newcommand{\LtupASTPython}{
  11225. \begin{array}{lcl}
  11226. \itm{cmp} &::= & \code{Is()} \\
  11227. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11228. &\MID& \LEN{\Exp}
  11229. \end{array}
  11230. }
  11231. \begin{figure}[tbp]
  11232. \centering
  11233. \begin{tcolorbox}[colback=white]
  11234. \small
  11235. {\if\edition\racketEd
  11236. \[
  11237. \begin{array}{l}
  11238. \gray{\LintGrammarRacket{}} \\ \hline
  11239. \gray{\LvarGrammarRacket{}} \\ \hline
  11240. \gray{\LifGrammarRacket{}} \\ \hline
  11241. \gray{\LwhileGrammarRacket} \\ \hline
  11242. \LtupGrammarRacket \\
  11243. \begin{array}{lcl}
  11244. \LangVecM{} &::=& \Exp
  11245. \end{array}
  11246. \end{array}
  11247. \]
  11248. \fi}
  11249. {\if\edition\pythonEd\pythonColor
  11250. \[
  11251. \begin{array}{l}
  11252. \gray{\LintGrammarPython{}} \\ \hline
  11253. \gray{\LvarGrammarPython{}} \\ \hline
  11254. \gray{\LifGrammarPython{}} \\ \hline
  11255. \gray{\LwhileGrammarPython} \\ \hline
  11256. \LtupGrammarPython \\
  11257. \begin{array}{rcl}
  11258. \LangVecM{} &::=& \Stmt^{*}
  11259. \end{array}
  11260. \end{array}
  11261. \]
  11262. \fi}
  11263. \end{tcolorbox}
  11264. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11265. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11266. \label{fig:Lvec-concrete-syntax}
  11267. \end{figure}
  11268. \begin{figure}[tp]
  11269. \centering
  11270. \begin{tcolorbox}[colback=white]
  11271. \small
  11272. {\if\edition\racketEd
  11273. \[
  11274. \begin{array}{l}
  11275. \gray{\LintOpAST} \\ \hline
  11276. \gray{\LvarASTRacket{}} \\ \hline
  11277. \gray{\LifASTRacket{}} \\ \hline
  11278. \gray{\LwhileASTRacket{}} \\ \hline
  11279. \LtupASTRacket{} \\
  11280. \begin{array}{lcl}
  11281. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11282. \end{array}
  11283. \end{array}
  11284. \]
  11285. \fi}
  11286. {\if\edition\pythonEd\pythonColor
  11287. \[
  11288. \begin{array}{l}
  11289. \gray{\LintASTPython} \\ \hline
  11290. \gray{\LvarASTPython} \\ \hline
  11291. \gray{\LifASTPython} \\ \hline
  11292. \gray{\LwhileASTPython} \\ \hline
  11293. \LtupASTPython \\
  11294. \begin{array}{lcl}
  11295. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11296. \end{array}
  11297. \end{array}
  11298. \]
  11299. \fi}
  11300. \end{tcolorbox}
  11301. \caption{The abstract syntax of \LangVec{}.}
  11302. \label{fig:Lvec-syntax}
  11303. \end{figure}
  11304. Tuples raise several interesting new issues. First, variable binding
  11305. performs a shallow copy in dealing with tuples, which means that
  11306. different variables can refer to the same tuple; that is, two
  11307. variables can be \emph{aliases}\index{subject}{alias} for the same
  11308. entity. Consider the following example, in which \code{t1} and
  11309. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11310. different tuple value with equal elements. The result of the
  11311. program is \code{42}.
  11312. \begin{center}
  11313. \begin{minipage}{0.96\textwidth}
  11314. {\if\edition\racketEd
  11315. \begin{lstlisting}
  11316. (let ([t1 (vector 3 7)])
  11317. (let ([t2 t1])
  11318. (let ([t3 (vector 3 7)])
  11319. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11320. 42
  11321. 0))))
  11322. \end{lstlisting}
  11323. \fi}
  11324. {\if\edition\pythonEd\pythonColor
  11325. \begin{lstlisting}
  11326. t1 = 3, 7
  11327. t2 = t1
  11328. t3 = 3, 7
  11329. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11330. \end{lstlisting}
  11331. \fi}
  11332. \end{minipage}
  11333. \end{center}
  11334. {\if\edition\racketEd
  11335. Whether two variables are aliased or not affects what happens
  11336. when the underlying tuple is mutated\index{subject}{mutation}.
  11337. Consider the following example in which \code{t1} and \code{t2}
  11338. again refer to the same tuple value.
  11339. \begin{center}
  11340. \begin{minipage}{0.96\textwidth}
  11341. \begin{lstlisting}
  11342. (let ([t1 (vector 3 7)])
  11343. (let ([t2 t1])
  11344. (let ([_ (vector-set! t2 0 42)])
  11345. (vector-ref t1 0))))
  11346. \end{lstlisting}
  11347. \end{minipage}
  11348. \end{center}
  11349. The mutation through \code{t2} is visible in referencing the tuple
  11350. from \code{t1}, so the result of this program is \code{42}.
  11351. \fi}
  11352. The next issue concerns the lifetime of tuples. When does a tuple's
  11353. lifetime end? Notice that \LangVec{} does not include an operation
  11354. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11355. to any notion of static scoping.
  11356. %
  11357. {\if\edition\racketEd
  11358. %
  11359. For example, the following program returns \code{42} even though the
  11360. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11361. that reads from the vector to which it was bound.
  11362. \begin{center}
  11363. \begin{minipage}{0.96\textwidth}
  11364. \begin{lstlisting}
  11365. (let ([v (vector (vector 44))])
  11366. (let ([x (let ([w (vector 42)])
  11367. (let ([_ (vector-set! v 0 w)])
  11368. 0))])
  11369. (+ x (vector-ref (vector-ref v 0) 0))))
  11370. \end{lstlisting}
  11371. \end{minipage}
  11372. \end{center}
  11373. \fi}
  11374. %
  11375. {\if\edition\pythonEd\pythonColor
  11376. %
  11377. For example, the following program returns \code{42} even though the
  11378. variable \code{x} goes out of scope when the function returns, prior
  11379. to reading the tuple element at index $0$. (We study the compilation
  11380. of functions in chapter~\ref{ch:Lfun}.)
  11381. %
  11382. \begin{center}
  11383. \begin{minipage}{0.96\textwidth}
  11384. \begin{lstlisting}
  11385. def f():
  11386. x = 42, 43
  11387. return x
  11388. t = f()
  11389. print(t[0])
  11390. \end{lstlisting}
  11391. \end{minipage}
  11392. \end{center}
  11393. \fi}
  11394. %
  11395. From the perspective of programmer-observable behavior, tuples live
  11396. forever. However, if they really lived forever then many long-running
  11397. programs would run out of memory. To solve this problem, the
  11398. language's runtime system performs automatic garbage collection.
  11399. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11400. \LangVec{} language.
  11401. %
  11402. \racket{We define the \code{vector}, \code{vector-ref},
  11403. \code{vector-set!}, and \code{vector-length} operations for
  11404. \LangVec{} in terms of the corresponding operations in Racket. One
  11405. subtle point is that the \code{vector-set!} operation returns the
  11406. \code{\#<void>} value.}
  11407. %
  11408. \python{We represent tuples with Python lists in the interpreter
  11409. because we need to write to them
  11410. (section~\ref{sec:expose-allocation}). (Python tuples are
  11411. immutable.) We define element access, the \code{is} operator, and
  11412. the \code{len} operator for \LangVec{} in terms of the corresponding
  11413. operations in Python.}
  11414. \begin{figure}[tbp]
  11415. \begin{tcolorbox}[colback=white]
  11416. {\if\edition\racketEd
  11417. \begin{lstlisting}
  11418. (define interp-Lvec-class
  11419. (class interp-Lwhile-class
  11420. (super-new)
  11421. (define/override (interp-op op)
  11422. (match op
  11423. ['eq? (lambda (v1 v2)
  11424. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11425. (and (boolean? v1) (boolean? v2))
  11426. (and (vector? v1) (vector? v2))
  11427. (and (void? v1) (void? v2)))
  11428. (eq? v1 v2)]))]
  11429. ['vector vector]
  11430. ['vector-length vector-length]
  11431. ['vector-ref vector-ref]
  11432. ['vector-set! vector-set!]
  11433. [else (super interp-op op)]
  11434. ))
  11435. (define/override ((interp-exp env) e)
  11436. (match e
  11437. [(HasType e t) ((interp-exp env) e)]
  11438. [else ((super interp-exp env) e)]
  11439. ))
  11440. ))
  11441. (define (interp-Lvec p)
  11442. (send (new interp-Lvec-class) interp-program p))
  11443. \end{lstlisting}
  11444. \fi}
  11445. %
  11446. {\if\edition\pythonEd\pythonColor
  11447. \begin{lstlisting}
  11448. class InterpLtup(InterpLwhile):
  11449. def interp_cmp(self, cmp):
  11450. match cmp:
  11451. case Is():
  11452. return lambda x, y: x is y
  11453. case _:
  11454. return super().interp_cmp(cmp)
  11455. def interp_exp(self, e, env):
  11456. match e:
  11457. case Tuple(es, Load()):
  11458. return tuple([self.interp_exp(e, env) for e in es])
  11459. case Subscript(tup, index, Load()):
  11460. t = self.interp_exp(tup, env)
  11461. n = self.interp_exp(index, env)
  11462. return t[n]
  11463. case _:
  11464. return super().interp_exp(e, env)
  11465. \end{lstlisting}
  11466. \fi}
  11467. \end{tcolorbox}
  11468. \caption{Interpreter for the \LangVec{} language.}
  11469. \label{fig:interp-Lvec}
  11470. \end{figure}
  11471. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11472. \LangVec{}.
  11473. %
  11474. The type of a tuple is a
  11475. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11476. type for each of its elements.
  11477. %
  11478. \racket{To create the s-expression for the \code{Vector} type, we use the
  11479. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11480. operator} \code{,@} to insert the list \code{t*} without its usual
  11481. start and end parentheses. \index{subject}{unquote-splicing}}
  11482. %
  11483. The type of accessing the ith element of a tuple is the ith element
  11484. type of the tuple's type, if there is one. If not, an error is
  11485. signaled. Note that the index \code{i} is required to be a constant
  11486. integer (and not, for example, a call to
  11487. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11488. can determine the element's type given the tuple type.
  11489. %
  11490. \racket{
  11491. Regarding writing an element to a tuple, the element's type must
  11492. be equal to the ith element type of the tuple's type.
  11493. The result type is \code{Void}.}
  11494. %% When allocating a tuple,
  11495. %% we need to know which elements of the tuple are themselves tuples for
  11496. %% the purposes of garbage collection. We can obtain this information
  11497. %% during type checking. The type checker shown in
  11498. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11499. %% expression; it also
  11500. %% %
  11501. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11502. %% where $T$ is the tuple's type.
  11503. %
  11504. %records the type of each tuple expression in a new field named \code{has\_type}.
  11505. \begin{figure}[tp]
  11506. \begin{tcolorbox}[colback=white]
  11507. {\if\edition\racketEd
  11508. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11509. (define type-check-Lvec-class
  11510. (class type-check-Lif-class
  11511. (super-new)
  11512. (inherit check-type-equal?)
  11513. (define/override (type-check-exp env)
  11514. (lambda (e)
  11515. (define recur (type-check-exp env))
  11516. (match e
  11517. [(Prim 'vector es)
  11518. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11519. (define t `(Vector ,@t*))
  11520. (values (Prim 'vector e*) t)]
  11521. [(Prim 'vector-ref (list e1 (Int i)))
  11522. (define-values (e1^ t) (recur e1))
  11523. (match t
  11524. [`(Vector ,ts ...)
  11525. (unless (and (0 . <= . i) (i . < . (length ts)))
  11526. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11527. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11528. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11529. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11530. (define-values (e-vec t-vec) (recur e1))
  11531. (define-values (e-elt^ t-elt) (recur elt))
  11532. (match t-vec
  11533. [`(Vector ,ts ...)
  11534. (unless (and (0 . <= . i) (i . < . (length ts)))
  11535. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11536. (check-type-equal? (list-ref ts i) t-elt e)
  11537. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11538. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11539. [(Prim 'vector-length (list e))
  11540. (define-values (e^ t) (recur e))
  11541. (match t
  11542. [`(Vector ,ts ...)
  11543. (values (Prim 'vector-length (list e^)) 'Integer)]
  11544. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11545. [(Prim 'eq? (list arg1 arg2))
  11546. (define-values (e1 t1) (recur arg1))
  11547. (define-values (e2 t2) (recur arg2))
  11548. (match* (t1 t2)
  11549. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11550. [(other wise) (check-type-equal? t1 t2 e)])
  11551. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11552. [else ((super type-check-exp env) e)]
  11553. )))
  11554. ))
  11555. (define (type-check-Lvec p)
  11556. (send (new type-check-Lvec-class) type-check-program p))
  11557. \end{lstlisting}
  11558. \fi}
  11559. {\if\edition\pythonEd\pythonColor
  11560. \begin{lstlisting}
  11561. class TypeCheckLtup(TypeCheckLwhile):
  11562. def type_check_exp(self, e, env):
  11563. match e:
  11564. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11565. l = self.type_check_exp(left, env)
  11566. r = self.type_check_exp(right, env)
  11567. check_type_equal(l, r, e)
  11568. return bool
  11569. case Tuple(es, Load()):
  11570. ts = [self.type_check_exp(e, env) for e in es]
  11571. e.has_type = TupleType(ts)
  11572. return e.has_type
  11573. case Subscript(tup, Constant(i), Load()):
  11574. tup_ty = self.type_check_exp(tup, env)
  11575. i_ty = self.type_check_exp(Constant(i), env)
  11576. check_type_equal(i_ty, int, i)
  11577. match tup_ty:
  11578. case TupleType(ts):
  11579. return ts[i]
  11580. case _:
  11581. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11582. case _:
  11583. return super().type_check_exp(e, env)
  11584. \end{lstlisting}
  11585. \fi}
  11586. \end{tcolorbox}
  11587. \caption{Type checker for the \LangVec{} language.}
  11588. \label{fig:type-check-Lvec}
  11589. \end{figure}
  11590. \section{Garbage Collection}
  11591. \label{sec:GC}
  11592. Garbage collection is a runtime technique for reclaiming space on the
  11593. heap that will not be used in the future of the running program. We
  11594. use the term \emph{object}\index{subject}{object} to refer to any
  11595. value that is stored in the heap, which for now includes only
  11596. tuples.%
  11597. %
  11598. \footnote{The term \emph{object} as it is used in the context of
  11599. object-oriented programming has a more specific meaning than the
  11600. way in which we use the term here.}
  11601. %
  11602. Unfortunately, it is impossible to know precisely which objects will
  11603. be accessed in the future and which will not. Instead, garbage
  11604. collectors overapproximate the set of objects that will be accessed by
  11605. identifying which objects can possibly be accessed. The running
  11606. program can directly access objects that are in registers and on the
  11607. procedure call stack. It can also transitively access the elements of
  11608. tuples, starting with a tuple whose address is in a register or on the
  11609. procedure call stack. We define the \emph{root
  11610. set}\index{subject}{root set} to be all the tuple addresses that are
  11611. in registers or on the procedure call stack. We define the \emph{live
  11612. objects}\index{subject}{live objects} to be the objects that are
  11613. reachable from the root set. Garbage collectors reclaim the space that
  11614. is allocated to objects that are no longer live. \index{subject}{allocate}
  11615. That means that some objects may not get reclaimed as soon as they could be,
  11616. but at least
  11617. garbage collectors do not reclaim the space dedicated to objects that
  11618. will be accessed in the future! The programmer can influence which
  11619. objects get reclaimed by causing them to become unreachable.
  11620. So the goal of the garbage collector is twofold:
  11621. \begin{enumerate}
  11622. \item to preserve all the live objects, and
  11623. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11624. \end{enumerate}
  11625. \subsection{Two-Space Copying Collector}
  11626. Here we study a relatively simple algorithm for garbage collection
  11627. that is the basis of many state-of-the-art garbage
  11628. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11629. particular, we describe a two-space copying
  11630. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11631. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11632. collector} \index{subject}{two-space copying collector}
  11633. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11634. what happens in a two-space collector, showing two time steps, prior
  11635. to garbage collection (on the top) and after garbage collection (on
  11636. the bottom). In a two-space collector, the heap is divided into two
  11637. parts named the FromSpace\index{subject}{FromSpace} and the
  11638. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11639. FromSpace until there is not enough room for the next allocation
  11640. request. At that point, the garbage collector goes to work to make
  11641. room for the next allocation.
  11642. A copying collector makes more room by copying all the live objects
  11643. from the FromSpace into the ToSpace and then performs a sleight of
  11644. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11645. as the new ToSpace. In the example shown in
  11646. figure~\ref{fig:copying-collector}, the root set consists of three
  11647. pointers, one in a register and two on the stack. All the live
  11648. objects have been copied to the ToSpace (the right-hand side of
  11649. figure~\ref{fig:copying-collector}) in a way that preserves the
  11650. pointer relationships. For example, the pointer in the register still
  11651. points to a tuple that in turn points to two other tuples. There are
  11652. four tuples that are not reachable from the root set and therefore do
  11653. not get copied into the ToSpace.
  11654. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11655. created by a well-typed program in \LangVec{} because it contains a
  11656. cycle. However, creating cycles will be possible once we get to
  11657. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11658. to deal with cycles to begin with, so we will not need to revisit this
  11659. issue.
  11660. \begin{figure}[tbp]
  11661. \centering
  11662. \begin{tcolorbox}[colback=white]
  11663. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11664. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11665. \\[5ex]
  11666. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11667. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11668. \end{tcolorbox}
  11669. \caption{A copying collector in action.}
  11670. \label{fig:copying-collector}
  11671. \end{figure}
  11672. \subsection{Graph Copying via Cheney's Algorithm}
  11673. \label{sec:cheney}
  11674. \index{subject}{Cheney's algorithm}
  11675. Let us take a closer look at the copying of the live objects. The
  11676. allocated\index{subject}{allocate} objects and pointers can be viewed
  11677. as a graph, and we need to copy the part of the graph that is
  11678. reachable from the root set. To make sure that we copy all the
  11679. reachable vertices in the graph, we need an exhaustive graph traversal
  11680. algorithm, such as depth-first search or breadth-first
  11681. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11682. take into account the possibility of cycles by marking which vertices
  11683. have already been visited, so to ensure termination of the
  11684. algorithm. These search algorithms also use a data structure such as a
  11685. stack or queue as a to-do list to keep track of the vertices that need
  11686. to be visited. We use breadth-first search and a trick due to
  11687. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11688. copying tuples into the ToSpace.
  11689. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11690. copy progresses. The queue is represented by a chunk of contiguous
  11691. memory at the beginning of the ToSpace, using two pointers to track
  11692. the front and the back of the queue, called the \emph{free pointer}
  11693. and the \emph{scan pointer}, respectively. The algorithm starts by
  11694. copying all tuples that are immediately reachable from the root set
  11695. into the ToSpace to form the initial queue. When we copy a tuple, we
  11696. mark the old tuple to indicate that it has been visited. We discuss
  11697. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11698. that any pointers inside the copied tuples in the queue still point
  11699. back to the FromSpace. Once the initial queue has been created, the
  11700. algorithm enters a loop in which it repeatedly processes the tuple at
  11701. the front of the queue and pops it off the queue. To process a tuple,
  11702. the algorithm copies all the objects that are directly reachable from it
  11703. to the ToSpace, placing them at the back of the queue. The algorithm
  11704. then updates the pointers in the popped tuple so that they point to the
  11705. newly copied objects.
  11706. \begin{figure}[tbp]
  11707. \centering
  11708. \begin{tcolorbox}[colback=white]
  11709. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11710. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11711. \end{tcolorbox}
  11712. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11713. \label{fig:cheney}
  11714. \end{figure}
  11715. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11716. tuple whose second element is $42$ to the back of the queue. The other
  11717. pointer goes to a tuple that has already been copied, so we do not
  11718. need to copy it again, but we do need to update the pointer to the new
  11719. location. This can be accomplished by storing a \emph{forwarding
  11720. pointer}\index{subject}{forwarding pointer} to the new location in the
  11721. old tuple, when we initially copied the tuple into the
  11722. ToSpace. This completes one step of the algorithm. The algorithm
  11723. continues in this way until the queue is empty; that is, when the scan
  11724. pointer catches up with the free pointer.
  11725. \subsection{Data Representation}
  11726. \label{sec:data-rep-gc}
  11727. The garbage collector places some requirements on the data
  11728. representations used by our compiler. First, the garbage collector
  11729. needs to distinguish between pointers and other kinds of data such as
  11730. integers. The following are three ways to accomplish this:
  11731. \begin{enumerate}
  11732. \item Attach a tag to each object that identifies what type of
  11733. object it is~\citep{McCarthy:1960dz}.
  11734. \item Store different types of objects in different
  11735. regions~\citep{Steele:1977ab}.
  11736. \item Use type information from the program to either (a) generate
  11737. type-specific code for collecting, or (b) generate tables that
  11738. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11739. \end{enumerate}
  11740. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11741. need to tag objects in any case, so option 1 is a natural choice for those
  11742. languages. However, \LangVec{} is a statically typed language, so it
  11743. would be unfortunate to require tags on every object, especially small
  11744. and pervasive objects like integers and Booleans. Option 3 is the
  11745. best-performing choice for statically typed languages, but it comes with
  11746. a relatively high implementation complexity. To keep this chapter
  11747. within a reasonable scope of complexity, we recommend a combination of options
  11748. 1 and 2, using separate strategies for the stack and the heap.
  11749. Regarding the stack, we recommend using a separate stack for pointers,
  11750. which we call the \emph{root stack}\index{subject}{root stack}
  11751. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11752. That is, when a local variable needs to be spilled and is of type
  11753. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11754. root stack instead of putting it on the procedure call
  11755. stack. Furthermore, we always spill tuple-typed variables if they are
  11756. live during a call to the collector, thereby ensuring that no pointers
  11757. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11758. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11759. contrasts it with the data layout using a root stack. The root stack
  11760. contains the two pointers from the regular stack and also the pointer
  11761. in the second register.
  11762. \begin{figure}[tbp]
  11763. \centering
  11764. \begin{tcolorbox}[colback=white]
  11765. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11766. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11767. \end{tcolorbox}
  11768. \caption{Maintaining a root stack to facilitate garbage collection.}
  11769. \label{fig:shadow-stack}
  11770. \end{figure}
  11771. The problem of distinguishing between pointers and other kinds of data
  11772. also arises inside each tuple on the heap. We solve this problem by
  11773. attaching a tag, an extra 64 bits, to each
  11774. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11775. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11776. Note that we have drawn the bits in a big-endian way, from right to left,
  11777. with bit location 0 (the least significant bit) on the far right,
  11778. which corresponds to the direction of the x86 shifting instructions
  11779. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11780. is dedicated to specifying which elements of the tuple are pointers,
  11781. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11782. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11783. data. The pointer mask starts at bit location 7. We limit tuples to a
  11784. maximum size of fifty elements, so we need 50 bits for the pointer
  11785. mask.%
  11786. %
  11787. \footnote{A production-quality compiler would handle
  11788. arbitrarily sized tuples and use a more complex approach.}
  11789. %
  11790. The tag also contains two other pieces of information. The length of
  11791. the tuple (number of elements) is stored in bits at locations 1 through
  11792. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11793. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11794. has not yet been copied. If the bit has value 0, then the entire tag
  11795. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11796. zero in any case, because our tuples are 8-byte aligned.)
  11797. \begin{figure}[tbp]
  11798. \centering
  11799. \begin{tcolorbox}[colback=white]
  11800. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11801. \end{tcolorbox}
  11802. \caption{Representation of tuples in the heap.}
  11803. \label{fig:tuple-rep}
  11804. \end{figure}
  11805. \subsection{Implementation of the Garbage Collector}
  11806. \label{sec:organize-gz}
  11807. \index{subject}{prelude}
  11808. An implementation of the copying collector is provided in the
  11809. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11810. interface to the garbage collector that is used by the compiler. The
  11811. \code{initialize} function creates the FromSpace, ToSpace, and root
  11812. stack and should be called in the prelude of the \code{main}
  11813. function. The arguments of \code{initialize} are the root stack size
  11814. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11815. good choice for both. The \code{initialize} function puts the address
  11816. of the beginning of the FromSpace into the global variable
  11817. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11818. the address that is one past the last element of the FromSpace. We use
  11819. half-open intervals to represent chunks of
  11820. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11821. points to the first element of the root stack.
  11822. As long as there is room left in the FromSpace, your generated code
  11823. can allocate\index{subject}{allocate} tuples simply by moving the
  11824. \code{free\_ptr} forward.
  11825. %
  11826. The amount of room left in the FromSpace is the difference between the
  11827. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11828. function should be called when there is not enough room left in the
  11829. FromSpace for the next allocation. The \code{collect} function takes
  11830. a pointer to the current top of the root stack (one past the last item
  11831. that was pushed) and the number of bytes that need to be
  11832. allocated. The \code{collect} function performs the copying collection
  11833. and leaves the heap in a state such that there is enough room for the
  11834. next allocation.
  11835. \begin{figure}[tbp]
  11836. \begin{tcolorbox}[colback=white]
  11837. \begin{lstlisting}
  11838. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11839. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11840. int64_t* free_ptr;
  11841. int64_t* fromspace_begin;
  11842. int64_t* fromspace_end;
  11843. int64_t** rootstack_begin;
  11844. \end{lstlisting}
  11845. \end{tcolorbox}
  11846. \caption{The compiler's interface to the garbage collector.}
  11847. \label{fig:gc-header}
  11848. \end{figure}
  11849. %% \begin{exercise}
  11850. %% In the file \code{runtime.c} you will find the implementation of
  11851. %% \code{initialize} and a partial implementation of \code{collect}.
  11852. %% The \code{collect} function calls another function, \code{cheney},
  11853. %% to perform the actual copy, and that function is left to the reader
  11854. %% to implement. The following is the prototype for \code{cheney}.
  11855. %% \begin{lstlisting}
  11856. %% static void cheney(int64_t** rootstack_ptr);
  11857. %% \end{lstlisting}
  11858. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11859. %% rootstack (which is an array of pointers). The \code{cheney} function
  11860. %% also communicates with \code{collect} through the global
  11861. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11862. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11863. %% the ToSpace:
  11864. %% \begin{lstlisting}
  11865. %% static int64_t* tospace_begin;
  11866. %% static int64_t* tospace_end;
  11867. %% \end{lstlisting}
  11868. %% The job of the \code{cheney} function is to copy all the live
  11869. %% objects (reachable from the root stack) into the ToSpace, update
  11870. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11871. %% update the root stack so that it points to the objects in the
  11872. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11873. %% and ToSpace.
  11874. %% \end{exercise}
  11875. The introduction of garbage collection has a nontrivial impact on our
  11876. compiler passes. We introduce a new compiler pass named
  11877. \code{expose\_allocation} that elaborates the code for allocating
  11878. tuples. We also make significant changes to
  11879. \code{select\_instructions}, \code{build\_interference},
  11880. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11881. make minor changes in several more passes.
  11882. The following program serves as our running example. It creates
  11883. two tuples, one nested inside the other. Both tuples have length
  11884. one. The program accesses the element in the inner tuple.
  11885. % tests/vectors_test_17.rkt
  11886. {\if\edition\racketEd
  11887. \begin{lstlisting}
  11888. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11889. \end{lstlisting}
  11890. \fi}
  11891. % tests/tuple/get_get.py
  11892. {\if\edition\pythonEd\pythonColor
  11893. \begin{lstlisting}
  11894. v1 = (42,)
  11895. v2 = (v1,)
  11896. print(v2[0][0])
  11897. \end{lstlisting}
  11898. \fi}
  11899. %% {\if\edition\racketEd
  11900. %% \section{Shrink}
  11901. %% \label{sec:shrink-Lvec}
  11902. %% Recall that the \code{shrink} pass translates the primitives operators
  11903. %% into a smaller set of primitives.
  11904. %% %
  11905. %% This pass comes after type checking, and the type checker adds a
  11906. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11907. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11908. %% \fi}
  11909. \section{Expose Allocation}
  11910. \label{sec:expose-allocation}
  11911. The pass \code{expose\_allocation} lowers tuple creation into making a
  11912. conditional call to the collector followed by allocating the
  11913. appropriate amount of memory and initializing it. We choose to place
  11914. the \code{expose\_allocation} pass before
  11915. \code{remove\_complex\_operands} because it generates code that
  11916. contains complex operands. However, with some care it can also be
  11917. placed before \code{remove\_complex\_operands} which would simplify
  11918. tuple creation by removing the need to assign the initializing
  11919. expressions to temporary variables (see below).
  11920. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11921. that replaces tuple creation with new lower-level forms that we use in the
  11922. translation of tuple creation.
  11923. %
  11924. {\if\edition\racketEd
  11925. \[
  11926. \begin{array}{lcl}
  11927. \Exp &::=& (\key{collect} \,\itm{int})
  11928. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11929. \MID (\key{global-value} \,\itm{name})
  11930. \end{array}
  11931. \]
  11932. \fi}
  11933. {\if\edition\pythonEd\pythonColor
  11934. \[
  11935. \begin{array}{lcl}
  11936. \Exp &::=& \key{collect}(\itm{int})
  11937. \MID \key{allocate}(\itm{int},\itm{type})
  11938. \MID \key{global\_value}(\itm{name}) \\
  11939. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11940. \end{array}
  11941. \]
  11942. \fi}
  11943. %
  11944. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  11945. there be $n$ bytes ready to be allocated. During instruction
  11946. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  11947. form will become a call to the \code{collect} function in
  11948. \code{runtime.c}.
  11949. %
  11950. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11951. space at the front for the 64-bit tag), but the elements are not
  11952. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11953. of the tuple:
  11954. %
  11955. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11956. %
  11957. where $\Type_i$ is the type of the $i$th element.
  11958. %
  11959. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11960. variable, such as \code{free\_ptr}.
  11961. \racket{
  11962. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11963. can be obtained by running the
  11964. \code{type-check-Lvec-has-type} type checker immediately before the
  11965. \code{expose\_allocation} pass. This version of the type checker
  11966. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11967. around each tuple creation. The concrete syntax
  11968. for \code{HasType} is \code{has-type}.}
  11969. The following shows the transformation of tuple creation into (1) a
  11970. sequence of temporary variable bindings for the initializing
  11971. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11972. \code{allocate}, and (4) the initialization of the tuple. The
  11973. \itm{len} placeholder refers to the length of the tuple, and
  11974. \itm{bytes} is the total number of bytes that need to be allocated for
  11975. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11976. %
  11977. \python{The \itm{type} needed for the second argument of the
  11978. \code{allocate} form can be obtained from the \code{has\_type} field
  11979. of the tuple AST node, which is stored there by running the type
  11980. checker for \LangVec{} immediately before this pass.}
  11981. %
  11982. \begin{center}
  11983. \begin{minipage}{\textwidth}
  11984. {\if\edition\racketEd
  11985. \begin{lstlisting}
  11986. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11987. |$\Longrightarrow$|
  11988. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11989. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11990. (global-value fromspace_end))
  11991. (void)
  11992. (collect |\itm{bytes}|))])
  11993. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11994. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11995. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11996. |$v$|) ... )))) ...)
  11997. \end{lstlisting}
  11998. \fi}
  11999. {\if\edition\pythonEd\pythonColor
  12000. \begin{lstlisting}
  12001. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12002. |$\Longrightarrow$|
  12003. begin:
  12004. |$x_0$| = |$e_0$|
  12005. |$\vdots$|
  12006. |$x_{n-1}$| = |$e_{n-1}$|
  12007. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12008. 0
  12009. else:
  12010. collect(|\itm{bytes}|)
  12011. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12012. |$v$|[0] = |$x_0$|
  12013. |$\vdots$|
  12014. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12015. |$v$|
  12016. \end{lstlisting}
  12017. \fi}
  12018. \end{minipage}
  12019. \end{center}
  12020. %
  12021. \noindent The sequencing of the initializing expressions
  12022. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12023. they may trigger garbage collection and we cannot have an allocated
  12024. but uninitialized tuple on the heap during a collection.
  12025. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12026. \code{expose\_allocation} pass on our running example.
  12027. \begin{figure}[tbp]
  12028. \begin{tcolorbox}[colback=white]
  12029. % tests/s2_17.rkt
  12030. {\if\edition\racketEd
  12031. \begin{lstlisting}
  12032. (vector-ref
  12033. (vector-ref
  12034. (let ([vecinit6
  12035. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12036. (global-value fromspace_end))
  12037. (void)
  12038. (collect 16))])
  12039. (let ([alloc2 (allocate 1 (Vector Integer))])
  12040. (let ([_3 (vector-set! alloc2 0 42)])
  12041. alloc2)))])
  12042. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12043. (global-value fromspace_end))
  12044. (void)
  12045. (collect 16))])
  12046. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12047. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12048. alloc5))))
  12049. 0)
  12050. 0)
  12051. \end{lstlisting}
  12052. \fi}
  12053. {\if\edition\pythonEd\pythonColor
  12054. \begin{lstlisting}
  12055. v1 = begin:
  12056. init.514 = 42
  12057. if (free_ptr + 16) < fromspace_end:
  12058. else:
  12059. collect(16)
  12060. alloc.513 = allocate(1,tuple[int])
  12061. alloc.513[0] = init.514
  12062. alloc.513
  12063. v2 = begin:
  12064. init.516 = v1
  12065. if (free_ptr + 16) < fromspace_end:
  12066. else:
  12067. collect(16)
  12068. alloc.515 = allocate(1,tuple[tuple[int]])
  12069. alloc.515[0] = init.516
  12070. alloc.515
  12071. print(v2[0][0])
  12072. \end{lstlisting}
  12073. \fi}
  12074. \end{tcolorbox}
  12075. \caption{Output of the \code{expose\_allocation} pass.}
  12076. \label{fig:expose-alloc-output}
  12077. \end{figure}
  12078. \section{Remove Complex Operands}
  12079. \label{sec:remove-complex-opera-Lvec}
  12080. {\if\edition\racketEd
  12081. %
  12082. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12083. should be treated as complex operands.
  12084. %
  12085. \fi}
  12086. %
  12087. {\if\edition\pythonEd\pythonColor
  12088. %
  12089. The expressions \code{allocate}, \code{begin},
  12090. and tuple access should be treated as complex operands. The
  12091. subexpressions of tuple access must be atomic.
  12092. The \code{global\_value} AST node is atomic.
  12093. %
  12094. \fi}
  12095. %% A new case for
  12096. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12097. %% handled carefully to prevent the \code{Prim} node from being separated
  12098. %% from its enclosing \code{HasType}.
  12099. Figure~\ref{fig:Lvec-anf-syntax}
  12100. shows the grammar for the output language \LangAllocANF{} of this
  12101. pass, which is \LangAlloc{} in monadic normal form.
  12102. \newcommand{\LtupMonadASTRacket}{
  12103. \begin{array}{rcl}
  12104. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12105. \MID \GLOBALVALUE{\Var}
  12106. \end{array}
  12107. }
  12108. \newcommand{\LtupMonadASTPython}{
  12109. \begin{array}{rcl}
  12110. \Atm &::=& \GLOBALVALUE{\Var} \\
  12111. \Exp &::=& \GET{\Atm}{\Atm}
  12112. \MID \LEN{\Atm}\\
  12113. &\MID& \ALLOCATE{\Int}{\Type}\\
  12114. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12115. &\MID& \COLLECT{\Int}
  12116. \end{array}
  12117. }
  12118. \begin{figure}[tp]
  12119. \centering
  12120. \begin{tcolorbox}[colback=white]
  12121. \small
  12122. {\if\edition\racketEd
  12123. \[
  12124. \begin{array}{l}
  12125. \gray{\LvarMonadASTRacket} \\ \hline
  12126. \gray{\LifMonadASTRacket} \\ \hline
  12127. \gray{\LwhileMonadASTRacket} \\ \hline
  12128. \LtupMonadASTRacket \\
  12129. \begin{array}{rcl}
  12130. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12131. \end{array}
  12132. \end{array}
  12133. \]
  12134. \fi}
  12135. {\if\edition\pythonEd\pythonColor
  12136. \[
  12137. \begin{array}{l}
  12138. \gray{\LvarMonadASTPython} \\ \hline
  12139. \gray{\LifMonadASTPython} \\ \hline
  12140. \gray{\LwhileMonadASTPython} \\ \hline
  12141. \LtupMonadASTPython \\
  12142. \begin{array}{rcl}
  12143. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12144. \end{array}
  12145. \end{array}
  12146. \]
  12147. \fi}
  12148. \end{tcolorbox}
  12149. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12150. \label{fig:Lvec-anf-syntax}
  12151. \end{figure}
  12152. \section{Explicate Control and the \LangCVec{} Language}
  12153. \label{sec:explicate-control-r3}
  12154. \newcommand{\CtupASTRacket}{
  12155. \begin{array}{lcl}
  12156. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12157. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12158. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12159. &\MID& \VECLEN{\Atm} \\
  12160. &\MID& \GLOBALVALUE{\Var} \\
  12161. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12162. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12163. \end{array}
  12164. }
  12165. \newcommand{\CtupASTPython}{
  12166. \begin{array}{lcl}
  12167. \Atm &::=& \GLOBALVALUE{\Var} \\
  12168. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12169. &\MID& \LEN{\Atm} \\
  12170. \Stmt &::=& \COLLECT{\Int}
  12171. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12172. \end{array}
  12173. }
  12174. \begin{figure}[tp]
  12175. \begin{tcolorbox}[colback=white]
  12176. \small
  12177. {\if\edition\racketEd
  12178. \[
  12179. \begin{array}{l}
  12180. \gray{\CvarASTRacket} \\ \hline
  12181. \gray{\CifASTRacket} \\ \hline
  12182. \gray{\CloopASTRacket} \\ \hline
  12183. \CtupASTRacket \\
  12184. \begin{array}{lcl}
  12185. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12186. \end{array}
  12187. \end{array}
  12188. \]
  12189. \fi}
  12190. {\if\edition\pythonEd\pythonColor
  12191. \[
  12192. \begin{array}{l}
  12193. \gray{\CifASTPython} \\ \hline
  12194. \CtupASTPython \\
  12195. \begin{array}{lcl}
  12196. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12197. \end{array}
  12198. \end{array}
  12199. \]
  12200. \fi}
  12201. \end{tcolorbox}
  12202. \caption{The abstract syntax of \LangCVec{}, extending
  12203. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12204. (figure~\ref{fig:c1-syntax})}.}
  12205. \label{fig:c2-syntax}
  12206. \end{figure}
  12207. The output of \code{explicate\_control} is a program in the
  12208. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12209. shows the definition of the abstract syntax.
  12210. %
  12211. %% \racket{(The concrete syntax is defined in
  12212. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12213. %
  12214. The new expressions of \LangCVec{} include \key{allocate},
  12215. %
  12216. \racket{\key{vector-ref}, and \key{vector-set!},}
  12217. %
  12218. \python{accessing tuple elements,}
  12219. %
  12220. and \key{global\_value}.
  12221. %
  12222. \python{\LangCVec{} also includes the \code{collect} statement and
  12223. assignment to a tuple element.}
  12224. %
  12225. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12226. %
  12227. The \code{explicate\_control} pass can treat these new forms much like
  12228. the other forms that we've already encountered. The output of the
  12229. \code{explicate\_control} pass on the running example is shown on the
  12230. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12231. section.
  12232. \section{Select Instructions and the \LangXGlobal{} Language}
  12233. \label{sec:select-instructions-gc}
  12234. \index{subject}{select instructions}
  12235. %% void (rep as zero)
  12236. %% allocate
  12237. %% collect (callq collect)
  12238. %% vector-ref
  12239. %% vector-set!
  12240. %% vector-length
  12241. %% global (postpone)
  12242. In this pass we generate x86 code for most of the new operations that
  12243. are needed to compile tuples, including \code{Allocate},
  12244. \code{Collect}, accessing tuple elements, and the \code{Is}
  12245. comparison.
  12246. %
  12247. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12248. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12249. \ref{fig:x86-2}). \index{subject}{x86}
  12250. The tuple read and write forms translate into \code{movq}
  12251. instructions. (The $+1$ in the offset serves to move past the tag at the
  12252. beginning of the tuple representation.)
  12253. %
  12254. \begin{center}
  12255. \begin{minipage}{\textwidth}
  12256. {\if\edition\racketEd
  12257. \begin{lstlisting}
  12258. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12259. |$\Longrightarrow$|
  12260. movq |$\itm{tup}'$|, %r11
  12261. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12262. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12263. |$\Longrightarrow$|
  12264. movq |$\itm{tup}'$|, %r11
  12265. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12266. movq $0, |$\itm{lhs'}$|
  12267. \end{lstlisting}
  12268. \fi}
  12269. {\if\edition\pythonEd\pythonColor
  12270. \begin{lstlisting}
  12271. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12272. |$\Longrightarrow$|
  12273. movq |$\itm{tup}'$|, %r11
  12274. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12275. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12276. |$\Longrightarrow$|
  12277. movq |$\itm{tup}'$|, %r11
  12278. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12279. \end{lstlisting}
  12280. \fi}
  12281. \end{minipage}
  12282. \end{center}
  12283. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12284. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12285. are obtained by translating from \LangCVec{} to x86.
  12286. %
  12287. The move of $\itm{tup}'$ to
  12288. register \code{r11} ensures that the offset expression
  12289. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12290. removing \code{r11} from consideration by the register allocator.
  12291. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12292. \code{rax}. Then the generated code for tuple assignment would be
  12293. \begin{lstlisting}
  12294. movq |$\itm{tup}'$|, %rax
  12295. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12296. \end{lstlisting}
  12297. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12298. \code{patch\_instructions} would insert a move through \code{rax}
  12299. as follows:
  12300. \begin{lstlisting}
  12301. movq |$\itm{tup}'$|, %rax
  12302. movq |$\itm{rhs}'$|, %rax
  12303. movq %rax, |$8(n+1)$|(%rax)
  12304. \end{lstlisting}
  12305. However, this sequence of instructions does not work because we're
  12306. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12307. $\itm{rhs}'$) at the same time!
  12308. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12309. be translated into a sequence of instructions that read the tag of the
  12310. tuple and extract the 6 bits that represent the tuple length, which
  12311. are the bits starting at index 1 and going up to and including bit 6.
  12312. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12313. (shift right) can be used to accomplish this.
  12314. We compile the \code{allocate} form to operations on the
  12315. \code{free\_ptr}, as shown next. This approach is called
  12316. \emph{inline allocation} because it implements allocation without a
  12317. function call by simply incrementing the allocation pointer. It is much
  12318. more efficient than calling a function for each allocation. The
  12319. address in the \code{free\_ptr} is the next free address in the
  12320. FromSpace, so we copy it into \code{r11} and then move it forward by
  12321. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12322. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12323. the tag. We then initialize the \itm{tag} and finally copy the
  12324. address in \code{r11} to the left-hand side. Refer to
  12325. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12326. %
  12327. \racket{We recommend using the Racket operations
  12328. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12329. during compilation.}
  12330. %
  12331. \python{We recommend using the bitwise-or operator \code{|} and the
  12332. shift-left operator \code{<<} to compute the tag during
  12333. compilation.}
  12334. %
  12335. The type annotation in the \code{allocate} form is used to determine
  12336. the pointer mask region of the tag.
  12337. %
  12338. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12339. address of the \code{free\_ptr} global variable using a special
  12340. instruction-pointer-relative addressing mode of the x86-64 processor.
  12341. In particular, the assembler computes the distance $d$ between the
  12342. address of \code{free\_ptr} and where the \code{rip} would be at that
  12343. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12344. \code{$d$(\%rip)}, which at runtime will compute the address of
  12345. \code{free\_ptr}.
  12346. %
  12347. {\if\edition\racketEd
  12348. \begin{lstlisting}
  12349. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12350. |$\Longrightarrow$|
  12351. movq free_ptr(%rip), %r11
  12352. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12353. movq $|$\itm{tag}$|, 0(%r11)
  12354. movq %r11, |$\itm{lhs}'$|
  12355. \end{lstlisting}
  12356. \fi}
  12357. {\if\edition\pythonEd\pythonColor
  12358. \begin{lstlisting}
  12359. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12360. |$\Longrightarrow$|
  12361. movq free_ptr(%rip), %r11
  12362. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12363. movq $|$\itm{tag}$|, 0(%r11)
  12364. movq %r11, |$\itm{lhs}'$|
  12365. \end{lstlisting}
  12366. \fi}
  12367. %
  12368. The \code{collect} form is compiled to a call to the \code{collect}
  12369. function in the runtime. The arguments to \code{collect} are (1) the
  12370. top of the root stack, and (2) the number of bytes that need to be
  12371. allocated. We use another dedicated register, \code{r15}, to store
  12372. the pointer to the top of the root stack. Therefore \code{r15} is not
  12373. available for use by the register allocator.
  12374. %
  12375. {\if\edition\racketEd
  12376. \begin{lstlisting}
  12377. (collect |$\itm{bytes}$|)
  12378. |$\Longrightarrow$|
  12379. movq %r15, %rdi
  12380. movq $|\itm{bytes}|, %rsi
  12381. callq collect
  12382. \end{lstlisting}
  12383. \fi}
  12384. {\if\edition\pythonEd\pythonColor
  12385. \begin{lstlisting}
  12386. collect(|$\itm{bytes}$|)
  12387. |$\Longrightarrow$|
  12388. movq %r15, %rdi
  12389. movq $|\itm{bytes}|, %rsi
  12390. callq collect
  12391. \end{lstlisting}
  12392. \fi}
  12393. {\if\edition\pythonEd\pythonColor
  12394. The \code{is} comparison is compiled similarly to the other comparison
  12395. operators, using the \code{cmpq} instruction. Because the value of a
  12396. tuple is its address, we can translate \code{is} into a simple check
  12397. for equality using the \code{e} condition code. \\
  12398. \begin{tabular}{lll}
  12399. \begin{minipage}{0.4\textwidth}
  12400. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12401. \end{minipage}
  12402. &
  12403. $\Rightarrow$
  12404. &
  12405. \begin{minipage}{0.4\textwidth}
  12406. \begin{lstlisting}
  12407. cmpq |$\Arg_2$|, |$\Arg_1$|
  12408. sete %al
  12409. movzbq %al, |$\Var$|
  12410. \end{lstlisting}
  12411. \end{minipage}
  12412. \end{tabular}
  12413. \fi}
  12414. \newcommand{\GrammarXGlobal}{
  12415. \begin{array}{lcl}
  12416. \Arg &::=& \itm{label} \key{(\%rip)}
  12417. \end{array}
  12418. }
  12419. \newcommand{\ASTXGlobalRacket}{
  12420. \begin{array}{lcl}
  12421. \Arg &::=& \GLOBAL{\itm{label}}
  12422. \end{array}
  12423. }
  12424. \begin{figure}[tp]
  12425. \begin{tcolorbox}[colback=white]
  12426. \[
  12427. \begin{array}{l}
  12428. \gray{\GrammarXInt} \\ \hline
  12429. \gray{\GrammarXIf} \\ \hline
  12430. \GrammarXGlobal \\
  12431. \begin{array}{lcl}
  12432. \LangXGlobalM{} &::= & \key{.globl main} \\
  12433. & & \key{main:} \; \Instr^{*}
  12434. \end{array}
  12435. \end{array}
  12436. \]
  12437. \end{tcolorbox}
  12438. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12439. \label{fig:x86-2-concrete}
  12440. \end{figure}
  12441. \begin{figure}[tp]
  12442. \begin{tcolorbox}[colback=white]
  12443. \small
  12444. {\if\edition\racketEd
  12445. \[
  12446. \begin{array}{l}
  12447. \gray{\ASTXIntRacket} \\ \hline
  12448. \gray{\ASTXIfRacket} \\ \hline
  12449. \ASTXGlobalRacket \\
  12450. \begin{array}{lcl}
  12451. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12452. \end{array}
  12453. \end{array}
  12454. \]
  12455. \fi}
  12456. {\if\edition\pythonEd\pythonColor
  12457. \[
  12458. \begin{array}{l}
  12459. \gray{\ASTXIntPython} \\ \hline
  12460. \gray{\ASTXIfPython} \\ \hline
  12461. \ASTXGlobalRacket \\
  12462. \begin{array}{lcl}
  12463. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12464. \end{array}
  12465. \end{array}
  12466. \]
  12467. \fi}
  12468. \end{tcolorbox}
  12469. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12470. \label{fig:x86-2}
  12471. \end{figure}
  12472. The definitions of the concrete and abstract syntax of the
  12473. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12474. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12475. of global variables.
  12476. %
  12477. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12478. \code{select\_instructions} pass on the running example.
  12479. \begin{figure}[tbp]
  12480. \centering
  12481. \begin{tcolorbox}[colback=white]
  12482. {\if\edition\racketEd
  12483. % tests/s2_17.rkt
  12484. \begin{tabular}{lll}
  12485. \begin{minipage}{0.5\textwidth}
  12486. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12487. start:
  12488. tmp9 = (global-value free_ptr);
  12489. tmp0 = (+ tmp9 16);
  12490. tmp1 = (global-value fromspace_end);
  12491. if (< tmp0 tmp1)
  12492. goto block0;
  12493. else
  12494. goto block1;
  12495. block0:
  12496. _4 = (void);
  12497. goto block9;
  12498. block1:
  12499. (collect 16)
  12500. goto block9;
  12501. block9:
  12502. alloc2 = (allocate 1 (Vector Integer));
  12503. _3 = (vector-set! alloc2 0 42);
  12504. vecinit6 = alloc2;
  12505. tmp2 = (global-value free_ptr);
  12506. tmp3 = (+ tmp2 16);
  12507. tmp4 = (global-value fromspace_end);
  12508. if (< tmp3 tmp4)
  12509. goto block7;
  12510. else
  12511. goto block8;
  12512. block7:
  12513. _8 = (void);
  12514. goto block6;
  12515. block8:
  12516. (collect 16)
  12517. goto block6;
  12518. block6:
  12519. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12520. _7 = (vector-set! alloc5 0 vecinit6);
  12521. tmp5 = (vector-ref alloc5 0);
  12522. return (vector-ref tmp5 0);
  12523. \end{lstlisting}
  12524. \end{minipage}
  12525. &$\Rightarrow$&
  12526. \begin{minipage}{0.4\textwidth}
  12527. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12528. start:
  12529. movq free_ptr(%rip), tmp9
  12530. movq tmp9, tmp0
  12531. addq $16, tmp0
  12532. movq fromspace_end(%rip), tmp1
  12533. cmpq tmp1, tmp0
  12534. jl block0
  12535. jmp block1
  12536. block0:
  12537. movq $0, _4
  12538. jmp block9
  12539. block1:
  12540. movq %r15, %rdi
  12541. movq $16, %rsi
  12542. callq collect
  12543. jmp block9
  12544. block9:
  12545. movq free_ptr(%rip), %r11
  12546. addq $16, free_ptr(%rip)
  12547. movq $3, 0(%r11)
  12548. movq %r11, alloc2
  12549. movq alloc2, %r11
  12550. movq $42, 8(%r11)
  12551. movq $0, _3
  12552. movq alloc2, vecinit6
  12553. movq free_ptr(%rip), tmp2
  12554. movq tmp2, tmp3
  12555. addq $16, tmp3
  12556. movq fromspace_end(%rip), tmp4
  12557. cmpq tmp4, tmp3
  12558. jl block7
  12559. jmp block8
  12560. block7:
  12561. movq $0, _8
  12562. jmp block6
  12563. block8:
  12564. movq %r15, %rdi
  12565. movq $16, %rsi
  12566. callq collect
  12567. jmp block6
  12568. block6:
  12569. movq free_ptr(%rip), %r11
  12570. addq $16, free_ptr(%rip)
  12571. movq $131, 0(%r11)
  12572. movq %r11, alloc5
  12573. movq alloc5, %r11
  12574. movq vecinit6, 8(%r11)
  12575. movq $0, _7
  12576. movq alloc5, %r11
  12577. movq 8(%r11), tmp5
  12578. movq tmp5, %r11
  12579. movq 8(%r11), %rax
  12580. jmp conclusion
  12581. \end{lstlisting}
  12582. \end{minipage}
  12583. \end{tabular}
  12584. \fi}
  12585. {\if\edition\pythonEd
  12586. % tests/tuple/get_get.py
  12587. \begin{tabular}{lll}
  12588. \begin{minipage}{0.5\textwidth}
  12589. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12590. start:
  12591. init.514 = 42
  12592. tmp.517 = free_ptr
  12593. tmp.518 = (tmp.517 + 16)
  12594. tmp.519 = fromspace_end
  12595. if tmp.518 < tmp.519:
  12596. goto block.529
  12597. else:
  12598. goto block.530
  12599. block.529:
  12600. goto block.528
  12601. block.530:
  12602. collect(16)
  12603. goto block.528
  12604. block.528:
  12605. alloc.513 = allocate(1,tuple[int])
  12606. alloc.513:tuple[int][0] = init.514
  12607. v1 = alloc.513
  12608. init.516 = v1
  12609. tmp.520 = free_ptr
  12610. tmp.521 = (tmp.520 + 16)
  12611. tmp.522 = fromspace_end
  12612. if tmp.521 < tmp.522:
  12613. goto block.526
  12614. else:
  12615. goto block.527
  12616. block.526:
  12617. goto block.525
  12618. block.527:
  12619. collect(16)
  12620. goto block.525
  12621. block.525:
  12622. alloc.515 = allocate(1,tuple[tuple[int]])
  12623. alloc.515:tuple[tuple[int]][0] = init.516
  12624. v2 = alloc.515
  12625. tmp.523 = v2[0]
  12626. tmp.524 = tmp.523[0]
  12627. print(tmp.524)
  12628. return 0
  12629. \end{lstlisting}
  12630. \end{minipage}
  12631. &$\Rightarrow$&
  12632. \begin{minipage}{0.4\textwidth}
  12633. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12634. start:
  12635. movq $42, init.514
  12636. movq free_ptr(%rip), tmp.517
  12637. movq tmp.517, tmp.518
  12638. addq $16, tmp.518
  12639. movq fromspace_end(%rip), tmp.519
  12640. cmpq tmp.519, tmp.518
  12641. jl block.529
  12642. jmp block.530
  12643. block.529:
  12644. jmp block.528
  12645. block.530:
  12646. movq %r15, %rdi
  12647. movq $16, %rsi
  12648. callq collect
  12649. jmp block.528
  12650. block.528:
  12651. movq free_ptr(%rip), %r11
  12652. addq $16, free_ptr(%rip)
  12653. movq $3, 0(%r11)
  12654. movq %r11, alloc.513
  12655. movq alloc.513, %r11
  12656. movq init.514, 8(%r11)
  12657. movq alloc.513, v1
  12658. movq v1, init.516
  12659. movq free_ptr(%rip), tmp.520
  12660. movq tmp.520, tmp.521
  12661. addq $16, tmp.521
  12662. movq fromspace_end(%rip), tmp.522
  12663. cmpq tmp.522, tmp.521
  12664. jl block.526
  12665. jmp block.527
  12666. block.526:
  12667. jmp block.525
  12668. block.527:
  12669. movq %r15, %rdi
  12670. movq $16, %rsi
  12671. callq collect
  12672. jmp block.525
  12673. block.525:
  12674. movq free_ptr(%rip), %r11
  12675. addq $16, free_ptr(%rip)
  12676. movq $131, 0(%r11)
  12677. movq %r11, alloc.515
  12678. movq alloc.515, %r11
  12679. movq init.516, 8(%r11)
  12680. movq alloc.515, v2
  12681. movq v2, %r11
  12682. movq 8(%r11), %r11
  12683. movq %r11, tmp.523
  12684. movq tmp.523, %r11
  12685. movq 8(%r11), %r11
  12686. movq %r11, tmp.524
  12687. movq tmp.524, %rdi
  12688. callq print_int
  12689. movq $0, %rax
  12690. jmp conclusion
  12691. \end{lstlisting}
  12692. \end{minipage}
  12693. \end{tabular}
  12694. \fi}
  12695. \end{tcolorbox}
  12696. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12697. \code{select\_instructions} (\emph{right}) on the running example.}
  12698. \label{fig:select-instr-output-gc}
  12699. \end{figure}
  12700. \clearpage
  12701. \section{Register Allocation}
  12702. \label{sec:reg-alloc-gc}
  12703. \index{subject}{register allocation}
  12704. As discussed previously in this chapter, the garbage collector needs to
  12705. access all the pointers in the root set, that is, all variables that
  12706. are tuples. It will be the responsibility of the register allocator
  12707. to make sure that
  12708. \begin{enumerate}
  12709. \item the root stack is used for spilling tuple-typed variables, and
  12710. \item if a tuple-typed variable is live during a call to the
  12711. collector, it must be spilled to ensure that it is visible to the
  12712. collector.
  12713. \end{enumerate}
  12714. The latter responsibility can be handled during construction of the
  12715. interference graph, by adding interference edges between the call-live
  12716. tuple-typed variables and all the callee-saved registers. (They
  12717. already interfere with the caller-saved registers.)
  12718. %
  12719. \racket{The type information for variables is in the \code{Program}
  12720. form, so we recommend adding another parameter to the
  12721. \code{build\_interference} function to communicate this alist.}
  12722. %
  12723. \python{The type information for variables is generated by the type
  12724. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12725. the \code{CProgram} AST mode. You'll need to propagate that
  12726. information so that it is available in this pass.}
  12727. The spilling of tuple-typed variables to the root stack can be handled
  12728. after graph coloring, in choosing how to assign the colors
  12729. (integers) to registers and stack locations. The
  12730. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12731. changes to also record the number of spills to the root stack.
  12732. % build-interference
  12733. %
  12734. % callq
  12735. % extra parameter for var->type assoc. list
  12736. % update 'program' and 'if'
  12737. % allocate-registers
  12738. % allocate spilled vectors to the rootstack
  12739. % don't change color-graph
  12740. % TODO:
  12741. %\section{Patch Instructions}
  12742. %[mention that global variables are memory references]
  12743. \section{Generate Prelude and Conclusion}
  12744. \label{sec:print-x86-gc}
  12745. \label{sec:prelude-conclusion-x86-gc}
  12746. \index{subject}{prelude}\index{subject}{conclusion}
  12747. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12748. \code{prelude\_and\_conclusion} pass on the running example. In the
  12749. prelude of the \code{main} function, we allocate space
  12750. on the root stack to make room for the spills of tuple-typed
  12751. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12752. taking care that the root stack grows up instead of down. For the
  12753. running example, there was just one spill, so we increment \code{r15}
  12754. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12755. One issue that deserves special care is that there may be a call to
  12756. \code{collect} prior to the initializing assignments for all the
  12757. variables in the root stack. We do not want the garbage collector to
  12758. mistakenly determine that some uninitialized variable is a pointer that
  12759. needs to be followed. Thus, we zero out all locations on the root
  12760. stack in the prelude of \code{main}. In
  12761. figure~\ref{fig:print-x86-output-gc}, the instruction
  12762. %
  12763. \lstinline{movq $0, 0(%r15)}
  12764. %
  12765. is sufficient to accomplish this task because there is only one spill.
  12766. In general, we have to clear as many words as there are spills of
  12767. tuple-typed variables. The garbage collector tests each root to see
  12768. if it is null prior to dereferencing it.
  12769. \begin{figure}[htbp]
  12770. \begin{tcolorbox}[colback=white]
  12771. {\if\edition\racketEd
  12772. \begin{minipage}[t]{0.5\textwidth}
  12773. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12774. .globl main
  12775. main:
  12776. pushq %rbp
  12777. movq %rsp, %rbp
  12778. subq $0, %rsp
  12779. movq $65536, %rdi
  12780. movq $65536, %rsi
  12781. callq initialize
  12782. movq rootstack_begin(%rip), %r15
  12783. movq $0, 0(%r15)
  12784. addq $8, %r15
  12785. jmp start
  12786. conclusion:
  12787. subq $8, %r15
  12788. addq $0, %rsp
  12789. popq %rbp
  12790. retq
  12791. \end{lstlisting}
  12792. \end{minipage}
  12793. \fi}
  12794. {\if\edition\pythonEd
  12795. \begin{minipage}[t]{0.5\textwidth}
  12796. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12797. .globl main
  12798. main:
  12799. pushq %rbp
  12800. movq %rsp, %rbp
  12801. pushq %rbx
  12802. subq $8, %rsp
  12803. movq $65536, %rdi
  12804. movq $16, %rsi
  12805. callq initialize
  12806. movq rootstack_begin(%rip), %r15
  12807. movq $0, 0(%r15)
  12808. addq $8, %r15
  12809. jmp start
  12810. conclusion:
  12811. subq $8, %r15
  12812. addq $8, %rsp
  12813. popq %rbx
  12814. popq %rbp
  12815. retq
  12816. \end{lstlisting}
  12817. \end{minipage}
  12818. \fi}
  12819. \end{tcolorbox}
  12820. \caption{The prelude and conclusion for the running example.}
  12821. \label{fig:print-x86-output-gc}
  12822. \end{figure}
  12823. \begin{figure}[tbp]
  12824. \begin{tcolorbox}[colback=white]
  12825. {\if\edition\racketEd
  12826. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12827. \node (Lvec) at (0,2) {\large \LangVec{}};
  12828. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12829. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12830. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12831. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12832. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12833. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12834. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12835. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12836. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12837. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12838. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12839. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12840. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12841. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12842. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12843. \path[->,bend left=15] (Lvec-4) edge [right] node
  12844. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12845. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12846. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12847. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12848. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12849. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12850. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12851. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12852. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12853. \end{tikzpicture}
  12854. \fi}
  12855. {\if\edition\pythonEd\pythonColor
  12856. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12857. \node (Lvec) at (0,2) {\large \LangVec{}};
  12858. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12859. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12860. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12861. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12862. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12863. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12864. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12865. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12866. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12867. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12868. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12869. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12870. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12871. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12872. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12873. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12874. \end{tikzpicture}
  12875. \fi}
  12876. \end{tcolorbox}
  12877. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12878. \label{fig:Lvec-passes}
  12879. \end{figure}
  12880. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12881. for the compilation of \LangVec{}.
  12882. \clearpage
  12883. {\if\edition\racketEd
  12884. \section{Challenge: Simple Structures}
  12885. \label{sec:simple-structures}
  12886. \index{subject}{struct}
  12887. \index{subject}{structure}
  12888. The language \LangStruct{} extends \LangVec{} with support for simple
  12889. structures. The definition of its concrete syntax is shown in
  12890. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12891. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12892. in Typed Racket is a user-defined data type that contains named fields
  12893. and that is heap allocated\index{subject}{heap allocated},
  12894. similarly to a vector. The following is an
  12895. example of a structure definition, in this case the definition of a
  12896. \code{point} type:
  12897. \begin{lstlisting}
  12898. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12899. \end{lstlisting}
  12900. \newcommand{\LstructGrammarRacket}{
  12901. \begin{array}{lcl}
  12902. \Type &::=& \Var \\
  12903. \Exp &::=& (\Var\;\Exp \ldots)\\
  12904. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12905. \end{array}
  12906. }
  12907. \newcommand{\LstructASTRacket}{
  12908. \begin{array}{lcl}
  12909. \Type &::=& \VAR{\Var} \\
  12910. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12911. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12912. \end{array}
  12913. }
  12914. \begin{figure}[tbp]
  12915. \centering
  12916. \begin{tcolorbox}[colback=white]
  12917. \[
  12918. \begin{array}{l}
  12919. \gray{\LintGrammarRacket{}} \\ \hline
  12920. \gray{\LvarGrammarRacket{}} \\ \hline
  12921. \gray{\LifGrammarRacket{}} \\ \hline
  12922. \gray{\LwhileGrammarRacket} \\ \hline
  12923. \gray{\LtupGrammarRacket} \\ \hline
  12924. \LstructGrammarRacket \\
  12925. \begin{array}{lcl}
  12926. \LangStruct{} &::=& \Def \ldots \; \Exp
  12927. \end{array}
  12928. \end{array}
  12929. \]
  12930. \end{tcolorbox}
  12931. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12932. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12933. \label{fig:Lstruct-concrete-syntax}
  12934. \end{figure}
  12935. \begin{figure}[tbp]
  12936. \centering
  12937. \begin{tcolorbox}[colback=white]
  12938. \small
  12939. \[
  12940. \begin{array}{l}
  12941. \gray{\LintASTRacket{}} \\ \hline
  12942. \gray{\LvarASTRacket{}} \\ \hline
  12943. \gray{\LifASTRacket{}} \\ \hline
  12944. \gray{\LwhileASTRacket} \\ \hline
  12945. \gray{\LtupASTRacket} \\ \hline
  12946. \LstructASTRacket \\
  12947. \begin{array}{lcl}
  12948. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12949. \end{array}
  12950. \end{array}
  12951. \]
  12952. \end{tcolorbox}
  12953. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12954. (figure~\ref{fig:Lvec-syntax}).}
  12955. \label{fig:Lstruct-syntax}
  12956. \end{figure}
  12957. An instance of a structure is created using function-call syntax, with
  12958. the name of the structure in the function position, as follows:
  12959. \begin{lstlisting}
  12960. (point 7 12)
  12961. \end{lstlisting}
  12962. Function-call syntax is also used to read a field of a structure. The
  12963. function name is formed by the structure name, a dash, and the field
  12964. name. The following example uses \code{point-x} and \code{point-y} to
  12965. access the \code{x} and \code{y} fields of two point instances:
  12966. \begin{center}
  12967. \begin{lstlisting}
  12968. (let ([pt1 (point 7 12)])
  12969. (let ([pt2 (point 4 3)])
  12970. (+ (- (point-x pt1) (point-x pt2))
  12971. (- (point-y pt1) (point-y pt2)))))
  12972. \end{lstlisting}
  12973. \end{center}
  12974. Similarly, to write to a field of a structure, use its set function,
  12975. whose name starts with \code{set-}, followed by the structure name,
  12976. then a dash, then the field name, and finally with an exclamation
  12977. mark. The following example uses \code{set-point-x!} to change the
  12978. \code{x} field from \code{7} to \code{42}:
  12979. \begin{center}
  12980. \begin{lstlisting}
  12981. (let ([pt (point 7 12)])
  12982. (let ([_ (set-point-x! pt 42)])
  12983. (point-x pt)))
  12984. \end{lstlisting}
  12985. \end{center}
  12986. \begin{exercise}\normalfont\normalsize
  12987. Create a type checker for \LangStruct{} by extending the type
  12988. checker for \LangVec{}. Extend your compiler with support for simple
  12989. structures, compiling \LangStruct{} to x86 assembly code. Create
  12990. five new test cases that use structures, and test your compiler.
  12991. \end{exercise}
  12992. % TODO: create an interpreter for L_struct
  12993. \clearpage
  12994. \fi}
  12995. \section{Challenge: Arrays}
  12996. \label{sec:arrays}
  12997. % TODO mention trapped-error
  12998. In this chapter we have studied tuples, that is, heterogeneous
  12999. sequences of elements whose length is determined at compile time. This
  13000. challenge is also about sequences, but this time the length is
  13001. determined at runtime and all the elements have the same type (they
  13002. are homogeneous). We use the traditional term \emph{array} for this
  13003. latter kind of sequence.
  13004. %
  13005. \racket{
  13006. The Racket language does not distinguish between tuples and arrays;
  13007. they are both represented by vectors. However, Typed Racket
  13008. distinguishes between tuples and arrays: the \code{Vector} type is for
  13009. tuples, and the \code{Vectorof} type is for arrays.}%
  13010. \python{Arrays correspond to the \code{list} type in the Python language.}
  13011. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13012. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13013. presents the definition of the abstract syntax, extending \LangVec{}
  13014. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13015. \racket{\code{make-vector} primitive operator for creating an array,
  13016. whose arguments are the length of the array and an initial value for
  13017. all the elements in the array.}%
  13018. \python{bracket notation for creating an array literal.}
  13019. \racket{The \code{vector-length},
  13020. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13021. for tuples become overloaded for use with arrays.}
  13022. \python{
  13023. The subscript operator becomes overloaded for use with arrays and tuples
  13024. and now may appear on the left-hand side of an assignment.
  13025. Note that the index of the subscript, when applied to an array, may be an
  13026. arbitrary expression and not exclusively a constant integer.
  13027. The \code{len} function is also applicable to arrays.
  13028. }
  13029. %
  13030. We include integer multiplication in \LangArray{} because it is
  13031. useful in many examples involving arrays such as computing the
  13032. inner product of two arrays (figure~\ref{fig:inner_product}).
  13033. \newcommand{\LarrayGrammarRacket}{
  13034. \begin{array}{lcl}
  13035. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13036. \Exp &::=& \CMUL{\Exp}{\Exp}
  13037. \MID \CMAKEVEC{\Exp}{\Exp}
  13038. \end{array}
  13039. }
  13040. \newcommand{\LarrayASTRacket}{
  13041. \begin{array}{lcl}
  13042. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13043. \Exp &::=& \MUL{\Exp}{\Exp}
  13044. \MID \MAKEVEC{\Exp}{\Exp}
  13045. \end{array}
  13046. }
  13047. \newcommand{\LarrayGrammarPython}{
  13048. \begin{array}{lcl}
  13049. \Type &::=& \key{list}\LS\Type\RS \\
  13050. \Exp &::=& \CMUL{\Exp}{\Exp}
  13051. \MID \CGET{\Exp}{\Exp}
  13052. \MID \LS \Exp \code{,} \ldots \RS \\
  13053. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13054. \end{array}
  13055. }
  13056. \newcommand{\LarrayASTPython}{
  13057. \begin{array}{lcl}
  13058. \Type &::=& \key{ListType}\LP\Type\RP \\
  13059. \Exp &::=& \MUL{\Exp}{\Exp}
  13060. \MID \GET{\Exp}{\Exp} \\
  13061. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13062. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13063. \end{array}
  13064. }
  13065. \begin{figure}[tp]
  13066. \centering
  13067. \begin{tcolorbox}[colback=white]
  13068. \small
  13069. {\if\edition\racketEd
  13070. \[
  13071. \begin{array}{l}
  13072. \gray{\LintGrammarRacket{}} \\ \hline
  13073. \gray{\LvarGrammarRacket{}} \\ \hline
  13074. \gray{\LifGrammarRacket{}} \\ \hline
  13075. \gray{\LwhileGrammarRacket} \\ \hline
  13076. \gray{\LtupGrammarRacket} \\ \hline
  13077. \LarrayGrammarRacket \\
  13078. \begin{array}{lcl}
  13079. \LangArray{} &::=& \Exp
  13080. \end{array}
  13081. \end{array}
  13082. \]
  13083. \fi}
  13084. {\if\edition\pythonEd\pythonColor
  13085. \[
  13086. \begin{array}{l}
  13087. \gray{\LintGrammarPython{}} \\ \hline
  13088. \gray{\LvarGrammarPython{}} \\ \hline
  13089. \gray{\LifGrammarPython{}} \\ \hline
  13090. \gray{\LwhileGrammarPython} \\ \hline
  13091. \gray{\LtupGrammarPython} \\ \hline
  13092. \LarrayGrammarPython \\
  13093. \begin{array}{rcl}
  13094. \LangArrayM{} &::=& \Stmt^{*}
  13095. \end{array}
  13096. \end{array}
  13097. \]
  13098. \fi}
  13099. \end{tcolorbox}
  13100. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13101. \label{fig:Lvecof-concrete-syntax}
  13102. \end{figure}
  13103. \begin{figure}[tp]
  13104. \centering
  13105. \begin{tcolorbox}[colback=white]
  13106. \small
  13107. {\if\edition\racketEd
  13108. \[
  13109. \begin{array}{l}
  13110. \gray{\LintASTRacket{}} \\ \hline
  13111. \gray{\LvarASTRacket{}} \\ \hline
  13112. \gray{\LifASTRacket{}} \\ \hline
  13113. \gray{\LwhileASTRacket} \\ \hline
  13114. \gray{\LtupASTRacket} \\ \hline
  13115. \LarrayASTRacket \\
  13116. \begin{array}{lcl}
  13117. \LangArray{} &::=& \Exp
  13118. \end{array}
  13119. \end{array}
  13120. \]
  13121. \fi}
  13122. {\if\edition\pythonEd\pythonColor
  13123. \[
  13124. \begin{array}{l}
  13125. \gray{\LintASTPython{}} \\ \hline
  13126. \gray{\LvarASTPython{}} \\ \hline
  13127. \gray{\LifASTPython{}} \\ \hline
  13128. \gray{\LwhileASTPython} \\ \hline
  13129. \gray{\LtupASTPython} \\ \hline
  13130. \LarrayASTPython \\
  13131. \begin{array}{rcl}
  13132. \LangArrayM{} &::=& \Stmt^{*}
  13133. \end{array}
  13134. \end{array}
  13135. \]
  13136. \fi}
  13137. \end{tcolorbox}
  13138. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13139. \label{fig:Lvecof-syntax}
  13140. \end{figure}
  13141. \begin{figure}[tp]
  13142. \begin{tcolorbox}[colback=white]
  13143. {\if\edition\racketEd
  13144. % TODO: remove the function from the following example, like the python version -Jeremy
  13145. \begin{lstlisting}
  13146. (let ([A (make-vector 2 2)])
  13147. (let ([B (make-vector 2 3)])
  13148. (let ([i 0])
  13149. (let ([prod 0])
  13150. (begin
  13151. (while (< i n)
  13152. (begin
  13153. (set! prod (+ prod (* (vector-ref A i)
  13154. (vector-ref B i))))
  13155. (set! i (+ i 1))))
  13156. prod)))))
  13157. \end{lstlisting}
  13158. \fi}
  13159. {\if\edition\pythonEd\pythonColor
  13160. \begin{lstlisting}
  13161. A = [2, 2]
  13162. B = [3, 3]
  13163. i = 0
  13164. prod = 0
  13165. while i != len(A):
  13166. prod = prod + A[i] * B[i]
  13167. i = i + 1
  13168. print(prod)
  13169. \end{lstlisting}
  13170. \fi}
  13171. \end{tcolorbox}
  13172. \caption{Example program that computes the inner product.}
  13173. \label{fig:inner_product}
  13174. \end{figure}
  13175. {\if\edition\racketEd
  13176. %
  13177. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13178. checker for \LangArray{}. The result type of
  13179. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13180. of the initializing expression. The length expression is required to
  13181. have type \code{Integer}. The type checking of the operators
  13182. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13183. updated to handle the situation in which the vector has type
  13184. \code{Vectorof}. In these cases we translate the operators to their
  13185. \code{vectorof} form so that later passes can easily distinguish
  13186. between operations on tuples versus arrays. We override the
  13187. \code{operator-types} method to provide the type signature for
  13188. multiplication: it takes two integers and returns an integer.
  13189. \fi}
  13190. %
  13191. {\if\edition\pythonEd\pythonColor
  13192. %
  13193. The type checker for \LangArray{} is defined in
  13194. figure~\ref{fig:type-check-Lvecof} and
  13195. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13196. is \code{list[T]}, where \code{T} is the type of the initializing
  13197. expressions. The type checking of the \code{len} function and the
  13198. subscript operator are updated to handle lists. The type checker now
  13199. also handles a subscript on the left-hand side of an assignment.
  13200. Regarding multiplication, it takes two integers and returns an
  13201. integer.
  13202. %
  13203. \fi}
  13204. \begin{figure}[tbp]
  13205. \begin{tcolorbox}[colback=white]
  13206. {\if\edition\racketEd
  13207. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13208. (define type-check-Lvecof-class
  13209. (class type-check-Lvec-class
  13210. (super-new)
  13211. (inherit check-type-equal?)
  13212. (define/override (operator-types)
  13213. (append '((* . ((Integer Integer) . Integer)))
  13214. (super operator-types)))
  13215. (define/override (type-check-exp env)
  13216. (lambda (e)
  13217. (define recur (type-check-exp env))
  13218. (match e
  13219. [(Prim 'make-vector (list e1 e2))
  13220. (define-values (e1^ t1) (recur e1))
  13221. (define-values (e2^ elt-type) (recur e2))
  13222. (define vec-type `(Vectorof ,elt-type))
  13223. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13224. [(Prim 'vector-ref (list e1 e2))
  13225. (define-values (e1^ t1) (recur e1))
  13226. (define-values (e2^ t2) (recur e2))
  13227. (match* (t1 t2)
  13228. [(`(Vectorof ,elt-type) 'Integer)
  13229. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13230. [(other wise) ((super type-check-exp env) e)])]
  13231. [(Prim 'vector-set! (list e1 e2 e3) )
  13232. (define-values (e-vec t-vec) (recur e1))
  13233. (define-values (e2^ t2) (recur e2))
  13234. (define-values (e-arg^ t-arg) (recur e3))
  13235. (match t-vec
  13236. [`(Vectorof ,elt-type)
  13237. (check-type-equal? elt-type t-arg e)
  13238. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13239. [else ((super type-check-exp env) e)])]
  13240. [(Prim 'vector-length (list e1))
  13241. (define-values (e1^ t1) (recur e1))
  13242. (match t1
  13243. [`(Vectorof ,t)
  13244. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13245. [else ((super type-check-exp env) e)])]
  13246. [else ((super type-check-exp env) e)])))
  13247. ))
  13248. (define (type-check-Lvecof p)
  13249. (send (new type-check-Lvecof-class) type-check-program p))
  13250. \end{lstlisting}
  13251. \fi}
  13252. {\if\edition\pythonEd\pythonColor
  13253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13254. class TypeCheckLarray(TypeCheckLtup):
  13255. def type_check_exp(self, e, env):
  13256. match e:
  13257. case ast.List(es, Load()):
  13258. ts = [self.type_check_exp(e, env) for e in es]
  13259. elt_ty = ts[0]
  13260. for (ty, elt) in zip(ts, es):
  13261. self.check_type_equal(elt_ty, ty, elt)
  13262. e.has_type = ListType(elt_ty)
  13263. return e.has_type
  13264. case Call(Name('len'), [tup]):
  13265. tup_t = self.type_check_exp(tup, env)
  13266. tup.has_type = tup_t
  13267. match tup_t:
  13268. case TupleType(ts):
  13269. return IntType()
  13270. case ListType(ty):
  13271. return IntType()
  13272. case _:
  13273. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13274. case Subscript(tup, index, Load()):
  13275. tup_ty = self.type_check_exp(tup, env)
  13276. index_ty = self.type_check_exp(index, env)
  13277. self.check_type_equal(index_ty, IntType(), index)
  13278. match tup_ty:
  13279. case TupleType(ts):
  13280. match index:
  13281. case Constant(i):
  13282. return ts[i]
  13283. case _:
  13284. raise Exception('subscript required constant integer index')
  13285. case ListType(ty):
  13286. return ty
  13287. case _:
  13288. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13289. case BinOp(left, Mult(), right):
  13290. l = self.type_check_exp(left, env)
  13291. self.check_type_equal(l, IntType(), left)
  13292. r = self.type_check_exp(right, env)
  13293. self.check_type_equal(r, IntType(), right)
  13294. return IntType()
  13295. case _:
  13296. return super().type_check_exp(e, env)
  13297. \end{lstlisting}
  13298. \fi}
  13299. \end{tcolorbox}
  13300. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13301. \label{fig:type-check-Lvecof}
  13302. \end{figure}
  13303. {\if\edition\pythonEd
  13304. \begin{figure}[tbp]
  13305. \begin{tcolorbox}[colback=white]
  13306. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13307. def type_check_stmts(self, ss, env):
  13308. if len(ss) == 0:
  13309. return VoidType()
  13310. match ss[0]:
  13311. case Assign([Subscript(tup, index, Store())], value):
  13312. tup_t = self.type_check_exp(tup, env)
  13313. value_t = self.type_check_exp(value, env)
  13314. index_ty = self.type_check_exp(index, env)
  13315. self.check_type_equal(index_ty, IntType(), index)
  13316. match tup_t:
  13317. case ListType(ty):
  13318. self.check_type_equal(ty, value_t, ss[0])
  13319. case TupleType(ts):
  13320. return self.type_check_stmts(ss, env)
  13321. case _:
  13322. raise Exception('type_check_stmts: '
  13323. 'expected tuple or list, not ' + repr(tup_t))
  13324. return self.type_check_stmts(ss[1:], env)
  13325. case _:
  13326. return super().type_check_stmts(ss, env)
  13327. \end{lstlisting}
  13328. \end{tcolorbox}
  13329. \caption{Type checker for the \LangArray{} language, part 2.}
  13330. \label{fig:type-check-Lvecof-part2}
  13331. \end{figure}
  13332. \fi}
  13333. The definition of the interpreter for \LangArray{} is shown in
  13334. \racket{figure~\ref{fig:interp-Lvecof}}
  13335. \python{figure~\ref{fig:interp-Lvecof}}.
  13336. \racket{The \code{make-vector} operator is
  13337. interpreted using Racket's \code{make-vector} function,
  13338. and multiplication is interpreted using \code{fx*},
  13339. which is multiplication for \code{fixnum} integers.
  13340. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13341. we translate array access operations
  13342. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13343. which we interpret using \code{vector} operations with additional
  13344. bounds checks that signal a \code{trapped-error}.
  13345. }
  13346. %
  13347. \python{We implement array creation with a Python list comprehension,
  13348. and multiplication is implemented with 64-bit multiplication. We
  13349. add a case to handle a subscript on the left-hand side of
  13350. assignment. Other uses of subscript can be handled by the existing
  13351. code for tuples.}
  13352. \begin{figure}[tbp]
  13353. \begin{tcolorbox}[colback=white]
  13354. {\if\edition\racketEd
  13355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13356. (define interp-Lvecof-class
  13357. (class interp-Lvec-class
  13358. (super-new)
  13359. (define/override (interp-op op)
  13360. (match op
  13361. ['make-vector make-vector]
  13362. ['vectorof-length vector-length]
  13363. ['vectorof-ref
  13364. (lambda (v i)
  13365. (if (< i (vector-length v))
  13366. (vector-ref v i)
  13367. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13368. ['vectorof-set!
  13369. (lambda (v i e)
  13370. (if (< i (vector-length v))
  13371. (vector-set! v i e)
  13372. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13373. [else (super interp-op op)]))
  13374. ))
  13375. (define (interp-Lvecof p)
  13376. (send (new interp-Lvecof-class) interp-program p))
  13377. \end{lstlisting}
  13378. \fi}
  13379. {\if\edition\pythonEd\pythonColor
  13380. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13381. class InterpLarray(InterpLtup):
  13382. def interp_exp(self, e, env):
  13383. match e:
  13384. case ast.List(es, Load()):
  13385. return [self.interp_exp(e, env) for e in es]
  13386. case BinOp(left, Mult(), right):
  13387. l = self.interp_exp(left, env)
  13388. r = self.interp_exp(right, env)
  13389. return mul64(l, r)
  13390. case Subscript(tup, index, Load()):
  13391. t = self.interp_exp(tup, env)
  13392. n = self.interp_exp(index, env)
  13393. if n < len(t):
  13394. return t[n]
  13395. else:
  13396. raise TrappedError('array index out of bounds')
  13397. case _:
  13398. return super().interp_exp(e, env)
  13399. def interp_stmt(self, s, env, cont):
  13400. match s:
  13401. case Assign([Subscript(tup, index)], value):
  13402. t = self.interp_exp(tup, env)
  13403. n = self.interp_exp(index, env)
  13404. if n < len(t):
  13405. t[n] = self.interp_exp(value, env)
  13406. else:
  13407. raise TrappedError('array index out of bounds')
  13408. return self.interp_stmts(cont, env)
  13409. case _:
  13410. return super().interp_stmt(s, env, cont)
  13411. \end{lstlisting}
  13412. \fi}
  13413. \end{tcolorbox}
  13414. \caption{Interpreter for \LangArray{}.}
  13415. \label{fig:interp-Lvecof}
  13416. \end{figure}
  13417. \subsection{Data Representation}
  13418. \label{sec:array-rep}
  13419. Just as with tuples, we store arrays on the heap, which means that the
  13420. garbage collector will need to inspect arrays. An immediate thought is
  13421. to use the same representation for arrays that we use for tuples.
  13422. However, we limit tuples to a length of fifty so that their length and
  13423. pointer mask can fit into the 64-bit tag at the beginning of each
  13424. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13425. millions of elements, so we need more bits to store the length.
  13426. However, because arrays are homogeneous, we need only 1 bit for the
  13427. pointer mask instead of 1 bit per array element. Finally, the
  13428. garbage collector must be able to distinguish between tuples
  13429. and arrays, so we need to reserve one bit for that purpose. We
  13430. arrive at the following layout for the 64-bit tag at the beginning of
  13431. an array:
  13432. \begin{itemize}
  13433. \item The right-most bit is the forwarding bit, just as in a tuple.
  13434. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13435. that it is not.
  13436. \item The next bit to the left is the pointer mask. A $0$ indicates
  13437. that none of the elements are pointers, and a $1$ indicates that all
  13438. the elements are pointers.
  13439. \item The next $60$ bits store the length of the array.
  13440. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13441. and an array ($1$).
  13442. \item The left-most bit is reserved as explained in
  13443. chapter~\ref{ch:Lgrad}.
  13444. \end{itemize}
  13445. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13446. %% differentiate the kinds of values that have been injected into the
  13447. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13448. %% to indicate that the value is an array.
  13449. In the following subsections we provide hints regarding how to update
  13450. the passes to handle arrays.
  13451. \subsection{Overload Resolution}
  13452. \label{sec:array-resolution}
  13453. As noted previously, with the addition of arrays, several operators
  13454. have become \emph{overloaded}; that is, they can be applied to values
  13455. of more than one type. In this case, the element access and length
  13456. operators can be applied to both tuples and arrays. This kind of
  13457. overloading is quite common in programming languages, so many
  13458. compilers perform \emph{overload resolution}\index{subject}{overload
  13459. resolution} to handle it. The idea is to translate each overloaded
  13460. operator into different operators for the different types.
  13461. Implement a new pass named \code{resolve}.
  13462. Translate the reading of an array element to
  13463. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13464. and the writing of an array element to
  13465. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13466. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13467. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13468. When these operators are applied to tuples, leave them as is.
  13469. %
  13470. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13471. field, which can be inspected to determine whether the operator
  13472. is applied to a tuple or an array.}
  13473. \subsection{Bounds Checking}
  13474. Recall that the interpreter for \LangArray{} signals a
  13475. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13476. when there is an array access that is out of
  13477. bounds. Therefore your compiler is obliged to also catch these errors
  13478. during execution and halt, signaling an error. We recommend inserting
  13479. a new pass named \code{check\_bounds} that inserts code around each
  13480. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13481. \python{subscript} operation to ensure that the index is greater than
  13482. or equal to zero and less than the array's length. If not, the program
  13483. should halt, for which we recommend using a new primitive operation
  13484. named \code{exit}.
  13485. %% \subsection{Reveal Casts}
  13486. %% The array-access operators \code{vectorof-ref} and
  13487. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13488. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13489. %% that the type checker cannot tell whether the index will be in bounds,
  13490. %% so the bounds check must be performed at run time. Recall that the
  13491. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13492. %% an \code{If} around a vector reference for update to check whether
  13493. %% the index is less than the length. You should do the same for
  13494. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13495. %% In addition, the handling of the \code{any-vector} operators in
  13496. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13497. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13498. %% generated code should test whether the tag is for tuples (\code{010})
  13499. %% or arrays (\code{110}) and then dispatch to either
  13500. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13501. %% we add a case in \code{select\_instructions} to generate the
  13502. %% appropriate instructions for accessing the array length from the
  13503. %% header of an array.
  13504. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13505. %% the generated code needs to check that the index is less than the
  13506. %% vector length, so like the code for \code{any-vector-length}, check
  13507. %% the tag to determine whether to use \code{any-vector-length} or
  13508. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13509. %% is complete, the generated code can use \code{any-vector-ref} and
  13510. %% \code{any-vector-set!} for both tuples and arrays because the
  13511. %% instructions used for those operators do not look at the tag at the
  13512. %% front of the tuple or array.
  13513. \subsection{Expose Allocation}
  13514. This pass should translate array creation into lower-level
  13515. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13516. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13517. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13518. array. The \code{AllocateArray} AST node allocates an array of the
  13519. length specified by the $\Exp$ (of type \INTTY), but does not
  13520. initialize the elements of the array. Generate code in this pass to
  13521. initialize the elements analogous to the case for tuples.
  13522. {\if\edition\racketEd
  13523. \subsection{Uncover \texttt{get!}}
  13524. \label{sec:uncover-get-bang-vecof}
  13525. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13526. \code{uncover-get!-exp}.
  13527. \fi}
  13528. \subsection{Remove Complex Operands}
  13529. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13530. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13531. complex, and its subexpression must be atomic.
  13532. \subsection{Explicate Control}
  13533. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13534. \code{explicate\_assign}.
  13535. \subsection{Select Instructions}
  13536. \index{subject}{select instructions}
  13537. Generate instructions for \code{AllocateArray} similar to those for
  13538. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13539. except that the tag at the front of the array should instead use the
  13540. representation discussed in section~\ref{sec:array-rep}.
  13541. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13542. extract the length from the tag.
  13543. The instructions generated for accessing an element of an array differ
  13544. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13545. that the index is not a constant so you need to generate instructions
  13546. that compute the offset at runtime.
  13547. Compile the \code{exit} primitive into a call to the \code{exit}
  13548. function of the C standard library, with an argument of $255$.
  13549. %% Also, note that assignment to an array element may appear in
  13550. %% as a stand-alone statement, so make sure to handle that situation in
  13551. %% this pass.
  13552. %% Finally, the instructions for \code{any-vectorof-length} should be
  13553. %% similar to those for \code{vectorof-length}, except that one must
  13554. %% first project the array by writing zeroes into the $3$-bit tag
  13555. \begin{exercise}\normalfont\normalsize
  13556. Implement a compiler for the \LangArray{} language by extending your
  13557. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13558. programs, including the one shown in figure~\ref{fig:inner_product}
  13559. and also a program that multiplies two matrices. Note that although
  13560. matrices are two-dimensional arrays, they can be encoded into
  13561. one-dimensional arrays by laying out each row in the array, one after
  13562. the next.
  13563. \end{exercise}
  13564. {\if\edition\racketEd
  13565. \section{Challenge: Generational Collection}
  13566. The copying collector described in section~\ref{sec:GC} can incur
  13567. significant runtime overhead because the call to \code{collect} takes
  13568. time proportional to all the live data. One way to reduce this
  13569. overhead is to reduce how much data is inspected in each call to
  13570. \code{collect}. In particular, researchers have observed that recently
  13571. allocated data is more likely to become garbage then data that has
  13572. survived one or more previous calls to \code{collect}. This insight
  13573. motivated the creation of \emph{generational garbage collectors}
  13574. \index{subject}{generational garbage collector} that
  13575. (1) segregate data according to its age into two or more generations;
  13576. (2) allocate less space for younger generations, so collecting them is
  13577. faster, and more space for the older generations; and (3) perform
  13578. collection on the younger generations more frequently than on older
  13579. generations~\citep{Wilson:1992fk}.
  13580. For this challenge assignment, the goal is to adapt the copying
  13581. collector implemented in \code{runtime.c} to use two generations, one
  13582. for young data and one for old data. Each generation consists of a
  13583. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13584. \code{collect} function to use the two generations:
  13585. \begin{enumerate}
  13586. \item Copy the young generation's FromSpace to its ToSpace and then
  13587. switch the role of the ToSpace and FromSpace.
  13588. \item If there is enough space for the requested number of bytes in
  13589. the young FromSpace, then return from \code{collect}.
  13590. \item If there is not enough space in the young FromSpace for the
  13591. requested bytes, then move the data from the young generation to the
  13592. old one with the following steps:
  13593. \begin{enumerate}
  13594. \item[a.] If there is enough room in the old FromSpace, copy the young
  13595. FromSpace to the old FromSpace and then return.
  13596. \item[b.] If there is not enough room in the old FromSpace, then collect
  13597. the old generation by copying the old FromSpace to the old ToSpace
  13598. and swap the roles of the old FromSpace and ToSpace.
  13599. \item[c.] If there is enough room now, copy the young FromSpace to the
  13600. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13601. and ToSpace for the old generation. Copy the young FromSpace and
  13602. the old FromSpace into the larger FromSpace for the old
  13603. generation and then return.
  13604. \end{enumerate}
  13605. \end{enumerate}
  13606. We recommend that you generalize the \code{cheney} function so that it
  13607. can be used for all the copies mentioned: between the young FromSpace
  13608. and ToSpace, between the old FromSpace and ToSpace, and between the
  13609. young FromSpace and old FromSpace. This can be accomplished by adding
  13610. parameters to \code{cheney} that replace its use of the global
  13611. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13612. \code{tospace\_begin}, and \code{tospace\_end}.
  13613. Note that the collection of the young generation does not traverse the
  13614. old generation. This introduces a potential problem: there may be
  13615. young data that is reachable only through pointers in the old
  13616. generation. If these pointers are not taken into account, the
  13617. collector could throw away young data that is live! One solution,
  13618. called \emph{pointer recording}, is to maintain a set of all the
  13619. pointers from the old generation into the new generation and consider
  13620. this set as part of the root set. To maintain this set, the compiler
  13621. must insert extra instructions around every \code{vector-set!}. If the
  13622. vector being modified is in the old generation, and if the value being
  13623. written is a pointer into the new generation, then that pointer must
  13624. be added to the set. Also, if the value being overwritten was a
  13625. pointer into the new generation, then that pointer should be removed
  13626. from the set.
  13627. \begin{exercise}\normalfont\normalsize
  13628. Adapt the \code{collect} function in \code{runtime.c} to implement
  13629. generational garbage collection, as outlined in this section.
  13630. Update the code generation for \code{vector-set!} to implement
  13631. pointer recording. Make sure that your new compiler and runtime
  13632. execute without error on your test suite.
  13633. \end{exercise}
  13634. \fi}
  13635. \section{Further Reading}
  13636. \citet{Appel90} describes many data representation approaches
  13637. including the ones used in the compilation of Standard ML.
  13638. There are many alternatives to copying collectors (and their bigger
  13639. siblings, the generational collectors) with regard to garbage
  13640. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13641. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13642. collectors are that allocation is fast (just a comparison and pointer
  13643. increment), there is no fragmentation, cyclic garbage is collected,
  13644. and the time complexity of collection depends only on the amount of
  13645. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13646. main disadvantages of a two-space copying collector is that it uses a
  13647. lot of extra space and takes a long time to perform the copy, though
  13648. these problems are ameliorated in generational collectors.
  13649. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13650. small objects and generate a lot of garbage, so copying and
  13651. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13652. Garbage collection is an active research topic, especially concurrent
  13653. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13654. developing new techniques and revisiting old
  13655. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13656. meet every year at the International Symposium on Memory Management to
  13657. present these findings.
  13658. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13659. \chapter{Functions}
  13660. \label{ch:Lfun}
  13661. \index{subject}{function}
  13662. \setcounter{footnote}{0}
  13663. This chapter studies the compilation of a subset of \racket{Typed
  13664. Racket}\python{Python} in which only top-level function definitions
  13665. are allowed. This kind of function appears in the C programming
  13666. language, and it serves as an important stepping-stone to implementing
  13667. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13668. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13669. \section{The \LangFun{} Language}
  13670. The concrete syntax and abstract syntax for function definitions and
  13671. function application are shown in
  13672. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13673. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13674. with zero or more function definitions. The function names from these
  13675. definitions are in scope for the entire program, including all the
  13676. function definitions, and therefore the ordering of function
  13677. definitions does not matter.
  13678. %
  13679. \python{The abstract syntax for function parameters in
  13680. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13681. consists of a parameter name and its type. This design differs from
  13682. Python's \code{ast} module, which has a more complex structure for
  13683. function parameters to handle keyword parameters,
  13684. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13685. complex Python abstract syntax into the simpler syntax shown in
  13686. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13687. \code{FunctionDef} constructor are for decorators and a type
  13688. comment, neither of which are used by our compiler. We recommend
  13689. replacing them with \code{None} in the \code{shrink} pass.
  13690. }
  13691. %
  13692. The concrete syntax for function application
  13693. \index{subject}{function application}
  13694. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13695. where the first expression
  13696. must evaluate to a function and the remaining expressions are the arguments. The
  13697. abstract syntax for function application is
  13698. $\APPLY{\Exp}{\Exp^*}$.
  13699. %% The syntax for function application does not include an explicit
  13700. %% keyword, which is error prone when using \code{match}. To alleviate
  13701. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13702. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13703. Functions are first-class in the sense that a function pointer
  13704. \index{subject}{function pointer} is data and can be stored in memory or passed
  13705. as a parameter to another function. Thus, there is a function
  13706. type, written
  13707. {\if\edition\racketEd
  13708. \begin{lstlisting}
  13709. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13710. \end{lstlisting}
  13711. \fi}
  13712. {\if\edition\pythonEd\pythonColor
  13713. \begin{lstlisting}
  13714. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13715. \end{lstlisting}
  13716. \fi}
  13717. %
  13718. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13719. through $\Type_n$ and whose return type is $\Type_R$. The main
  13720. limitation of these functions (with respect to
  13721. \racket{Racket}\python{Python} functions) is that they are not
  13722. lexically scoped. That is, the only external entities that can be
  13723. referenced from inside a function body are other globally defined
  13724. functions. The syntax of \LangFun{} prevents function definitions from
  13725. being nested inside each other.
  13726. \newcommand{\LfunGrammarRacket}{
  13727. \begin{array}{lcl}
  13728. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13729. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13730. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13731. \end{array}
  13732. }
  13733. \newcommand{\LfunASTRacket}{
  13734. \begin{array}{lcl}
  13735. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13736. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13737. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13738. \end{array}
  13739. }
  13740. \newcommand{\LfunGrammarPython}{
  13741. \begin{array}{lcl}
  13742. \Type &::=& \key{int}
  13743. \MID \key{bool} \MID \key{void}
  13744. \MID \key{tuple}\LS \Type^+ \RS
  13745. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13746. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13747. \Stmt &::=& \CRETURN{\Exp} \\
  13748. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13749. \end{array}
  13750. }
  13751. \newcommand{\LfunASTPython}{
  13752. \begin{array}{lcl}
  13753. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13754. \MID \key{TupleType}\LS\Type^+\RS\\
  13755. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13756. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13757. \Stmt &::=& \RETURN{\Exp} \\
  13758. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13759. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13760. \end{array}
  13761. }
  13762. \begin{figure}[tp]
  13763. \centering
  13764. \begin{tcolorbox}[colback=white]
  13765. \small
  13766. {\if\edition\racketEd
  13767. \[
  13768. \begin{array}{l}
  13769. \gray{\LintGrammarRacket{}} \\ \hline
  13770. \gray{\LvarGrammarRacket{}} \\ \hline
  13771. \gray{\LifGrammarRacket{}} \\ \hline
  13772. \gray{\LwhileGrammarRacket} \\ \hline
  13773. \gray{\LtupGrammarRacket} \\ \hline
  13774. \LfunGrammarRacket \\
  13775. \begin{array}{lcl}
  13776. \LangFunM{} &::=& \Def \ldots \; \Exp
  13777. \end{array}
  13778. \end{array}
  13779. \]
  13780. \fi}
  13781. {\if\edition\pythonEd\pythonColor
  13782. \[
  13783. \begin{array}{l}
  13784. \gray{\LintGrammarPython{}} \\ \hline
  13785. \gray{\LvarGrammarPython{}} \\ \hline
  13786. \gray{\LifGrammarPython{}} \\ \hline
  13787. \gray{\LwhileGrammarPython} \\ \hline
  13788. \gray{\LtupGrammarPython} \\ \hline
  13789. \LfunGrammarPython \\
  13790. \begin{array}{rcl}
  13791. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13792. \end{array}
  13793. \end{array}
  13794. \]
  13795. \fi}
  13796. \end{tcolorbox}
  13797. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13798. \label{fig:Lfun-concrete-syntax}
  13799. \end{figure}
  13800. \begin{figure}[tp]
  13801. \centering
  13802. \begin{tcolorbox}[colback=white]
  13803. \small
  13804. {\if\edition\racketEd
  13805. \[
  13806. \begin{array}{l}
  13807. \gray{\LintOpAST} \\ \hline
  13808. \gray{\LvarASTRacket{}} \\ \hline
  13809. \gray{\LifASTRacket{}} \\ \hline
  13810. \gray{\LwhileASTRacket{}} \\ \hline
  13811. \gray{\LtupASTRacket{}} \\ \hline
  13812. \LfunASTRacket \\
  13813. \begin{array}{lcl}
  13814. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13815. \end{array}
  13816. \end{array}
  13817. \]
  13818. \fi}
  13819. {\if\edition\pythonEd\pythonColor
  13820. \[
  13821. \begin{array}{l}
  13822. \gray{\LintASTPython{}} \\ \hline
  13823. \gray{\LvarASTPython{}} \\ \hline
  13824. \gray{\LifASTPython{}} \\ \hline
  13825. \gray{\LwhileASTPython} \\ \hline
  13826. \gray{\LtupASTPython} \\ \hline
  13827. \LfunASTPython \\
  13828. \begin{array}{rcl}
  13829. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13830. \end{array}
  13831. \end{array}
  13832. \]
  13833. \fi}
  13834. \end{tcolorbox}
  13835. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13836. \label{fig:Lfun-syntax}
  13837. \end{figure}
  13838. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13839. representative example of defining and using functions in \LangFun{}.
  13840. We define a function \code{map} that applies some other function
  13841. \code{f} to both elements of a tuple and returns a new tuple
  13842. containing the results. We also define a function \code{inc}. The
  13843. program applies \code{map} to \code{inc} and
  13844. %
  13845. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13846. %
  13847. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13848. %
  13849. from which we return \code{42}.
  13850. \begin{figure}[tbp]
  13851. \begin{tcolorbox}[colback=white]
  13852. {\if\edition\racketEd
  13853. \begin{lstlisting}
  13854. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13855. : (Vector Integer Integer)
  13856. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13857. (define (inc [x : Integer]) : Integer
  13858. (+ x 1))
  13859. (vector-ref (map inc (vector 0 41)) 1)
  13860. \end{lstlisting}
  13861. \fi}
  13862. {\if\edition\pythonEd\pythonColor
  13863. \begin{lstlisting}
  13864. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13865. return f(v[0]), f(v[1])
  13866. def inc(x : int) -> int:
  13867. return x + 1
  13868. print(map(inc, (0, 41))[1])
  13869. \end{lstlisting}
  13870. \fi}
  13871. \end{tcolorbox}
  13872. \caption{Example of using functions in \LangFun{}.}
  13873. \label{fig:Lfun-function-example}
  13874. \end{figure}
  13875. The definitional interpreter for \LangFun{} is shown in
  13876. figure~\ref{fig:interp-Lfun}. The case for the
  13877. %
  13878. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13879. %
  13880. AST is responsible for setting up the mutual recursion between the
  13881. top-level function definitions.
  13882. %
  13883. \racket{We use the classic back-patching
  13884. \index{subject}{back-patching} approach that uses mutable variables
  13885. and makes two passes over the function
  13886. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13887. top-level environment using a mutable cons cell for each function
  13888. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13889. for each function is incomplete; it does not yet include the environment.
  13890. Once the top-level environment has been constructed, we iterate over it and
  13891. update the \code{lambda} values to use the top-level environment.}
  13892. %
  13893. \python{We create a dictionary named \code{env} and fill it in
  13894. by mapping each function name to a new \code{Function} value,
  13895. each of which stores a reference to the \code{env}.
  13896. (We define the class \code{Function} for this purpose.)}
  13897. %
  13898. To interpret a function \racket{application}\python{call}, we match
  13899. the result of the function expression to obtain a function value. We
  13900. then extend the function's environment with the mapping of parameters to
  13901. argument values. Finally, we interpret the body of the function in
  13902. this extended environment.
  13903. \begin{figure}[tp]
  13904. \begin{tcolorbox}[colback=white]
  13905. {\if\edition\racketEd
  13906. \begin{lstlisting}
  13907. (define interp-Lfun-class
  13908. (class interp-Lvec-class
  13909. (super-new)
  13910. (define/override ((interp-exp env) e)
  13911. (define recur (interp-exp env))
  13912. (match e
  13913. [(Apply fun args)
  13914. (define fun-val (recur fun))
  13915. (define arg-vals (for/list ([e args]) (recur e)))
  13916. (match fun-val
  13917. [`(function (,xs ...) ,body ,fun-env)
  13918. (define params-args (for/list ([x xs] [arg arg-vals])
  13919. (cons x (box arg))))
  13920. (define new-env (append params-args fun-env))
  13921. ((interp-exp new-env) body)]
  13922. [else
  13923. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13924. [else ((super interp-exp env) e)]
  13925. ))
  13926. (define/public (interp-def d)
  13927. (match d
  13928. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13929. (cons f (box `(function ,xs ,body ())))]))
  13930. (define/override (interp-program p)
  13931. (match p
  13932. [(ProgramDefsExp info ds body)
  13933. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13934. (for/list ([f (in-dict-values top-level)])
  13935. (set-box! f (match (unbox f)
  13936. [`(function ,xs ,body ())
  13937. `(function ,xs ,body ,top-level)])))
  13938. ((interp-exp top-level) body))]))
  13939. ))
  13940. (define (interp-Lfun p)
  13941. (send (new interp-Lfun-class) interp-program p))
  13942. \end{lstlisting}
  13943. \fi}
  13944. {\if\edition\pythonEd\pythonColor
  13945. \begin{lstlisting}
  13946. class InterpLfun(InterpLtup):
  13947. def apply_fun(self, fun, args, e):
  13948. match fun:
  13949. case Function(name, xs, body, env):
  13950. new_env = env.copy().update(zip(xs, args))
  13951. return self.interp_stmts(body, new_env)
  13952. case _:
  13953. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13954. def interp_exp(self, e, env):
  13955. match e:
  13956. case Call(Name('input_int'), []):
  13957. return super().interp_exp(e, env)
  13958. case Call(func, args):
  13959. f = self.interp_exp(func, env)
  13960. vs = [self.interp_exp(arg, env) for arg in args]
  13961. return self.apply_fun(f, vs, e)
  13962. case _:
  13963. return super().interp_exp(e, env)
  13964. def interp_stmt(self, s, env, cont):
  13965. match s:
  13966. case Return(value):
  13967. return self.interp_exp(value, env)
  13968. case FunctionDef(name, params, bod, dl, returns, comment):
  13969. if isinstance(params, ast.arguments):
  13970. ps = [p.arg for p in params.args]
  13971. else:
  13972. ps = [x for (x,t) in params]
  13973. env[name] = Function(name, ps, bod, env)
  13974. return self.interp_stmts(cont, env)
  13975. case _:
  13976. return super().interp_stmt(s, env, cont)
  13977. def interp(self, p):
  13978. match p:
  13979. case Module(ss):
  13980. env = {}
  13981. self.interp_stmts(ss, env)
  13982. if 'main' in env.keys():
  13983. self.apply_fun(env['main'], [], None)
  13984. case _:
  13985. raise Exception('interp: unexpected ' + repr(p))
  13986. \end{lstlisting}
  13987. \fi}
  13988. \end{tcolorbox}
  13989. \caption{Interpreter for the \LangFun{} language.}
  13990. \label{fig:interp-Lfun}
  13991. \end{figure}
  13992. %\margincomment{TODO: explain type checker}
  13993. The type checker for \LangFun{} is shown in
  13994. figure~\ref{fig:type-check-Lfun}.
  13995. %
  13996. \python{(We omit the code that parses function parameters into the
  13997. simpler abstract syntax.)}
  13998. %
  13999. Similarly to the interpreter, the case for the
  14000. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14001. %
  14002. AST is responsible for setting up the mutual recursion between the
  14003. top-level function definitions. We begin by creating a mapping
  14004. \code{env} from every function name to its type. We then type check
  14005. the program using this mapping.
  14006. %
  14007. \python{To check a function definition, we copy and extend the
  14008. \code{env} with the parameters of the function. We then type check
  14009. the body of the function and obtain the actual return type
  14010. \code{rt}, which is either the type of the expression in a
  14011. \code{return} statement, or the \code{VoidType} if control reaches
  14012. the end of the function without a \code{return} statement. (If
  14013. there are multiple \code{return} statements, the types of their
  14014. expressions must agree.) Finally we check that the actual return
  14015. type \code{rt} is equal to the declared return type \code{returns}.}
  14016. %
  14017. To check a function \racket{application}\python{call}, we match
  14018. the type of the function expression to a function type and check that
  14019. the types of the argument expressions are equal to the function's
  14020. parameter types. The type of the \racket{application}\python{call} as
  14021. a whole is the return type from the function type.
  14022. \begin{figure}[tp]
  14023. \begin{tcolorbox}[colback=white]
  14024. {\if\edition\racketEd
  14025. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14026. (define type-check-Lfun-class
  14027. (class type-check-Lvec-class
  14028. (super-new)
  14029. (inherit check-type-equal?)
  14030. (define/public (type-check-apply env e es)
  14031. (define-values (e^ ty) ((type-check-exp env) e))
  14032. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14033. ((type-check-exp env) e)))
  14034. (match ty
  14035. [`(,ty^* ... -> ,rt)
  14036. (for ([arg-ty ty*] [param-ty ty^*])
  14037. (check-type-equal? arg-ty param-ty (Apply e es)))
  14038. (values e^ e* rt)]))
  14039. (define/override (type-check-exp env)
  14040. (lambda (e)
  14041. (match e
  14042. [(FunRef f n)
  14043. (values (FunRef f n) (dict-ref env f))]
  14044. [(Apply e es)
  14045. (define-values (e^ es^ rt) (type-check-apply env e es))
  14046. (values (Apply e^ es^) rt)]
  14047. [(Call e es)
  14048. (define-values (e^ es^ rt) (type-check-apply env e es))
  14049. (values (Call e^ es^) rt)]
  14050. [else ((super type-check-exp env) e)])))
  14051. (define/public (type-check-def env)
  14052. (lambda (e)
  14053. (match e
  14054. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14055. (define new-env (append (map cons xs ps) env))
  14056. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14057. (check-type-equal? ty^ rt body)
  14058. (Def f p:t* rt info body^)])))
  14059. (define/public (fun-def-type d)
  14060. (match d
  14061. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14062. (define/override (type-check-program e)
  14063. (match e
  14064. [(ProgramDefsExp info ds body)
  14065. (define env (for/list ([d ds])
  14066. (cons (Def-name d) (fun-def-type d))))
  14067. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14068. (define-values (body^ ty) ((type-check-exp env) body))
  14069. (check-type-equal? ty 'Integer body)
  14070. (ProgramDefsExp info ds^ body^)]))))
  14071. (define (type-check-Lfun p)
  14072. (send (new type-check-Lfun-class) type-check-program p))
  14073. \end{lstlisting}
  14074. \fi}
  14075. {\if\edition\pythonEd\pythonColor
  14076. \begin{lstlisting}
  14077. class TypeCheckLfun(TypeCheckLtup):
  14078. def type_check_exp(self, e, env):
  14079. match e:
  14080. case Call(Name('input_int'), []):
  14081. return super().type_check_exp(e, env)
  14082. case Call(func, args):
  14083. func_t = self.type_check_exp(func, env)
  14084. args_t = [self.type_check_exp(arg, env) for arg in args]
  14085. match func_t:
  14086. case FunctionType(params_t, return_t):
  14087. for (arg_t, param_t) in zip(args_t, params_t):
  14088. check_type_equal(param_t, arg_t, e)
  14089. return return_t
  14090. case _:
  14091. raise Exception('type_check_exp: in call, unexpected ' +
  14092. repr(func_t))
  14093. case _:
  14094. return super().type_check_exp(e, env)
  14095. def type_check_stmts(self, ss, env):
  14096. if len(ss) == 0:
  14097. return VoidType()
  14098. match ss[0]:
  14099. case FunctionDef(name, params, body, dl, returns, comment):
  14100. new_env = env.copy().update(params)
  14101. rt = self.type_check_stmts(body, new_env)
  14102. check_type_equal(returns, rt, ss[0])
  14103. return self.type_check_stmts(ss[1:], env)
  14104. case Return(value):
  14105. return self.type_check_exp(value, env)
  14106. case _:
  14107. return super().type_check_stmts(ss, env)
  14108. def type_check(self, p):
  14109. match p:
  14110. case Module(body):
  14111. env = {}
  14112. for s in body:
  14113. match s:
  14114. case FunctionDef(name, params, bod, dl, returns, comment):
  14115. if name in env:
  14116. raise Exception('type_check: function ' +
  14117. repr(name) + ' defined twice')
  14118. params_t = [t for (x,t) in params]
  14119. env[name] = FunctionType(params_t, returns)
  14120. self.type_check_stmts(body, env)
  14121. case _:
  14122. raise Exception('type_check: unexpected ' + repr(p))
  14123. \end{lstlisting}
  14124. \fi}
  14125. \end{tcolorbox}
  14126. \caption{Type checker for the \LangFun{} language.}
  14127. \label{fig:type-check-Lfun}
  14128. \end{figure}
  14129. \clearpage
  14130. \section{Functions in x86}
  14131. \label{sec:fun-x86}
  14132. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14133. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14134. %% \margincomment{\tiny Talk about the return address on the
  14135. %% stack and what callq and retq does.\\ --Jeremy }
  14136. The x86 architecture provides a few features to support the
  14137. implementation of functions. We have already seen that there are
  14138. labels in x86 so that one can refer to the location of an instruction,
  14139. as is needed for jump instructions. Labels can also be used to mark
  14140. the beginning of the instructions for a function. Going further, we
  14141. can obtain the address of a label by using the \key{leaq}
  14142. instruction. For example, the following puts the address of the
  14143. \code{inc} label into the \code{rbx} register:
  14144. \begin{lstlisting}
  14145. leaq inc(%rip), %rbx
  14146. \end{lstlisting}
  14147. Recall from section~\ref{sec:select-instructions-gc} that
  14148. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14149. addressing.
  14150. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14151. to functions whose locations were given by a label, such as
  14152. \code{read\_int}. To support function calls in this chapter we instead
  14153. jump to functions whose location are given by an address in
  14154. a register; that is, we use \emph{indirect function calls}. The
  14155. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14156. before the register name.\index{subject}{indirect function call}
  14157. \begin{lstlisting}
  14158. callq *%rbx
  14159. \end{lstlisting}
  14160. \subsection{Calling Conventions}
  14161. \label{sec:calling-conventions-fun}
  14162. \index{subject}{calling conventions}
  14163. The \code{callq} instruction provides partial support for implementing
  14164. functions: it pushes the return address on the stack and it jumps to
  14165. the target. However, \code{callq} does not handle
  14166. \begin{enumerate}
  14167. \item parameter passing,
  14168. \item pushing frames on the procedure call stack and popping them off,
  14169. or
  14170. \item determining how registers are shared by different functions.
  14171. \end{enumerate}
  14172. Regarding parameter passing, recall that the x86-64 calling
  14173. convention for Unix-based systems uses the following six registers to
  14174. pass arguments to a function, in the given order:
  14175. \begin{lstlisting}
  14176. rdi rsi rdx rcx r8 r9
  14177. \end{lstlisting}
  14178. If there are more than six arguments, then the calling convention
  14179. mandates using space on the frame of the caller for the rest of the
  14180. arguments. However, to ease the implementation of efficient tail calls
  14181. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14182. arguments.
  14183. %
  14184. The return value of the function is stored in register \code{rax}.
  14185. Regarding frames \index{subject}{frame} and the procedure call stack,
  14186. \index{subject}{procedure call stack} recall from
  14187. section~\ref{sec:x86} that the stack grows down and each function call
  14188. uses a chunk of space on the stack called a frame. The caller sets the
  14189. stack pointer, register \code{rsp}, to the last data item in its
  14190. frame. The callee must not change anything in the caller's frame, that
  14191. is, anything that is at or above the stack pointer. The callee is free
  14192. to use locations that are below the stack pointer.
  14193. Recall that we store variables of tuple type on the root stack. So,
  14194. the prelude\index{subject}{prelude} of a function needs to move the
  14195. root stack pointer \code{r15} up according to the number of variables
  14196. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14197. move the root stack pointer back down. Also, the prelude must
  14198. initialize to \code{0} this frame's slots in the root stack to signal
  14199. to the garbage collector that those slots do not yet contain a valid
  14200. pointer. Otherwise the garbage collector will interpret the garbage
  14201. bits in those slots as memory addresses and try to traverse them,
  14202. causing serious mayhem!
  14203. Regarding the sharing of registers between different functions, recall
  14204. from section~\ref{sec:calling-conventions} that the registers are
  14205. divided into two groups, the caller-saved registers and the
  14206. callee-saved registers. The caller should assume that all the
  14207. caller-saved registers are overwritten with arbitrary values by the
  14208. callee. For that reason we recommend in
  14209. section~\ref{sec:calling-conventions} that variables that are live
  14210. during a function call should not be assigned to caller-saved
  14211. registers.
  14212. On the flip side, if the callee wants to use a callee-saved register,
  14213. the callee must save the contents of those registers on their stack
  14214. frame and then put them back prior to returning to the caller. For
  14215. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14216. the register allocator assigns a variable to a callee-saved register,
  14217. then the prelude of the \code{main} function must save that register
  14218. to the stack and the conclusion of \code{main} must restore it. This
  14219. recommendation now generalizes to all functions.
  14220. Recall that the base pointer, register \code{rbp}, is used as a
  14221. point of reference within a frame, so that each local variable can be
  14222. accessed at a fixed offset from the base pointer
  14223. (section~\ref{sec:x86}).
  14224. %
  14225. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14226. frames.
  14227. \begin{figure}[tbp]
  14228. \centering
  14229. \begin{tcolorbox}[colback=white]
  14230. \begin{tabular}{r|r|l|l} \hline
  14231. Caller View & Callee View & Contents & Frame \\ \hline
  14232. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14233. 0(\key{\%rbp}) & & old \key{rbp} \\
  14234. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14235. \ldots & & \ldots \\
  14236. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14237. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14238. \ldots & & \ldots \\
  14239. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14240. %% & & \\
  14241. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14242. %% & \ldots & \ldots \\
  14243. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14244. \hline
  14245. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14246. & 0(\key{\%rbp}) & old \key{rbp} \\
  14247. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14248. & \ldots & \ldots \\
  14249. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14250. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14251. & \ldots & \ldots \\
  14252. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14253. \end{tabular}
  14254. \end{tcolorbox}
  14255. \caption{Memory layout of caller and callee frames.}
  14256. \label{fig:call-frames}
  14257. \end{figure}
  14258. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14259. %% local variables and for storing the values of callee-saved registers
  14260. %% (we shall refer to all of these collectively as ``locals''), and that
  14261. %% at the beginning of a function we move the stack pointer \code{rsp}
  14262. %% down to make room for them.
  14263. %% We recommend storing the local variables
  14264. %% first and then the callee-saved registers, so that the local variables
  14265. %% can be accessed using \code{rbp} the same as before the addition of
  14266. %% functions.
  14267. %% To make additional room for passing arguments, we shall
  14268. %% move the stack pointer even further down. We count how many stack
  14269. %% arguments are needed for each function call that occurs inside the
  14270. %% body of the function and find their maximum. Adding this number to the
  14271. %% number of locals gives us how much the \code{rsp} should be moved at
  14272. %% the beginning of the function. In preparation for a function call, we
  14273. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14274. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14275. %% so on.
  14276. %% Upon calling the function, the stack arguments are retrieved by the
  14277. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14278. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14279. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14280. %% the layout of the caller and callee frames. Notice how important it is
  14281. %% that we correctly compute the maximum number of arguments needed for
  14282. %% function calls; if that number is too small then the arguments and
  14283. %% local variables will smash into each other!
  14284. \subsection{Efficient Tail Calls}
  14285. \label{sec:tail-call}
  14286. In general, the amount of stack space used by a program is determined
  14287. by the longest chain of nested function calls. That is, if function
  14288. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14289. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14290. large if functions are recursive. However, in some cases we can
  14291. arrange to use only a constant amount of space for a long chain of
  14292. nested function calls.
  14293. A \emph{tail call}\index{subject}{tail call} is a function call that
  14294. happens as the last action in a function body. For example, in the
  14295. following program, the recursive call to \code{tail\_sum} is a tail
  14296. call:
  14297. \begin{center}
  14298. {\if\edition\racketEd
  14299. \begin{lstlisting}
  14300. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14301. (if (eq? n 0)
  14302. r
  14303. (tail_sum (- n 1) (+ n r))))
  14304. (+ (tail_sum 3 0) 36)
  14305. \end{lstlisting}
  14306. \fi}
  14307. {\if\edition\pythonEd\pythonColor
  14308. \begin{lstlisting}
  14309. def tail_sum(n : int, r : int) -> int:
  14310. if n == 0:
  14311. return r
  14312. else:
  14313. return tail_sum(n - 1, n + r)
  14314. print(tail_sum(3, 0) + 36)
  14315. \end{lstlisting}
  14316. \fi}
  14317. \end{center}
  14318. At a tail call, the frame of the caller is no longer needed, so we can
  14319. pop the caller's frame before making the tail
  14320. call. \index{subject}{frame} With this approach, a recursive function
  14321. that makes only tail calls ends up using a constant amount of stack
  14322. space. \racket{Functional languages like Racket rely heavily on
  14323. recursive functions, so the definition of Racket \emph{requires}
  14324. that all tail calls be optimized in this way.}
  14325. Some care is needed with regard to argument passing in tail calls. As
  14326. mentioned, for arguments beyond the sixth, the convention is to use
  14327. space in the caller's frame for passing arguments. However, for a
  14328. tail call we pop the caller's frame and can no longer use it. An
  14329. alternative is to use space in the callee's frame for passing
  14330. arguments. However, this option is also problematic because the caller
  14331. and callee's frames overlap in memory. As we begin to copy the
  14332. arguments from their sources in the caller's frame, the target
  14333. locations in the callee's frame might collide with the sources for
  14334. later arguments! We solve this problem by using the heap instead of
  14335. the stack for passing more than six arguments
  14336. (section~\ref{sec:limit-functions-r4}).
  14337. As mentioned, for a tail call we pop the caller's frame prior to
  14338. making the tail call. The instructions for popping a frame are the
  14339. instructions that we usually place in the conclusion of a
  14340. function. Thus, we also need to place such code immediately before
  14341. each tail call. These instructions include restoring the callee-saved
  14342. registers, so it is fortunate that the argument passing registers are
  14343. all caller-saved registers.
  14344. One note remains regarding which instruction to use to make the tail
  14345. call. When the callee is finished, it should not return to the current
  14346. function but instead return to the function that called the current
  14347. one. Thus, the return address that is already on the stack is the
  14348. right one, and we should not use \key{callq} to make the tail call
  14349. because that would overwrite the return address. Instead we simply use
  14350. the \key{jmp} instruction. As with the indirect function call, we write
  14351. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14352. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14353. jump target because the conclusion can overwrite just about everything
  14354. else.
  14355. \begin{lstlisting}
  14356. jmp *%rax
  14357. \end{lstlisting}
  14358. \section{Shrink \LangFun{}}
  14359. \label{sec:shrink-r4}
  14360. The \code{shrink} pass performs a minor modification to ease the
  14361. later passes. This pass introduces an explicit \code{main} function
  14362. that gobbles up all the top-level statements of the module.
  14363. %
  14364. \racket{It also changes the top \code{ProgramDefsExp} form to
  14365. \code{ProgramDefs}.}
  14366. {\if\edition\racketEd
  14367. \begin{lstlisting}
  14368. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14369. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14370. \end{lstlisting}
  14371. where $\itm{mainDef}$ is
  14372. \begin{lstlisting}
  14373. (Def 'main '() 'Integer '() |$\Exp'$|)
  14374. \end{lstlisting}
  14375. \fi}
  14376. {\if\edition\pythonEd\pythonColor
  14377. \begin{lstlisting}
  14378. Module(|$\Def\ldots\Stmt\ldots$|)
  14379. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14380. \end{lstlisting}
  14381. where $\itm{mainDef}$ is
  14382. \begin{lstlisting}
  14383. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14384. \end{lstlisting}
  14385. \fi}
  14386. \section{Reveal Functions and the \LangFunRef{} Language}
  14387. \label{sec:reveal-functions-r4}
  14388. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14389. in that it conflates the use of function names and local
  14390. variables. This is a problem because we need to compile the use of a
  14391. function name differently from the use of a local variable. In
  14392. particular, we use \code{leaq} to convert the function name (a label
  14393. in x86) to an address in a register. Thus, we create a new pass that
  14394. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14395. $n$ is the arity of the function.\python{\footnote{The arity is not
  14396. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14397. This pass is named \code{reveal\_functions} and the output language
  14398. is \LangFunRef{}.
  14399. %is defined in figure~\ref{fig:f1-syntax}.
  14400. %% The concrete syntax for a
  14401. %% function reference is $\CFUNREF{f}$.
  14402. %% \begin{figure}[tp]
  14403. %% \centering
  14404. %% \fbox{
  14405. %% \begin{minipage}{0.96\textwidth}
  14406. %% {\if\edition\racketEd
  14407. %% \[
  14408. %% \begin{array}{lcl}
  14409. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14410. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14411. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14412. %% \end{array}
  14413. %% \]
  14414. %% \fi}
  14415. %% {\if\edition\pythonEd\pythonColor
  14416. %% \[
  14417. %% \begin{array}{lcl}
  14418. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14419. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14420. %% \end{array}
  14421. %% \]
  14422. %% \fi}
  14423. %% \end{minipage}
  14424. %% }
  14425. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14426. %% (figure~\ref{fig:Lfun-syntax}).}
  14427. %% \label{fig:f1-syntax}
  14428. %% \end{figure}
  14429. %% Distinguishing between calls in tail position and non-tail position
  14430. %% requires the pass to have some notion of context. We recommend using
  14431. %% two mutually recursive functions, one for processing expressions in
  14432. %% tail position and another for the rest.
  14433. \racket{Placing this pass after \code{uniquify} will make sure that
  14434. there are no local variables and functions that share the same
  14435. name.}
  14436. %
  14437. The \code{reveal\_functions} pass should come before the
  14438. \code{remove\_complex\_operands} pass because function references
  14439. should be categorized as complex expressions.
  14440. \section{Limit Functions}
  14441. \label{sec:limit-functions-r4}
  14442. Recall that we wish to limit the number of function parameters to six
  14443. so that we do not need to use the stack for argument passing, which
  14444. makes it easier to implement efficient tail calls. However, because
  14445. the input language \LangFun{} supports arbitrary numbers of function
  14446. arguments, we have some work to do! The \code{limit\_functions} pass
  14447. transforms functions and function calls that involve more than six
  14448. arguments to pass the first five arguments as usual, but it packs the
  14449. rest of the arguments into a tuple and passes it as the sixth
  14450. argument.\footnote{The implementation this pass can be postponed to
  14451. last because you can test the rest of the passes on functions with
  14452. six or fewer parameters.}
  14453. Each function definition with seven or more parameters is transformed as
  14454. follows:
  14455. {\if\edition\racketEd
  14456. \begin{lstlisting}
  14457. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14458. |$\Rightarrow$|
  14459. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14460. \end{lstlisting}
  14461. \fi}
  14462. {\if\edition\pythonEd\pythonColor
  14463. \begin{lstlisting}
  14464. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14465. |$\Rightarrow$|
  14466. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14467. |$T_r$|, None, |$\itm{body}'$|, None)
  14468. \end{lstlisting}
  14469. \fi}
  14470. %
  14471. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14472. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14473. the $k$th element of the tuple, where $k = i - 6$.
  14474. %
  14475. {\if\edition\racketEd
  14476. \begin{lstlisting}
  14477. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14478. \end{lstlisting}
  14479. \fi}
  14480. {\if\edition\pythonEd\pythonColor
  14481. \begin{lstlisting}
  14482. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14483. \end{lstlisting}
  14484. \fi}
  14485. For function calls with too many arguments, the \code{limit\_functions}
  14486. pass transforms them in the following way:
  14487. \begin{tabular}{lll}
  14488. \begin{minipage}{0.3\textwidth}
  14489. {\if\edition\racketEd
  14490. \begin{lstlisting}
  14491. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14492. \end{lstlisting}
  14493. \fi}
  14494. {\if\edition\pythonEd\pythonColor
  14495. \begin{lstlisting}
  14496. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14497. \end{lstlisting}
  14498. \fi}
  14499. \end{minipage}
  14500. &
  14501. $\Rightarrow$
  14502. &
  14503. \begin{minipage}{0.5\textwidth}
  14504. {\if\edition\racketEd
  14505. \begin{lstlisting}
  14506. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14507. \end{lstlisting}
  14508. \fi}
  14509. {\if\edition\pythonEd\pythonColor
  14510. \begin{lstlisting}
  14511. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14512. \end{lstlisting}
  14513. \fi}
  14514. \end{minipage}
  14515. \end{tabular}
  14516. \section{Remove Complex Operands}
  14517. \label{sec:rco-r4}
  14518. The primary decisions to make for this pass are whether to classify
  14519. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14520. atomic or complex expressions. Recall that an atomic expression
  14521. ends up as an immediate argument of an x86 instruction. Function
  14522. application translates to a sequence of instructions, so
  14523. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14524. a complex expression. On the other hand, the arguments of
  14525. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14526. expressions.
  14527. %
  14528. Regarding \code{FunRef}, as discussed previously, the function label
  14529. needs to be converted to an address using the \code{leaq}
  14530. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14531. needs to be classified as a complex expression so that we generate an
  14532. assignment statement with a left-hand side that can serve as the
  14533. target of the \code{leaq}.
  14534. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14535. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14536. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14537. and augments programs to include a list of function definitions.
  14538. %
  14539. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14540. \newcommand{\LfunMonadASTRacket}{
  14541. \begin{array}{lcl}
  14542. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14543. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14544. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14545. \end{array}
  14546. }
  14547. \newcommand{\LfunMonadASTPython}{
  14548. \begin{array}{lcl}
  14549. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14550. \MID \key{TupleType}\LS\Type^+\RS\\
  14551. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14552. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14553. \Stmt &::=& \RETURN{\Exp} \\
  14554. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14555. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14556. \end{array}
  14557. }
  14558. \begin{figure}[tp]
  14559. \centering
  14560. \begin{tcolorbox}[colback=white]
  14561. \footnotesize
  14562. {\if\edition\racketEd
  14563. \[
  14564. \begin{array}{l}
  14565. \gray{\LvarMonadASTRacket} \\ \hline
  14566. \gray{\LifMonadASTRacket} \\ \hline
  14567. \gray{\LwhileMonadASTRacket} \\ \hline
  14568. \gray{\LtupMonadASTRacket} \\ \hline
  14569. \LfunMonadASTRacket \\
  14570. \begin{array}{rcl}
  14571. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14572. \end{array}
  14573. \end{array}
  14574. \]
  14575. \fi}
  14576. {\if\edition\pythonEd\pythonColor
  14577. \[
  14578. \begin{array}{l}
  14579. \gray{\LvarMonadASTPython} \\ \hline
  14580. \gray{\LifMonadASTPython} \\ \hline
  14581. \gray{\LwhileMonadASTPython} \\ \hline
  14582. \gray{\LtupMonadASTPython} \\ \hline
  14583. \LfunMonadASTPython \\
  14584. \begin{array}{rcl}
  14585. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14586. \end{array}
  14587. \end{array}
  14588. \]
  14589. \fi}
  14590. \end{tcolorbox}
  14591. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14592. \label{fig:Lfun-anf-syntax}
  14593. \end{figure}
  14594. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14595. %% \LangFunANF{} of this pass.
  14596. %% \begin{figure}[tp]
  14597. %% \centering
  14598. %% \fbox{
  14599. %% \begin{minipage}{0.96\textwidth}
  14600. %% \small
  14601. %% \[
  14602. %% \begin{array}{rcl}
  14603. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14604. %% \MID \VOID{} } \\
  14605. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14606. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14607. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14608. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14609. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14610. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14611. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14612. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14613. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14614. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14615. %% \end{array}
  14616. %% \]
  14617. %% \end{minipage}
  14618. %% }
  14619. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14620. %% \label{fig:Lfun-anf-syntax}
  14621. %% \end{figure}
  14622. \section{Explicate Control and the \LangCFun{} Language}
  14623. \label{sec:explicate-control-r4}
  14624. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14625. output of \code{explicate\_control}.
  14626. %
  14627. %% \racket{(The concrete syntax is given in
  14628. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14629. %
  14630. The auxiliary functions for assignment\racket{ and tail contexts} should
  14631. be updated with cases for
  14632. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14633. function for predicate context should be updated for
  14634. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14635. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14636. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14637. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14638. auxiliary function for processing function definitions. This code is
  14639. similar to the case for \code{Program} in \LangVec{}. The top-level
  14640. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14641. form of \LangFun{} can then apply this new function to all the
  14642. function definitions.
  14643. {\if\edition\pythonEd\pythonColor
  14644. The translation of \code{Return} statements requires a new auxiliary
  14645. function to handle expressions in tail context, called
  14646. \code{explicate\_tail}. The function should take an expression and the
  14647. dictionary of basic blocks and produce a list of statements in the
  14648. \LangCFun{} language. The \code{explicate\_tail} function should
  14649. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14650. and a default case for other kinds of expressions. The default case
  14651. should produce a \code{Return} statement. The case for \code{Call}
  14652. should change it into \code{TailCall}. The other cases should
  14653. recursively process their subexpressions and statements, choosing the
  14654. appropriate explicate functions for the various contexts.
  14655. \fi}
  14656. \newcommand{\CfunASTRacket}{
  14657. \begin{array}{lcl}
  14658. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14659. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14660. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14661. \end{array}
  14662. }
  14663. \newcommand{\CfunASTPython}{
  14664. \begin{array}{lcl}
  14665. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14666. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14667. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14668. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14669. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14670. \end{array}
  14671. }
  14672. \begin{figure}[tp]
  14673. \begin{tcolorbox}[colback=white]
  14674. \footnotesize
  14675. {\if\edition\racketEd
  14676. \[
  14677. \begin{array}{l}
  14678. \gray{\CvarASTRacket} \\ \hline
  14679. \gray{\CifASTRacket} \\ \hline
  14680. \gray{\CloopASTRacket} \\ \hline
  14681. \gray{\CtupASTRacket} \\ \hline
  14682. \CfunASTRacket \\
  14683. \begin{array}{lcl}
  14684. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14685. \end{array}
  14686. \end{array}
  14687. \]
  14688. \fi}
  14689. {\if\edition\pythonEd\pythonColor
  14690. \[
  14691. \begin{array}{l}
  14692. \gray{\CifASTPython} \\ \hline
  14693. \gray{\CtupASTPython} \\ \hline
  14694. \CfunASTPython \\
  14695. \begin{array}{lcl}
  14696. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14697. \end{array}
  14698. \end{array}
  14699. \]
  14700. \fi}
  14701. \end{tcolorbox}
  14702. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14703. \label{fig:c3-syntax}
  14704. \end{figure}
  14705. \clearpage
  14706. \section{Select Instructions and the \LangXIndCall{} Language}
  14707. \label{sec:select-r4}
  14708. \index{subject}{select instructions}
  14709. The output of select instructions is a program in the \LangXIndCall{}
  14710. language; the definition of its concrete syntax is shown in
  14711. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14712. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14713. directive on the labels of function definitions to make sure the
  14714. bottom three bits are zero, which we put to use in
  14715. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14716. this section. \index{subject}{x86}
  14717. \newcommand{\GrammarXIndCall}{
  14718. \begin{array}{lcl}
  14719. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14720. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14721. \Block &::= & \Instr^{+} \\
  14722. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14723. \end{array}
  14724. }
  14725. \newcommand{\ASTXIndCallRacket}{
  14726. \begin{array}{lcl}
  14727. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14728. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14729. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14730. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14731. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14732. \end{array}
  14733. }
  14734. \begin{figure}[tp]
  14735. \begin{tcolorbox}[colback=white]
  14736. \small
  14737. \[
  14738. \begin{array}{l}
  14739. \gray{\GrammarXInt} \\ \hline
  14740. \gray{\GrammarXIf} \\ \hline
  14741. \gray{\GrammarXGlobal} \\ \hline
  14742. \GrammarXIndCall \\
  14743. \begin{array}{lcl}
  14744. \LangXIndCallM{} &::= & \Def^{*}
  14745. \end{array}
  14746. \end{array}
  14747. \]
  14748. \end{tcolorbox}
  14749. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14750. \label{fig:x86-3-concrete}
  14751. \end{figure}
  14752. \begin{figure}[tp]
  14753. \begin{tcolorbox}[colback=white]
  14754. \small
  14755. {\if\edition\racketEd
  14756. \[\arraycolsep=3pt
  14757. \begin{array}{l}
  14758. \gray{\ASTXIntRacket} \\ \hline
  14759. \gray{\ASTXIfRacket} \\ \hline
  14760. \gray{\ASTXGlobalRacket} \\ \hline
  14761. \ASTXIndCallRacket \\
  14762. \begin{array}{lcl}
  14763. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14764. \end{array}
  14765. \end{array}
  14766. \]
  14767. \fi}
  14768. {\if\edition\pythonEd\pythonColor
  14769. \[
  14770. \begin{array}{lcl}
  14771. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14772. \MID \BYTEREG{\Reg} } \\
  14773. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14774. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14775. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14776. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14777. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14778. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14779. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14780. \end{array}
  14781. \]
  14782. \fi}
  14783. \end{tcolorbox}
  14784. \caption{The abstract syntax of \LangXIndCall{} (extends
  14785. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14786. \label{fig:x86-3}
  14787. \end{figure}
  14788. An assignment of a function reference to a variable becomes a
  14789. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14790. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14791. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14792. node, whose concrete syntax is instruction-pointer-relative
  14793. addressing.
  14794. \begin{center}
  14795. \begin{tabular}{lcl}
  14796. \begin{minipage}{0.35\textwidth}
  14797. {\if\edition\racketEd
  14798. \begin{lstlisting}
  14799. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14800. \end{lstlisting}
  14801. \fi}
  14802. {\if\edition\pythonEd\pythonColor
  14803. \begin{lstlisting}
  14804. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14805. \end{lstlisting}
  14806. \fi}
  14807. \end{minipage}
  14808. &
  14809. $\Rightarrow$\qquad\qquad
  14810. &
  14811. \begin{minipage}{0.3\textwidth}
  14812. \begin{lstlisting}
  14813. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14814. \end{lstlisting}
  14815. \end{minipage}
  14816. \end{tabular}
  14817. \end{center}
  14818. Regarding function definitions, we need to remove the parameters and
  14819. instead perform parameter passing using the conventions discussed in
  14820. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14821. registers. We recommend turning the parameters into local variables
  14822. and generating instructions at the beginning of the function to move
  14823. from the argument-passing registers
  14824. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14825. {\if\edition\racketEd
  14826. \begin{lstlisting}
  14827. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14828. |$\Rightarrow$|
  14829. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14830. \end{lstlisting}
  14831. \fi}
  14832. {\if\edition\pythonEd\pythonColor
  14833. \begin{lstlisting}
  14834. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14835. |$\Rightarrow$|
  14836. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14837. \end{lstlisting}
  14838. \fi}
  14839. The basic blocks $B'$ are the same as $B$ except that the
  14840. \code{start} block is modified to add the instructions for moving from
  14841. the argument registers to the parameter variables. So the \code{start}
  14842. block of $B$ shown on the left of the following is changed to the code
  14843. on the right:
  14844. \begin{center}
  14845. \begin{minipage}{0.3\textwidth}
  14846. \begin{lstlisting}
  14847. start:
  14848. |$\itm{instr}_1$|
  14849. |$\cdots$|
  14850. |$\itm{instr}_n$|
  14851. \end{lstlisting}
  14852. \end{minipage}
  14853. $\Rightarrow$
  14854. \begin{minipage}{0.3\textwidth}
  14855. \begin{lstlisting}
  14856. |$f$|start:
  14857. movq %rdi, |$x_1$|
  14858. movq %rsi, |$x_2$|
  14859. |$\cdots$|
  14860. |$\itm{instr}_1$|
  14861. |$\cdots$|
  14862. |$\itm{instr}_n$|
  14863. \end{lstlisting}
  14864. \end{minipage}
  14865. \end{center}
  14866. Recall that we use the label \code{start} for the initial block of a
  14867. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14868. the conclusion of the program with \code{conclusion}, so that
  14869. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14870. by a jump to \code{conclusion}. With the addition of function
  14871. definitions, there is a start block and conclusion for each function,
  14872. but their labels need to be unique. We recommend prepending the
  14873. function's name to \code{start} and \code{conclusion}, respectively,
  14874. to obtain unique labels.
  14875. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14876. number of parameters the function expects, but the parameters are no
  14877. longer in the syntax of function definitions. Instead, add an entry
  14878. to $\itm{info}$ that maps \code{num-params} to the number of
  14879. parameters to construct $\itm{info}'$.}
  14880. By changing the parameters to local variables, we are giving the
  14881. register allocator control over which registers or stack locations to
  14882. use for them. If you implement the move-biasing challenge
  14883. (section~\ref{sec:move-biasing}), the register allocator will try to
  14884. assign the parameter variables to the corresponding argument register,
  14885. in which case the \code{patch\_instructions} pass will remove the
  14886. \code{movq} instruction. This happens in the example translation given
  14887. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14888. the \code{add} function.
  14889. %
  14890. Also, note that the register allocator will perform liveness analysis
  14891. on this sequence of move instructions and build the interference
  14892. graph. So, for example, $x_1$ will be marked as interfering with
  14893. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14894. which is good because otherwise the first \code{movq} would overwrite
  14895. the argument in \code{rsi} that is needed for $x_2$.
  14896. Next, consider the compilation of function calls. In the mirror image
  14897. of the handling of parameters in function definitions, the arguments
  14898. are moved to the argument-passing registers. Note that the function
  14899. is not given as a label, but its address is produced by the argument
  14900. $\itm{arg}_0$. So, we translate the call into an indirect function
  14901. call. The return value from the function is stored in \code{rax}, so
  14902. it needs to be moved into the \itm{lhs}.
  14903. \begin{lstlisting}
  14904. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14905. |$\Rightarrow$|
  14906. movq |$\itm{arg}_1$|, %rdi
  14907. movq |$\itm{arg}_2$|, %rsi
  14908. |$\vdots$|
  14909. callq *|$\itm{arg}_0$|
  14910. movq %rax, |$\itm{lhs}$|
  14911. \end{lstlisting}
  14912. The \code{IndirectCallq} AST node includes an integer for the arity of
  14913. the function, that is, the number of parameters. That information is
  14914. useful in the \code{uncover\_live} pass for determining which
  14915. argument-passing registers are potentially read during the call.
  14916. For tail calls, the parameter passing is the same as non-tail calls:
  14917. generate instructions to move the arguments into the argument-passing
  14918. registers. After that we need to pop the frame from the procedure
  14919. call stack. However, we do not yet know how big the frame is; that
  14920. gets determined during register allocation. So, instead of generating
  14921. those instructions here, we invent a new instruction that means ``pop
  14922. the frame and then do an indirect jump,'' which we name
  14923. \code{TailJmp}. The abstract syntax for this instruction includes an
  14924. argument that specifies where to jump and an integer that represents
  14925. the arity of the function being called.
  14926. \section{Register Allocation}
  14927. \label{sec:register-allocation-r4}
  14928. The addition of functions requires some changes to all three aspects
  14929. of register allocation, which we discuss in the following subsections.
  14930. \subsection{Liveness Analysis}
  14931. \label{sec:liveness-analysis-r4}
  14932. \index{subject}{liveness analysis}
  14933. %% The rest of the passes need only minor modifications to handle the new
  14934. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14935. %% \code{leaq}.
  14936. The \code{IndirectCallq} instruction should be treated like
  14937. \code{Callq} regarding its written locations $W$, in that they should
  14938. include all the caller-saved registers. Recall that the reason for
  14939. that is to force variables that are live across a function call to be assigned to callee-saved
  14940. registers or to be spilled to the stack.
  14941. Regarding the set of read locations $R$, the arity fields of
  14942. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14943. argument-passing registers should be considered as read by those
  14944. instructions. Also, the target field of \code{TailJmp} and
  14945. \code{IndirectCallq} should be included in the set of read locations
  14946. $R$.
  14947. \subsection{Build Interference Graph}
  14948. \label{sec:build-interference-r4}
  14949. With the addition of function definitions, we compute a separate interference
  14950. graph for each function (not just one for the whole program).
  14951. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14952. spill tuple-typed variables that are live during a call to
  14953. \code{collect}, the garbage collector. With the addition of functions
  14954. to our language, we need to revisit this issue. Functions that perform
  14955. allocation contain calls to the collector. Thus, we should not only
  14956. spill a tuple-typed variable when it is live during a call to
  14957. \code{collect}, but we should spill the variable if it is live during
  14958. a call to any user-defined function. Thus, in the
  14959. \code{build\_interference} pass, we recommend adding interference
  14960. edges between call-live tuple-typed variables and the callee-saved
  14961. registers (in addition to creating edges between
  14962. call-live variables and the caller-saved registers).
  14963. \subsection{Allocate Registers}
  14964. The primary change to the \code{allocate\_registers} pass is adding an
  14965. auxiliary function for handling definitions (the \Def{} nonterminal
  14966. shown in figure~\ref{fig:x86-3}) with one case for function
  14967. definitions. The logic is the same as described in
  14968. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14969. allocation is performed many times, once for each function definition,
  14970. instead of just once for the whole program.
  14971. \section{Patch Instructions}
  14972. In \code{patch\_instructions}, you should deal with the x86
  14973. idiosyncrasy that the destination argument of \code{leaq} must be a
  14974. register. Additionally, you should ensure that the argument of
  14975. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14976. trample many other registers before the tail call, as explained in the
  14977. next section.
  14978. \section{Generate Prelude and Conclusion}
  14979. Now that register allocation is complete, we can translate the
  14980. \code{TailJmp} into a sequence of instructions. A naive translation of
  14981. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14982. before the jump we need to pop the current frame to achieve efficient
  14983. tail calls. This sequence of instructions is the same as the code for
  14984. the conclusion of a function, except that the \code{retq} is replaced with
  14985. \code{jmp *$\itm{arg}$}.
  14986. Regarding function definitions, we generate a prelude and conclusion
  14987. for each one. This code is similar to the prelude and conclusion
  14988. generated for the \code{main} function presented in
  14989. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14990. carry out the following steps:
  14991. % TODO: .align the functions!
  14992. \begin{enumerate}
  14993. %% \item Start with \code{.global} and \code{.align} directives followed
  14994. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14995. %% example.)
  14996. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14997. pointer.
  14998. \item Push to the stack all the callee-saved registers that were
  14999. used for register allocation.
  15000. \item Move the stack pointer \code{rsp} down to make room for the
  15001. regular spills (aligned to 16 bytes).
  15002. \item Move the root stack pointer \code{r15} up by the size of the
  15003. root-stack frame for this function, which depends on the number of
  15004. spilled tuple-typed variables. \label{root-stack-init}
  15005. \item Initialize to zero all new entries in the root-stack frame.
  15006. \item Jump to the start block.
  15007. \end{enumerate}
  15008. The prelude of the \code{main} function has an additional task: call
  15009. the \code{initialize} function to set up the garbage collector, and
  15010. then move the value of the global \code{rootstack\_begin} in
  15011. \code{r15}. This initialization should happen before step
  15012. \ref{root-stack-init}, which depends on \code{r15}.
  15013. The conclusion of every function should do the following:
  15014. \begin{enumerate}
  15015. \item Move the stack pointer back up past the regular spills.
  15016. \item Restore the callee-saved registers by popping them from the
  15017. stack.
  15018. \item Move the root stack pointer back down by the size of the
  15019. root-stack frame for this function.
  15020. \item Restore \code{rbp} by popping it from the stack.
  15021. \item Return to the caller with the \code{retq} instruction.
  15022. \end{enumerate}
  15023. The output of this pass is \LangXIndCallFlat{}, which differs from
  15024. \LangXIndCall{} in that there is no longer an AST node for function
  15025. definitions. Instead, a program is just
  15026. \racket{an association list}\python{dictionary}
  15027. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15028. {\if\edition\racketEd
  15029. \[
  15030. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15031. \]
  15032. \fi}
  15033. {\if\edition\pythonEd
  15034. \[
  15035. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15036. \]
  15037. \fi}
  15038. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15039. compiling \LangFun{} to x86.
  15040. \begin{exercise}\normalfont\normalsize
  15041. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15042. Create eight new programs that use functions including examples that
  15043. pass functions and return functions from other functions, recursive
  15044. functions, functions that create tuples, and functions that make tail
  15045. calls. Test your compiler on these new programs and all your
  15046. previously created test programs.
  15047. \end{exercise}
  15048. \begin{figure}[tbp]
  15049. \begin{tcolorbox}[colback=white]
  15050. {\if\edition\racketEd
  15051. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15052. \node (Lfun) at (0,2) {\large \LangFun{}};
  15053. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15054. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15055. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15056. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15057. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15058. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15059. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15060. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15061. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15062. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15063. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15064. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15065. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15066. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15067. \path[->,bend left=15] (Lfun) edge [above] node
  15068. {\ttfamily\footnotesize shrink} (Lfun-1);
  15069. \path[->,bend left=15] (Lfun-1) edge [above] node
  15070. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15071. \path[->,bend left=15] (Lfun-2) edge [above] node
  15072. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15073. \path[->,bend left=15] (F1-1) edge [left] node
  15074. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15075. \path[->,bend left=15] (F1-2) edge [below] node
  15076. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15077. \path[->,bend left=15] (F1-3) edge [below] node
  15078. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15079. \path[->,bend right=15] (F1-4) edge [above] node
  15080. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15081. \path[->,bend right=15] (F1-5) edge [right] node
  15082. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15083. \path[->,bend right=15] (C3-2) edge [right] node
  15084. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15085. \path[->,bend left=15] (x86-2) edge [right] node
  15086. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15087. \path[->,bend right=15] (x86-2-1) edge [below] node
  15088. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15089. \path[->,bend right=15] (x86-2-2) edge [right] node
  15090. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15091. \path[->,bend left=15] (x86-3) edge [above] node
  15092. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15093. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15094. \end{tikzpicture}
  15095. \fi}
  15096. {\if\edition\pythonEd\pythonColor
  15097. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15098. \node (Lfun) at (0,2) {\large \LangFun{}};
  15099. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15100. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15101. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15102. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15103. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15104. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15105. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15106. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15107. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15108. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15109. \path[->,bend left=15] (Lfun) edge [above] node
  15110. {\ttfamily\footnotesize shrink} (Lfun-2);
  15111. \path[->,bend left=15] (Lfun-2) edge [above] node
  15112. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15113. \path[->,bend left=15] (F1-1) edge [above] node
  15114. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15115. \path[->,bend left=15] (F1-2) edge [right] node
  15116. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15117. \path[->,bend right=15] (F1-4) edge [above] node
  15118. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15119. \path[->,bend right=15] (F1-5) edge [right] node
  15120. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15121. \path[->,bend left=15] (C3-2) edge [right] node
  15122. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15123. \path[->,bend right=15] (x86-2) edge [below] node
  15124. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15125. \path[->,bend left=15] (x86-3) edge [above] node
  15126. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15127. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15128. \end{tikzpicture}
  15129. \fi}
  15130. \end{tcolorbox}
  15131. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15132. \label{fig:Lfun-passes}
  15133. \end{figure}
  15134. \section{An Example Translation}
  15135. \label{sec:functions-example}
  15136. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15137. function in \LangFun{} to x86. The figure includes the results of
  15138. \code{explicate\_control} and \code{select\_instructions}.
  15139. \begin{figure}[hbtp]
  15140. \begin{tcolorbox}[colback=white]
  15141. \begin{tabular}{ll}
  15142. \begin{minipage}{0.4\textwidth}
  15143. % s3_2.rkt
  15144. {\if\edition\racketEd
  15145. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15146. (define (add [x : Integer]
  15147. [y : Integer])
  15148. : Integer
  15149. (+ x y))
  15150. (add 40 2)
  15151. \end{lstlisting}
  15152. \fi}
  15153. {\if\edition\pythonEd\pythonColor
  15154. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15155. def add(x:int, y:int) -> int:
  15156. return x + y
  15157. print(add(40, 2))
  15158. \end{lstlisting}
  15159. \fi}
  15160. $\Downarrow$
  15161. {\if\edition\racketEd
  15162. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15163. (define (add86 [x87 : Integer]
  15164. [y88 : Integer])
  15165. : Integer
  15166. add86start:
  15167. return (+ x87 y88);
  15168. )
  15169. (define (main) : Integer ()
  15170. mainstart:
  15171. tmp89 = (fun-ref add86 2);
  15172. (tail-call tmp89 40 2)
  15173. )
  15174. \end{lstlisting}
  15175. \fi}
  15176. {\if\edition\pythonEd\pythonColor
  15177. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15178. def add(x:int, y:int) -> int:
  15179. addstart:
  15180. return x + y
  15181. def main() -> int:
  15182. mainstart:
  15183. fun.0 = add
  15184. tmp.1 = fun.0(40, 2)
  15185. print(tmp.1)
  15186. return 0
  15187. \end{lstlisting}
  15188. \fi}
  15189. \end{minipage}
  15190. &
  15191. $\Rightarrow$
  15192. \begin{minipage}{0.5\textwidth}
  15193. {\if\edition\racketEd
  15194. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15195. (define (add86) : Integer
  15196. add86start:
  15197. movq %rdi, x87
  15198. movq %rsi, y88
  15199. movq x87, %rax
  15200. addq y88, %rax
  15201. jmp inc1389conclusion
  15202. )
  15203. (define (main) : Integer
  15204. mainstart:
  15205. leaq (fun-ref add86 2), tmp89
  15206. movq $40, %rdi
  15207. movq $2, %rsi
  15208. tail-jmp tmp89
  15209. )
  15210. \end{lstlisting}
  15211. \fi}
  15212. {\if\edition\pythonEd\pythonColor
  15213. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15214. def add() -> int:
  15215. addstart:
  15216. movq %rdi, x
  15217. movq %rsi, y
  15218. movq x, %rax
  15219. addq y, %rax
  15220. jmp addconclusion
  15221. def main() -> int:
  15222. mainstart:
  15223. leaq add, fun.0
  15224. movq $40, %rdi
  15225. movq $2, %rsi
  15226. callq *fun.0
  15227. movq %rax, tmp.1
  15228. movq tmp.1, %rdi
  15229. callq print_int
  15230. movq $0, %rax
  15231. jmp mainconclusion
  15232. \end{lstlisting}
  15233. \fi}
  15234. $\Downarrow$
  15235. \end{minipage}
  15236. \end{tabular}
  15237. \begin{tabular}{ll}
  15238. \begin{minipage}{0.3\textwidth}
  15239. {\if\edition\racketEd
  15240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15241. .globl add86
  15242. .align 8
  15243. add86:
  15244. pushq %rbp
  15245. movq %rsp, %rbp
  15246. jmp add86start
  15247. add86start:
  15248. movq %rdi, %rax
  15249. addq %rsi, %rax
  15250. jmp add86conclusion
  15251. add86conclusion:
  15252. popq %rbp
  15253. retq
  15254. \end{lstlisting}
  15255. \fi}
  15256. {\if\edition\pythonEd\pythonColor
  15257. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15258. .align 8
  15259. add:
  15260. pushq %rbp
  15261. movq %rsp, %rbp
  15262. subq $0, %rsp
  15263. jmp addstart
  15264. addstart:
  15265. movq %rdi, %rdx
  15266. movq %rsi, %rcx
  15267. movq %rdx, %rax
  15268. addq %rcx, %rax
  15269. jmp addconclusion
  15270. addconclusion:
  15271. subq $0, %r15
  15272. addq $0, %rsp
  15273. popq %rbp
  15274. retq
  15275. \end{lstlisting}
  15276. \fi}
  15277. \end{minipage}
  15278. &
  15279. \begin{minipage}{0.5\textwidth}
  15280. {\if\edition\racketEd
  15281. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15282. .globl main
  15283. .align 8
  15284. main:
  15285. pushq %rbp
  15286. movq %rsp, %rbp
  15287. movq $16384, %rdi
  15288. movq $16384, %rsi
  15289. callq initialize
  15290. movq rootstack_begin(%rip), %r15
  15291. jmp mainstart
  15292. mainstart:
  15293. leaq add86(%rip), %rcx
  15294. movq $40, %rdi
  15295. movq $2, %rsi
  15296. movq %rcx, %rax
  15297. popq %rbp
  15298. jmp *%rax
  15299. mainconclusion:
  15300. popq %rbp
  15301. retq
  15302. \end{lstlisting}
  15303. \fi}
  15304. {\if\edition\pythonEd\pythonColor
  15305. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15306. .globl main
  15307. .align 8
  15308. main:
  15309. pushq %rbp
  15310. movq %rsp, %rbp
  15311. subq $0, %rsp
  15312. movq $65536, %rdi
  15313. movq $65536, %rsi
  15314. callq initialize
  15315. movq rootstack_begin(%rip), %r15
  15316. jmp mainstart
  15317. mainstart:
  15318. leaq add(%rip), %rcx
  15319. movq $40, %rdi
  15320. movq $2, %rsi
  15321. callq *%rcx
  15322. movq %rax, %rcx
  15323. movq %rcx, %rdi
  15324. callq print_int
  15325. movq $0, %rax
  15326. jmp mainconclusion
  15327. mainconclusion:
  15328. subq $0, %r15
  15329. addq $0, %rsp
  15330. popq %rbp
  15331. retq
  15332. \end{lstlisting}
  15333. \fi}
  15334. \end{minipage}
  15335. \end{tabular}
  15336. \end{tcolorbox}
  15337. \caption{Example compilation of a simple function to x86.}
  15338. \label{fig:add-fun}
  15339. \end{figure}
  15340. % Challenge idea: inlining! (simple version)
  15341. % Further Reading
  15342. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15343. \chapter{Lexically Scoped Functions}
  15344. \label{ch:Llambda}
  15345. \setcounter{footnote}{0}
  15346. This chapter studies lexically scoped functions. Lexical
  15347. scoping\index{subject}{lexical scoping} means that a function's body
  15348. may refer to variables whose binding site is outside of the function,
  15349. in an enclosing scope.
  15350. %
  15351. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15352. in \LangLam{}, which extends \LangFun{} with the
  15353. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15354. functions. The body of the \key{lambda} refers to three variables:
  15355. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15356. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15357. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15358. function \code{f}}, and \code{x} is a parameter of function
  15359. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15360. result value. The main expression of the program includes two calls to
  15361. \code{f} with different arguments for \code{x}: first \code{5} and
  15362. then \code{3}. The functions returned from \code{f} are bound to
  15363. variables \code{g} and \code{h}. Even though these two functions were
  15364. created by the same \code{lambda}, they are really different functions
  15365. because they use different values for \code{x}. Applying \code{g} to
  15366. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15367. produces \code{22}, so the result of the program is \code{42}.
  15368. \begin{figure}[btp]
  15369. \begin{tcolorbox}[colback=white]
  15370. {\if\edition\racketEd
  15371. % lambda_test_21.rkt
  15372. \begin{lstlisting}
  15373. (define (f [x : Integer]) : (Integer -> Integer)
  15374. (let ([y 4])
  15375. (lambda: ([z : Integer]) : Integer
  15376. (+ x (+ y z)))))
  15377. (let ([g (f 5)])
  15378. (let ([h (f 3)])
  15379. (+ (g 11) (h 15))))
  15380. \end{lstlisting}
  15381. \fi}
  15382. {\if\edition\pythonEd\pythonColor
  15383. \begin{lstlisting}
  15384. def f(x : int) -> Callable[[int], int]:
  15385. y = 4
  15386. return lambda z: x + y + z
  15387. g = f(5)
  15388. h = f(3)
  15389. print(g(11) + h(15))
  15390. \end{lstlisting}
  15391. \fi}
  15392. \end{tcolorbox}
  15393. \caption{Example of a lexically scoped function.}
  15394. \label{fig:lexical-scoping}
  15395. \end{figure}
  15396. The approach that we take for implementing lexically scoped functions
  15397. is to compile them into top-level function definitions, translating
  15398. from \LangLam{} into \LangFun{}. However, the compiler must give
  15399. special treatment to variable occurrences such as \code{x} and
  15400. \code{y} in the body of the \code{lambda} shown in
  15401. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15402. may not refer to variables defined outside of it. To identify such
  15403. variable occurrences, we review the standard notion of free variable.
  15404. \begin{definition}\normalfont
  15405. A variable is \emph{free in expression} $e$ if the variable occurs
  15406. inside $e$ but does not have an enclosing definition that is also in
  15407. $e$.\index{subject}{free variable}
  15408. \end{definition}
  15409. For example, in the expression
  15410. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15411. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15412. only \code{x} and \code{y} are free in the following expression,
  15413. because \code{z} is defined by the \code{lambda}
  15414. {\if\edition\racketEd
  15415. \begin{lstlisting}
  15416. (lambda: ([z : Integer]) : Integer
  15417. (+ x (+ y z)))
  15418. \end{lstlisting}
  15419. \fi}
  15420. {\if\edition\pythonEd\pythonColor
  15421. \begin{lstlisting}
  15422. lambda z: x + y + z
  15423. \end{lstlisting}
  15424. \fi}
  15425. %
  15426. \noindent Thus the free variables of a \code{lambda} are the ones that
  15427. need special treatment. We need to transport at runtime the values
  15428. of those variables from the point where the \code{lambda} was created
  15429. to the point where the \code{lambda} is applied. An efficient solution
  15430. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15431. values of the free variables together with a function pointer into a
  15432. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15433. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15434. closure}
  15435. %
  15436. By design, we have all the ingredients to make closures:
  15437. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15438. function pointers. The function pointer resides at index $0$, and the
  15439. values for the free variables fill in the rest of the tuple.
  15440. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15441. to see how closures work. It is a three-step dance. The program calls
  15442. function \code{f}, which creates a closure for the \code{lambda}. The
  15443. closure is a tuple whose first element is a pointer to the top-level
  15444. function that we will generate for the \code{lambda}; the second
  15445. element is the value of \code{x}, which is \code{5}; and the third
  15446. element is \code{4}, the value of \code{y}. The closure does not
  15447. contain an element for \code{z} because \code{z} is not a free
  15448. variable of the \code{lambda}. Creating the closure is step 1 of the
  15449. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15450. shown in figure~\ref{fig:closures}.
  15451. %
  15452. The second call to \code{f} creates another closure, this time with
  15453. \code{3} in the second slot (for \code{x}). This closure is also
  15454. returned from \code{f} but bound to \code{h}, which is also shown in
  15455. figure~\ref{fig:closures}.
  15456. \begin{figure}[tbp]
  15457. \centering
  15458. \begin{minipage}{0.65\textwidth}
  15459. \begin{tcolorbox}[colback=white]
  15460. \includegraphics[width=\textwidth]{figs/closures}
  15461. \end{tcolorbox}
  15462. \end{minipage}
  15463. \caption{Flat closure representations for the two functions
  15464. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15465. \label{fig:closures}
  15466. \end{figure}
  15467. Continuing with the example, consider the application of \code{g} to
  15468. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15469. closure, we obtain the function pointer from the first element of the
  15470. closure and call it, passing in the closure itself and then the
  15471. regular arguments, in this case \code{11}. This technique for applying
  15472. a closure is step 2 of the dance.
  15473. %
  15474. But doesn't this \code{lambda} take only one argument, for parameter
  15475. \code{z}? The third and final step of the dance is generating a
  15476. top-level function for a \code{lambda}. We add an additional
  15477. parameter for the closure and insert an initialization at the beginning
  15478. of the function for each free variable, to bind those variables to the
  15479. appropriate elements from the closure parameter.
  15480. %
  15481. This three-step dance is known as \emph{closure
  15482. conversion}\index{subject}{closure conversion}. We discuss the
  15483. details of closure conversion in section~\ref{sec:closure-conversion}
  15484. and show the code generated from the example in
  15485. section~\ref{sec:example-lambda}. First, we define the syntax and
  15486. semantics of \LangLam{} in section~\ref{sec:r5}.
  15487. \section{The \LangLam{} Language}
  15488. \label{sec:r5}
  15489. The definitions of the concrete syntax and abstract syntax for
  15490. \LangLam{}, a language with anonymous functions and lexical scoping,
  15491. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15492. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15493. for \LangFun{}, which already has syntax for function application.
  15494. %
  15495. \python{The syntax also includes an assignment statement that includes
  15496. a type annotation for the variable on the left-hand side, which
  15497. facilitates the type checking of \code{lambda} expressions that we
  15498. discuss later in this section.}
  15499. %
  15500. \racket{The \code{procedure-arity} operation returns the number of parameters
  15501. of a given function, an operation that we need for the translation
  15502. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15503. %
  15504. \python{The \code{arity} operation returns the number of parameters of
  15505. a given function, an operation that we need for the translation
  15506. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15507. The \code{arity} operation is not in Python, but the same functionality
  15508. is available in a more complex form. We include \code{arity} in the
  15509. \LangLam{} source language to enable testing.}
  15510. \newcommand{\LlambdaGrammarRacket}{
  15511. \begin{array}{lcl}
  15512. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15513. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15514. \end{array}
  15515. }
  15516. \newcommand{\LlambdaASTRacket}{
  15517. \begin{array}{lcl}
  15518. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15519. \itm{op} &::=& \code{procedure-arity}
  15520. \end{array}
  15521. }
  15522. \newcommand{\LlambdaGrammarPython}{
  15523. \begin{array}{lcl}
  15524. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15525. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15526. \end{array}
  15527. }
  15528. \newcommand{\LlambdaASTPython}{
  15529. \begin{array}{lcl}
  15530. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15531. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15532. \end{array}
  15533. }
  15534. % include AnnAssign in ASTPython
  15535. \begin{figure}[tp]
  15536. \centering
  15537. \begin{tcolorbox}[colback=white]
  15538. \small
  15539. {\if\edition\racketEd
  15540. \[
  15541. \begin{array}{l}
  15542. \gray{\LintGrammarRacket{}} \\ \hline
  15543. \gray{\LvarGrammarRacket{}} \\ \hline
  15544. \gray{\LifGrammarRacket{}} \\ \hline
  15545. \gray{\LwhileGrammarRacket} \\ \hline
  15546. \gray{\LtupGrammarRacket} \\ \hline
  15547. \gray{\LfunGrammarRacket} \\ \hline
  15548. \LlambdaGrammarRacket \\
  15549. \begin{array}{lcl}
  15550. \LangLamM{} &::=& \Def\ldots \; \Exp
  15551. \end{array}
  15552. \end{array}
  15553. \]
  15554. \fi}
  15555. {\if\edition\pythonEd\pythonColor
  15556. \[
  15557. \begin{array}{l}
  15558. \gray{\LintGrammarPython{}} \\ \hline
  15559. \gray{\LvarGrammarPython{}} \\ \hline
  15560. \gray{\LifGrammarPython{}} \\ \hline
  15561. \gray{\LwhileGrammarPython} \\ \hline
  15562. \gray{\LtupGrammarPython} \\ \hline
  15563. \gray{\LfunGrammarPython} \\ \hline
  15564. \LlambdaGrammarPython \\
  15565. \begin{array}{lcl}
  15566. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15567. \end{array}
  15568. \end{array}
  15569. \]
  15570. \fi}
  15571. \end{tcolorbox}
  15572. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15573. with \key{lambda}.}
  15574. \label{fig:Llam-concrete-syntax}
  15575. \end{figure}
  15576. \begin{figure}[tp]
  15577. \centering
  15578. \begin{tcolorbox}[colback=white]
  15579. \small
  15580. {\if\edition\racketEd
  15581. \[\arraycolsep=3pt
  15582. \begin{array}{l}
  15583. \gray{\LintOpAST} \\ \hline
  15584. \gray{\LvarASTRacket{}} \\ \hline
  15585. \gray{\LifASTRacket{}} \\ \hline
  15586. \gray{\LwhileASTRacket{}} \\ \hline
  15587. \gray{\LtupASTRacket{}} \\ \hline
  15588. \gray{\LfunASTRacket} \\ \hline
  15589. \LlambdaASTRacket \\
  15590. \begin{array}{lcl}
  15591. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15592. \end{array}
  15593. \end{array}
  15594. \]
  15595. \fi}
  15596. {\if\edition\pythonEd\pythonColor
  15597. \[
  15598. \begin{array}{l}
  15599. \gray{\LintASTPython} \\ \hline
  15600. \gray{\LvarASTPython{}} \\ \hline
  15601. \gray{\LifASTPython{}} \\ \hline
  15602. \gray{\LwhileASTPython{}} \\ \hline
  15603. \gray{\LtupASTPython{}} \\ \hline
  15604. \gray{\LfunASTPython} \\ \hline
  15605. \LlambdaASTPython \\
  15606. \begin{array}{lcl}
  15607. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15608. \end{array}
  15609. \end{array}
  15610. \]
  15611. \fi}
  15612. \end{tcolorbox}
  15613. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15614. \label{fig:Llam-syntax}
  15615. \end{figure}
  15616. Figure~\ref{fig:interp-Llambda} shows the definitional
  15617. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15618. \key{Lambda} saves the current environment inside the returned
  15619. function value. Recall that during function application, the
  15620. environment stored in the function value, extended with the mapping of
  15621. parameters to argument values, is used to interpret the body of the
  15622. function.
  15623. \begin{figure}[tbp]
  15624. \begin{tcolorbox}[colback=white]
  15625. {\if\edition\racketEd
  15626. \begin{lstlisting}
  15627. (define interp-Llambda-class
  15628. (class interp-Lfun-class
  15629. (super-new)
  15630. (define/override (interp-op op)
  15631. (match op
  15632. ['procedure-arity
  15633. (lambda (v)
  15634. (match v
  15635. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15636. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15637. [else (super interp-op op)]))
  15638. (define/override ((interp-exp env) e)
  15639. (define recur (interp-exp env))
  15640. (match e
  15641. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15642. `(function ,xs ,body ,env)]
  15643. [else ((super interp-exp env) e)]))
  15644. ))
  15645. (define (interp-Llambda p)
  15646. (send (new interp-Llambda-class) interp-program p))
  15647. \end{lstlisting}
  15648. \fi}
  15649. {\if\edition\pythonEd\pythonColor
  15650. \begin{lstlisting}
  15651. class InterpLlambda(InterpLfun):
  15652. def arity(self, v):
  15653. match v:
  15654. case Function(name, params, body, env):
  15655. return len(params)
  15656. case _:
  15657. raise Exception('Llambda arity unexpected ' + repr(v))
  15658. def interp_exp(self, e, env):
  15659. match e:
  15660. case Call(Name('arity'), [fun]):
  15661. f = self.interp_exp(fun, env)
  15662. return self.arity(f)
  15663. case Lambda(params, body):
  15664. return Function('lambda', params, [Return(body)], env)
  15665. case _:
  15666. return super().interp_exp(e, env)
  15667. def interp_stmt(self, s, env, cont):
  15668. match s:
  15669. case AnnAssign(lhs, typ, value, simple):
  15670. env[lhs.id] = self.interp_exp(value, env)
  15671. return self.interp_stmts(cont, env)
  15672. case Pass():
  15673. return self.interp_stmts(cont, env)
  15674. case _:
  15675. return super().interp_stmt(s, env, cont)
  15676. \end{lstlisting}
  15677. \fi}
  15678. \end{tcolorbox}
  15679. \caption{Interpreter for \LangLam{}.}
  15680. \label{fig:interp-Llambda}
  15681. \end{figure}
  15682. {\if\edition\racketEd
  15683. %
  15684. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15685. \key{lambda} form. The body of the \key{lambda} is checked in an
  15686. environment that includes the current environment (because it is
  15687. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15688. require the body's type to match the declared return type.
  15689. %
  15690. \fi}
  15691. {\if\edition\pythonEd\pythonColor
  15692. %
  15693. Figures~\ref{fig:type-check-Llambda} and
  15694. \ref{fig:type-check-Llambda-part2} define the type checker for
  15695. \LangLam{}, which is more complex than one might expect. The reason
  15696. for the added complexity is that the syntax of \key{lambda} does not
  15697. include type annotations for the parameters or return type. Instead
  15698. they must be inferred. There are many approaches to type inference
  15699. from which to choose, of varying degrees of complexity. We choose one
  15700. of the simpler approaches, bidirectional type
  15701. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15702. book is compilation, not type inference.
  15703. The main idea of bidirectional type inference is to add an auxiliary
  15704. function, here named \code{check\_exp}, that takes an expected type
  15705. and checks whether the given expression is of that type. Thus, in
  15706. \code{check\_exp}, type information flows in a top-down manner with
  15707. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15708. function, where type information flows in a primarily bottom-up
  15709. manner.
  15710. %
  15711. The idea then is to use \code{check\_exp} in all the places where we
  15712. already know what the type of an expression should be, such as in the
  15713. \code{return} statement of a top-level function definition or on the
  15714. right-hand side of an annotated assignment statement.
  15715. With regard to \code{lambda}, it is straightforward to check a
  15716. \code{lambda} inside \code{check\_exp} because the expected type
  15717. provides the parameter types and the return type. On the other hand,
  15718. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15719. that we do not allow \code{lambda} in contexts in which we don't already
  15720. know its type. This restriction does not incur a loss of
  15721. expressiveness for \LangLam{} because it is straightforward to modify
  15722. a program to sidestep the restriction, for example, by using an
  15723. annotated assignment statement to assign the \code{lambda} to a
  15724. temporary variable.
  15725. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15726. checker records their type in a \code{has\_type} field. This type
  15727. information is used further on in this chapter.
  15728. %
  15729. \fi}
  15730. \begin{figure}[tbp]
  15731. \begin{tcolorbox}[colback=white]
  15732. {\if\edition\racketEd
  15733. \begin{lstlisting}
  15734. (define (type-check-Llambda env)
  15735. (lambda (e)
  15736. (match e
  15737. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15738. (define-values (new-body bodyT)
  15739. ((type-check-exp (append (map cons xs Ts) env)) body))
  15740. (define ty `(,@Ts -> ,rT))
  15741. (cond
  15742. [(equal? rT bodyT)
  15743. (values (HasType (Lambda params rT new-body) ty) ty)]
  15744. [else
  15745. (error "mismatch in return type" bodyT rT)])]
  15746. ...
  15747. )))
  15748. \end{lstlisting}
  15749. \fi}
  15750. {\if\edition\pythonEd\pythonColor
  15751. \begin{lstlisting}
  15752. class TypeCheckLlambda(TypeCheckLfun):
  15753. def type_check_exp(self, e, env):
  15754. match e:
  15755. case Name(id):
  15756. e.has_type = env[id]
  15757. return env[id]
  15758. case Lambda(params, body):
  15759. raise Exception('cannot synthesize a type for a lambda')
  15760. case Call(Name('arity'), [func]):
  15761. func_t = self.type_check_exp(func, env)
  15762. match func_t:
  15763. case FunctionType(params_t, return_t):
  15764. return IntType()
  15765. case _:
  15766. raise Exception('in arity, unexpected ' + repr(func_t))
  15767. case _:
  15768. return super().type_check_exp(e, env)
  15769. def check_exp(self, e, ty, env):
  15770. match e:
  15771. case Lambda(params, body):
  15772. e.has_type = ty
  15773. match ty:
  15774. case FunctionType(params_t, return_t):
  15775. new_env = env.copy().update(zip(params, params_t))
  15776. self.check_exp(body, return_t, new_env)
  15777. case _:
  15778. raise Exception('lambda does not have type ' + str(ty))
  15779. case Call(func, args):
  15780. func_t = self.type_check_exp(func, env)
  15781. match func_t:
  15782. case FunctionType(params_t, return_t):
  15783. for (arg, param_t) in zip(args, params_t):
  15784. self.check_exp(arg, param_t, env)
  15785. self.check_type_equal(return_t, ty, e)
  15786. case _:
  15787. raise Exception('type_check_exp: in call, unexpected ' + \
  15788. repr(func_t))
  15789. case _:
  15790. t = self.type_check_exp(e, env)
  15791. self.check_type_equal(t, ty, e)
  15792. \end{lstlisting}
  15793. \fi}
  15794. \end{tcolorbox}
  15795. \caption{Type checking \LangLam{}\python{, part 1}.}
  15796. \label{fig:type-check-Llambda}
  15797. \end{figure}
  15798. {\if\edition\pythonEd\pythonColor
  15799. \begin{figure}[tbp]
  15800. \begin{tcolorbox}[colback=white]
  15801. \begin{lstlisting}
  15802. def check_stmts(self, ss, return_ty, env):
  15803. if len(ss) == 0:
  15804. return
  15805. match ss[0]:
  15806. case FunctionDef(name, params, body, dl, returns, comment):
  15807. new_env = env.copy().update(params)
  15808. rt = self.check_stmts(body, returns, new_env)
  15809. self.check_stmts(ss[1:], return_ty, env)
  15810. case Return(value):
  15811. self.check_exp(value, return_ty, env)
  15812. case Assign([Name(id)], value):
  15813. if id in env:
  15814. self.check_exp(value, env[id], env)
  15815. else:
  15816. env[id] = self.type_check_exp(value, env)
  15817. self.check_stmts(ss[1:], return_ty, env)
  15818. case Assign([Subscript(tup, Constant(index), Store())], value):
  15819. tup_t = self.type_check_exp(tup, env)
  15820. match tup_t:
  15821. case TupleType(ts):
  15822. self.check_exp(value, ts[index], env)
  15823. case _:
  15824. raise Exception('expected a tuple, not ' + repr(tup_t))
  15825. self.check_stmts(ss[1:], return_ty, env)
  15826. case AnnAssign(Name(id), ty_annot, value, simple):
  15827. ss[0].annotation = ty_annot
  15828. if id in env:
  15829. self.check_type_equal(env[id], ty_annot)
  15830. else:
  15831. env[id] = ty_annot
  15832. self.check_exp(value, ty_annot, env)
  15833. self.check_stmts(ss[1:], return_ty, env)
  15834. case _:
  15835. self.type_check_stmts(ss, env)
  15836. def type_check(self, p):
  15837. match p:
  15838. case Module(body):
  15839. env = {}
  15840. for s in body:
  15841. match s:
  15842. case FunctionDef(name, params, bod, dl, returns, comment):
  15843. params_t = [t for (x,t) in params]
  15844. env[name] = FunctionType(params_t, returns)
  15845. self.check_stmts(body, int, env)
  15846. \end{lstlisting}
  15847. \end{tcolorbox}
  15848. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15849. \label{fig:type-check-Llambda-part2}
  15850. \end{figure}
  15851. \fi}
  15852. \clearpage
  15853. \section{Assignment and Lexically Scoped Functions}
  15854. \label{sec:assignment-scoping}
  15855. The combination of lexically scoped functions and assignment to
  15856. variables raises a challenge with the flat-closure approach to
  15857. implementing lexically scoped functions. Consider the following
  15858. example in which function \code{f} has a free variable \code{x} that
  15859. is changed after \code{f} is created but before the call to \code{f}.
  15860. % loop_test_11.rkt
  15861. {\if\edition\racketEd
  15862. \begin{lstlisting}
  15863. (let ([x 0])
  15864. (let ([y 0])
  15865. (let ([z 20])
  15866. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15867. (begin
  15868. (set! x 10)
  15869. (set! y 12)
  15870. (f y))))))
  15871. \end{lstlisting}
  15872. \fi}
  15873. {\if\edition\pythonEd\pythonColor
  15874. % box_free_assign.py
  15875. \begin{lstlisting}
  15876. def g(z : int) -> int:
  15877. x = 0
  15878. y = 0
  15879. f : Callable[[int],int] = lambda a: a + x + z
  15880. x = 10
  15881. y = 12
  15882. return f(y)
  15883. print(g(20))
  15884. \end{lstlisting}
  15885. \fi} The correct output for this example is \code{42} because the call
  15886. to \code{f} is required to use the current value of \code{x} (which is
  15887. \code{10}). Unfortunately, the closure conversion pass
  15888. (section~\ref{sec:closure-conversion}) generates code for the
  15889. \code{lambda} that copies the old value of \code{x} into a
  15890. closure. Thus, if we naively applied closure conversion, the output of
  15891. this program would be \code{32}.
  15892. A first attempt at solving this problem would be to save a pointer to
  15893. \code{x} in the closure and change the occurrences of \code{x} inside
  15894. the lambda to dereference the pointer. Of course, this would require
  15895. assigning \code{x} to the stack and not to a register. However, the
  15896. problem goes a bit deeper.
  15897. Consider the following example that returns a function that refers to
  15898. a local variable of the enclosing function:
  15899. \begin{center}
  15900. \begin{minipage}{\textwidth}
  15901. {\if\edition\racketEd
  15902. \begin{lstlisting}
  15903. (define (f) : ( -> Integer)
  15904. (let ([x 0])
  15905. (let ([g (lambda: () : Integer x)])
  15906. (begin
  15907. (set! x 42)
  15908. g))))
  15909. ((f))
  15910. \end{lstlisting}
  15911. \fi}
  15912. {\if\edition\pythonEd\pythonColor
  15913. % counter.py
  15914. \begin{lstlisting}
  15915. def f():
  15916. x = 0
  15917. g = lambda: x
  15918. x = 42
  15919. return g
  15920. print(f()())
  15921. \end{lstlisting}
  15922. \fi}
  15923. \end{minipage}
  15924. \end{center}
  15925. In this example, the lifetime of \code{x} extends beyond the lifetime
  15926. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15927. stack frame for the call to \code{f}, it would be gone by the time we
  15928. called \code{g}, leaving us with dangling pointers for
  15929. \code{x}. This example demonstrates that when a variable occurs free
  15930. inside a function, its lifetime becomes indefinite. Thus, the value of
  15931. the variable needs to live on the heap. The verb
  15932. \emph{box}\index{subject}{box} is often used for allocating a single
  15933. value on the heap, producing a pointer, and
  15934. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15935. %
  15936. We introduce a new pass named \code{convert\_assignments} to address
  15937. this challenge.
  15938. %
  15939. \python{But before diving into that, we have one more
  15940. problem to discuss.}
  15941. {\if\edition\pythonEd\pythonColor
  15942. \section{Uniquify Variables}
  15943. \label{sec:uniquify-lambda}
  15944. With the addition of \code{lambda} we have a complication to deal
  15945. with: name shadowing. Consider the following program with a function
  15946. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15947. \code{lambda} expressions. The first \code{lambda} has a parameter
  15948. that is also named \code{x}.
  15949. \begin{lstlisting}
  15950. def f(x:int, y:int) -> Callable[[int], int]:
  15951. g : Callable[[int],int] = (lambda x: x + y)
  15952. h : Callable[[int],int] = (lambda y: x + y)
  15953. x = input_int()
  15954. return g
  15955. print(f(0, 10)(32))
  15956. \end{lstlisting}
  15957. Many of our compiler passes rely on being able to connect variable
  15958. uses with their definitions using just the name of the
  15959. variable. However, in the example above, the name of the variable does
  15960. not uniquely determine its definition. To solve this problem we
  15961. recommend implementing a pass named \code{uniquify} that renames every
  15962. variable in the program to make sure that they are all unique.
  15963. The following shows the result of \code{uniquify} for the example
  15964. above. The \code{x} parameter of function \code{f} is renamed to
  15965. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15966. renamed to \code{x\_4}.
  15967. \begin{lstlisting}
  15968. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15969. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15970. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15971. x_0 = input_int()
  15972. return g_2
  15973. def main() -> int :
  15974. print(f(0, 10)(32))
  15975. return 0
  15976. \end{lstlisting}
  15977. \fi} % pythonEd
  15978. %% \section{Reveal Functions}
  15979. %% \label{sec:reveal-functions-r5}
  15980. %% \racket{To support the \code{procedure-arity} operator we need to
  15981. %% communicate the arity of a function to the point of closure
  15982. %% creation.}
  15983. %% %
  15984. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15985. %% function at runtime. Thus, we need to communicate the arity of a
  15986. %% function to the point of closure creation.}
  15987. %% %
  15988. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15989. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15990. %% \[
  15991. %% \begin{array}{lcl}
  15992. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15993. %% \end{array}
  15994. %% \]
  15995. \section{Assignment Conversion}
  15996. \label{sec:convert-assignments}
  15997. The purpose of the \code{convert\_assignments} pass is to address the
  15998. challenge regarding the interaction between variable assignments and
  15999. closure conversion. First we identify which variables need to be
  16000. boxed, and then we transform the program to box those variables. In
  16001. general, boxing introduces runtime overhead that we would like to
  16002. avoid, so we should box as few variables as possible. We recommend
  16003. boxing the variables in the intersection of the following two sets of
  16004. variables:
  16005. \begin{enumerate}
  16006. \item The variables that are free in a \code{lambda}.
  16007. \item The variables that appear on the left-hand side of an
  16008. assignment.
  16009. \end{enumerate}
  16010. The first condition is a must but the second condition is
  16011. conservative. It is possible to develop a more liberal condition using
  16012. static program analysis.
  16013. Consider again the first example from
  16014. section~\ref{sec:assignment-scoping}:
  16015. %
  16016. {\if\edition\racketEd
  16017. \begin{lstlisting}
  16018. (let ([x 0])
  16019. (let ([y 0])
  16020. (let ([z 20])
  16021. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16022. (begin
  16023. (set! x 10)
  16024. (set! y 12)
  16025. (f y))))))
  16026. \end{lstlisting}
  16027. \fi}
  16028. {\if\edition\pythonEd\pythonColor
  16029. \begin{lstlisting}
  16030. def g(z : int) -> int:
  16031. x = 0
  16032. y = 0
  16033. f : Callable[[int],int] = lambda a: a + x + z
  16034. x = 10
  16035. y = 12
  16036. return f(y)
  16037. print(g(20))
  16038. \end{lstlisting}
  16039. \fi}
  16040. %
  16041. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16042. side of assignments. The variables \code{x} and \code{z} occur free
  16043. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16044. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16045. three transformations: initialize \code{x} with a tuple whose element
  16046. is uninitialized, replace reads from \code{x} with tuple reads, and
  16047. replace each assignment to \code{x} with a tuple write. The output of
  16048. \code{convert\_assignments} for this example is as follows:
  16049. %
  16050. {\if\edition\racketEd
  16051. \begin{lstlisting}
  16052. (define (main) : Integer
  16053. (let ([x0 (vector 0)])
  16054. (let ([y1 0])
  16055. (let ([z2 20])
  16056. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16057. (+ a3 (+ (vector-ref x0 0) z2)))])
  16058. (begin
  16059. (vector-set! x0 0 10)
  16060. (set! y1 12)
  16061. (f4 y1)))))))
  16062. \end{lstlisting}
  16063. \fi}
  16064. %
  16065. {\if\edition\pythonEd\pythonColor
  16066. \begin{lstlisting}
  16067. def g(z : int)-> int:
  16068. x = (uninitialized(int),)
  16069. x[0] = 0
  16070. y = 0
  16071. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16072. x[0] = 10
  16073. y = 12
  16074. return f(y)
  16075. def main() -> int:
  16076. print(g(20))
  16077. return 0
  16078. \end{lstlisting}
  16079. \fi}
  16080. To compute the free variables of all the \code{lambda} expressions, we
  16081. recommend defining the following two auxiliary functions:
  16082. \begin{enumerate}
  16083. \item \code{free\_variables} computes the free variables of an expression, and
  16084. \item \code{free\_in\_lambda} collects all the variables that are
  16085. free in any of the \code{lambda} expressions, using
  16086. \code{free\_variables} in the case for each \code{lambda}.
  16087. \end{enumerate}
  16088. {\if\edition\racketEd
  16089. %
  16090. To compute the variables that are assigned to, we recommend updating
  16091. the \code{collect-set!} function that we introduced in
  16092. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16093. as \code{Lambda}.
  16094. %
  16095. \fi}
  16096. {\if\edition\pythonEd\pythonColor
  16097. %
  16098. To compute the variables that are assigned to, we recommend defining
  16099. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16100. the set of variables that occur in the left-hand side of an assignment
  16101. statement and otherwise returns the empty set.
  16102. %
  16103. \fi}
  16104. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16105. free in a \code{lambda} and that are assigned to in the enclosing
  16106. function definition.
  16107. Next we discuss the \code{convert\_assignments} pass. In the case for
  16108. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16109. $\VAR{x}$ to a tuple read.
  16110. %
  16111. {\if\edition\racketEd
  16112. \begin{lstlisting}
  16113. (Var |$x$|)
  16114. |$\Rightarrow$|
  16115. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16116. \end{lstlisting}
  16117. \fi}
  16118. %
  16119. {\if\edition\pythonEd\pythonColor
  16120. \begin{lstlisting}
  16121. Name(|$x$|)
  16122. |$\Rightarrow$|
  16123. Subscript(Name(|$x$|), Constant(0), Load())
  16124. \end{lstlisting}
  16125. \fi}
  16126. %
  16127. \noindent In the case for assignment, recursively process the
  16128. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16129. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16130. as follows:
  16131. %
  16132. {\if\edition\racketEd
  16133. \begin{lstlisting}
  16134. (SetBang |$x$| |$\itm{rhs}$|)
  16135. |$\Rightarrow$|
  16136. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16137. \end{lstlisting}
  16138. \fi}
  16139. {\if\edition\pythonEd\pythonColor
  16140. \begin{lstlisting}
  16141. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16142. |$\Rightarrow$|
  16143. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16144. \end{lstlisting}
  16145. \fi}
  16146. %
  16147. {\if\edition\racketEd
  16148. The case for \code{Lambda} is nontrivial, but it is similar to the
  16149. case for function definitions, which we discuss next.
  16150. \fi}
  16151. %
  16152. To translate a function definition, we first compute $\mathit{AF}$,
  16153. the intersection of the variables that are free in a \code{lambda} and
  16154. that are assigned to. We then apply assignment conversion to the body
  16155. of the function definition. Finally, we box the parameters of this
  16156. function definition that are in $\mathit{AF}$. For example,
  16157. the parameter \code{x} of the following function \code{g}
  16158. needs to be boxed:
  16159. {\if\edition\racketEd
  16160. \begin{lstlisting}
  16161. (define (g [x : Integer]) : Integer
  16162. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16163. (begin
  16164. (set! x 10)
  16165. (f 32))))
  16166. \end{lstlisting}
  16167. \fi}
  16168. %
  16169. {\if\edition\pythonEd\pythonColor
  16170. \begin{lstlisting}
  16171. def g(x : int) -> int:
  16172. f : Callable[[int],int] = lambda a: a + x
  16173. x = 10
  16174. return f(32)
  16175. \end{lstlisting}
  16176. \fi}
  16177. %
  16178. \noindent We box parameter \code{x} by creating a local variable named
  16179. \code{x} that is initialized to a tuple whose contents is the value of
  16180. the parameter, which is renamed to \code{x\_0}.
  16181. %
  16182. {\if\edition\racketEd
  16183. \begin{lstlisting}
  16184. (define (g [x_0 : Integer]) : Integer
  16185. (let ([x (vector x_0)])
  16186. (let ([f (lambda: ([a : Integer]) : Integer
  16187. (+ a (vector-ref x 0)))])
  16188. (begin
  16189. (vector-set! x 0 10)
  16190. (f 32)))))
  16191. \end{lstlisting}
  16192. \fi}
  16193. %
  16194. {\if\edition\pythonEd\pythonColor
  16195. \begin{lstlisting}
  16196. def g(x_0 : int)-> int:
  16197. x = (x_0,)
  16198. f : Callable[[int], int] = (lambda a: a + x[0])
  16199. x[0] = 10
  16200. return f(32)
  16201. \end{lstlisting}
  16202. \fi}
  16203. \section{Closure Conversion}
  16204. \label{sec:closure-conversion}
  16205. \index{subject}{closure conversion}
  16206. The compiling of lexically scoped functions into top-level function
  16207. definitions and flat closures is accomplished in the pass
  16208. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16209. and before \code{limit\_functions}.
  16210. As usual, we implement the pass as a recursive function over the
  16211. AST. The interesting cases are for \key{lambda} and function
  16212. application. We transform a \key{lambda} expression into an expression
  16213. that creates a closure, that is, a tuple for which the first element
  16214. is a function pointer and the rest of the elements are the values of
  16215. the free variables of the \key{lambda}.
  16216. %
  16217. However, we use the \code{Closure} AST node instead of using a tuple
  16218. so that we can record the arity.
  16219. %
  16220. In the generated code that follows, \itm{fvs} is the list of free
  16221. variables of the lambda and \itm{name} is a unique symbol generated to
  16222. identify the lambda.
  16223. %
  16224. \racket{The \itm{arity} is the number of parameters (the length of
  16225. \itm{ps}).}
  16226. %
  16227. {\if\edition\racketEd
  16228. \begin{lstlisting}
  16229. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16230. |$\Rightarrow$|
  16231. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16232. \end{lstlisting}
  16233. \fi}
  16234. %
  16235. {\if\edition\pythonEd\pythonColor
  16236. \begin{lstlisting}
  16237. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16238. |$\Rightarrow$|
  16239. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16240. \end{lstlisting}
  16241. \fi}
  16242. %
  16243. In addition to transforming each \key{Lambda} AST node into a
  16244. tuple, we create a top-level function definition for each
  16245. \key{Lambda}, as shown next.\\
  16246. \begin{minipage}{0.8\textwidth}
  16247. {\if\edition\racketEd
  16248. \begin{lstlisting}
  16249. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16250. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16251. ...
  16252. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16253. |\itm{body'}|)...))
  16254. \end{lstlisting}
  16255. \fi}
  16256. {\if\edition\pythonEd\pythonColor
  16257. \begin{lstlisting}
  16258. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16259. |$\itm{fvs}_1$| = clos[1]
  16260. |$\ldots$|
  16261. |$\itm{fvs}_m$| = clos[|$m$|]
  16262. |\itm{body'}|
  16263. \end{lstlisting}
  16264. \fi}
  16265. \end{minipage}\\
  16266. %
  16267. The \code{clos} parameter refers to the closure. The type
  16268. \itm{closTy} is a tuple type for which the first element type is
  16269. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16270. rest of the element types are the types of the free variables in the
  16271. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16272. is nontrivial to give a type to the function in the closure's
  16273. type.\footnote{To give an accurate type to a closure, we would need to
  16274. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16275. %
  16276. \racket{Translate the type
  16277. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16278. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16279. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16280. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16281. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16282. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16283. %% The dummy type is considered to be equal to any other type during type
  16284. %% checking.
  16285. The free variables become local variables that are initialized with
  16286. their values in the closure.
  16287. Closure conversion turns every function into a tuple, so the type
  16288. annotations in the program must also be translated. We recommend
  16289. defining an auxiliary recursive function for this purpose. Function
  16290. types should be translated as follows:
  16291. %
  16292. {\if\edition\racketEd
  16293. \begin{lstlisting}
  16294. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16295. |$\Rightarrow$|
  16296. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16297. \end{lstlisting}
  16298. \fi}
  16299. {\if\edition\pythonEd\pythonColor
  16300. \begin{lstlisting}
  16301. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16302. |$\Rightarrow$|
  16303. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16304. \end{lstlisting}
  16305. \fi}
  16306. %
  16307. This type indicates that the first thing in the tuple is a
  16308. function. The first parameter of the function is a tuple (a closure)
  16309. and the rest of the parameters are the ones from the original
  16310. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16311. omits the types of the free variables because (1) those types are not
  16312. available in this context, and (2) we do not need them in the code that
  16313. is generated for function application. So this type describes only the
  16314. first component of the closure tuple. At runtime the tuple may have
  16315. more components, but we ignore them at this point.
  16316. We transform function application into code that retrieves the
  16317. function from the closure and then calls the function, passing the
  16318. closure as the first argument. We place $e'$ in a temporary variable
  16319. to avoid code duplication.
  16320. \begin{center}
  16321. \begin{minipage}{\textwidth}
  16322. {\if\edition\racketEd
  16323. \begin{lstlisting}
  16324. (Apply |$e$| |$\itm{es}$|)
  16325. |$\Rightarrow$|
  16326. (Let |$\itm{tmp}$| |$e'$|
  16327. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16328. \end{lstlisting}
  16329. \fi}
  16330. %
  16331. {\if\edition\pythonEd\pythonColor
  16332. \begin{lstlisting}
  16333. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16334. |$\Rightarrow$|
  16335. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16336. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16337. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16338. \end{lstlisting}
  16339. \fi}
  16340. \end{minipage}
  16341. \end{center}
  16342. There is also the question of what to do with references to top-level
  16343. function definitions. To maintain a uniform translation of function
  16344. application, we turn function references into closures.
  16345. \begin{tabular}{lll}
  16346. \begin{minipage}{0.2\textwidth}
  16347. {\if\edition\racketEd
  16348. \begin{lstlisting}
  16349. (FunRef |$f$| |$n$|)
  16350. \end{lstlisting}
  16351. \fi}
  16352. {\if\edition\pythonEd\pythonColor
  16353. \begin{lstlisting}
  16354. FunRef(|$f$|, |$n$|)
  16355. \end{lstlisting}
  16356. \fi}
  16357. \end{minipage}
  16358. &
  16359. $\Rightarrow\qquad$
  16360. &
  16361. \begin{minipage}{0.5\textwidth}
  16362. {\if\edition\racketEd
  16363. \begin{lstlisting}
  16364. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16365. \end{lstlisting}
  16366. \fi}
  16367. {\if\edition\pythonEd\pythonColor
  16368. \begin{lstlisting}
  16369. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16370. \end{lstlisting}
  16371. \fi}
  16372. \end{minipage}
  16373. \end{tabular} \\
  16374. We no longer need the annotated assignment statement \code{AnnAssign}
  16375. to support the type checking of \code{lambda} expressions, so we
  16376. translate it to a regular \code{Assign} statement.
  16377. The top-level function definitions need to be updated to take an extra
  16378. closure parameter, but that parameter is ignored in the body of those
  16379. functions.
  16380. \subsection{An Example Translation}
  16381. \label{sec:example-lambda}
  16382. Figure~\ref{fig:lexical-functions-example} shows the result of
  16383. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16384. program demonstrating lexical scoping that we discussed at the
  16385. beginning of this chapter.
  16386. \begin{figure}[tbp]
  16387. \begin{tcolorbox}[colback=white]
  16388. \begin{minipage}{0.8\textwidth}
  16389. {\if\edition\racketEd
  16390. % tests/lambda_test_6.rkt
  16391. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16392. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16393. (let ([y8 4])
  16394. (lambda: ([z9 : Integer]) : Integer
  16395. (+ x7 (+ y8 z9)))))
  16396. (define (main) : Integer
  16397. (let ([g0 ((fun-ref f6 1) 5)])
  16398. (let ([h1 ((fun-ref f6 1) 3)])
  16399. (+ (g0 11) (h1 15)))))
  16400. \end{lstlisting}
  16401. $\Rightarrow$
  16402. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16403. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16404. (let ([y8 4])
  16405. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16406. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16407. (let ([x7 (vector-ref fvs3 1)])
  16408. (let ([y8 (vector-ref fvs3 2)])
  16409. (+ x7 (+ y8 z9)))))
  16410. (define (main) : Integer
  16411. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16412. ((vector-ref clos5 0) clos5 5))])
  16413. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16414. ((vector-ref clos6 0) clos6 3))])
  16415. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16416. \end{lstlisting}
  16417. \fi}
  16418. %
  16419. {\if\edition\pythonEd\pythonColor
  16420. % free_var.py
  16421. \begin{lstlisting}
  16422. def f(x: int) -> Callable[[int],int]:
  16423. y = 4
  16424. return lambda z: x + y + z
  16425. g = f(5)
  16426. h = f(3)
  16427. print(g(11) + h(15))
  16428. \end{lstlisting}
  16429. $\Rightarrow$
  16430. \begin{lstlisting}
  16431. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16432. x = fvs_1[1]
  16433. y = fvs_1[2]
  16434. return (x + y[0] + z)
  16435. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16436. y = (uninitialized(int),)
  16437. y[0] = 4
  16438. return closure{1}({lambda_0}, x, y)
  16439. def main() -> int:
  16440. g = (begin: clos_3 = closure{1}({f})
  16441. clos_3[0](clos_3, 5))
  16442. h = (begin: clos_4 = closure{1}({f})
  16443. clos_4[0](clos_4, 3))
  16444. print((begin: clos_5 = g
  16445. clos_5[0](clos_5, 11))
  16446. + (begin: clos_6 = h
  16447. clos_6[0](clos_6, 15)))
  16448. return 0
  16449. \end{lstlisting}
  16450. \fi}
  16451. \end{minipage}
  16452. \end{tcolorbox}
  16453. \caption{Example of closure conversion.}
  16454. \label{fig:lexical-functions-example}
  16455. \end{figure}
  16456. \begin{exercise}\normalfont\normalsize
  16457. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16458. Create five new programs that use \key{lambda} functions and make use of
  16459. lexical scoping. Test your compiler on these new programs and all
  16460. your previously created test programs.
  16461. \end{exercise}
  16462. \section{Expose Allocation}
  16463. \label{sec:expose-allocation-r5}
  16464. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16465. that allocates and initializes a tuple, similar to the translation of
  16466. the tuple creation in section~\ref{sec:expose-allocation}.
  16467. The only difference is replacing the use of
  16468. \ALLOC{\itm{len}}{\itm{type}} with
  16469. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16470. \section{Explicate Control and \LangCLam{}}
  16471. \label{sec:explicate-r5}
  16472. The output language of \code{explicate\_control} is \LangCLam{}; the
  16473. definition of its abstract syntax is shown in
  16474. figure~\ref{fig:Clam-syntax}.
  16475. %
  16476. \racket{The only differences with respect to \LangCFun{} are the
  16477. addition of the \code{AllocateClosure} form to the grammar for
  16478. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16479. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16480. similar to the handling of other expressions such as primitive
  16481. operators.}
  16482. %
  16483. \python{The differences with respect to \LangCFun{} are the
  16484. additions of \code{Uninitialized}, \code{AllocateClosure},
  16485. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16486. \code{explicate\_control} pass is similar to the handling of other
  16487. expressions such as primitive operators.}
  16488. \newcommand{\ClambdaASTRacket}{
  16489. \begin{array}{lcl}
  16490. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16491. \itm{op} &::= & \code{procedure-arity}
  16492. \end{array}
  16493. }
  16494. \newcommand{\ClambdaASTPython}{
  16495. \begin{array}{lcl}
  16496. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16497. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16498. &\MID& \ARITY{\Atm}
  16499. \end{array}
  16500. }
  16501. \begin{figure}[tp]
  16502. \begin{tcolorbox}[colback=white]
  16503. \small
  16504. {\if\edition\racketEd
  16505. \[
  16506. \begin{array}{l}
  16507. \gray{\CvarASTRacket} \\ \hline
  16508. \gray{\CifASTRacket} \\ \hline
  16509. \gray{\CloopASTRacket} \\ \hline
  16510. \gray{\CtupASTRacket} \\ \hline
  16511. \gray{\CfunASTRacket} \\ \hline
  16512. \ClambdaASTRacket \\
  16513. \begin{array}{lcl}
  16514. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16515. \end{array}
  16516. \end{array}
  16517. \]
  16518. \fi}
  16519. {\if\edition\pythonEd\pythonColor
  16520. \[
  16521. \begin{array}{l}
  16522. \gray{\CifASTPython} \\ \hline
  16523. \gray{\CtupASTPython} \\ \hline
  16524. \gray{\CfunASTPython} \\ \hline
  16525. \ClambdaASTPython \\
  16526. \begin{array}{lcl}
  16527. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16528. \end{array}
  16529. \end{array}
  16530. \]
  16531. \fi}
  16532. \end{tcolorbox}
  16533. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16534. \label{fig:Clam-syntax}
  16535. \end{figure}
  16536. \section{Select Instructions}
  16537. \label{sec:select-instructions-Llambda}
  16538. \index{subject}{select instructions}
  16539. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16540. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16541. (section~\ref{sec:select-instructions-gc}). The only difference is
  16542. that you should place the \itm{arity} in the tag that is stored at
  16543. position $0$ of the tuple. Recall that in
  16544. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16545. was not used. We store the arity in the $5$ bits starting at position
  16546. $58$.
  16547. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16548. instructions that access the tag from position $0$ of the vector and
  16549. extract the $5$ bits starting at position $58$ from the tag.}
  16550. %
  16551. \python{Compile a call to the \code{arity} operator to a sequence of
  16552. instructions that access the tag from position $0$ of the tuple
  16553. (representing a closure) and extract the $5$ bits starting at position
  16554. $58$ from the tag.}
  16555. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16556. needed for the compilation of \LangLam{}.
  16557. \begin{figure}[bthp]
  16558. \begin{tcolorbox}[colback=white]
  16559. {\if\edition\racketEd
  16560. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16561. \node (Lfun) at (0,2) {\large \LangLam{}};
  16562. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16563. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16564. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16565. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16566. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16567. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16568. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16569. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16570. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16571. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16572. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16573. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16574. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16575. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16576. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16577. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16578. \path[->,bend left=15] (Lfun) edge [above] node
  16579. {\ttfamily\footnotesize shrink} (Lfun-2);
  16580. \path[->,bend left=15] (Lfun-2) edge [above] node
  16581. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16582. \path[->,bend left=15] (Lfun-3) edge [above] node
  16583. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16584. \path[->,bend left=15] (F1-0) edge [left] node
  16585. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16586. \path[->,bend left=15] (F1-1) edge [below] node
  16587. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16588. \path[->,bend right=15] (F1-2) edge [above] node
  16589. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16590. \path[->,bend right=15] (F1-3) edge [above] node
  16591. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16592. \path[->,bend left=15] (F1-4) edge [right] node
  16593. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16594. \path[->,bend right=15] (F1-5) edge [below] node
  16595. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16596. \path[->,bend left=15] (F1-6) edge [above] node
  16597. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16598. \path[->] (C3-2) edge [right] node
  16599. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16600. \path[->,bend right=15] (x86-2) edge [right] node
  16601. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16602. \path[->,bend right=15] (x86-2-1) edge [below] node
  16603. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16604. \path[->,bend right=15] (x86-2-2) edge [right] node
  16605. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16606. \path[->,bend left=15] (x86-3) edge [above] node
  16607. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16608. \path[->,bend left=15] (x86-4) edge [right] node
  16609. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16610. \end{tikzpicture}
  16611. \fi}
  16612. {\if\edition\pythonEd\pythonColor
  16613. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16614. \node (Lfun) at (0,2) {\large \LangLam{}};
  16615. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16616. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16617. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16618. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16619. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16620. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16621. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16622. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16623. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16624. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16625. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16626. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16627. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16628. \path[->,bend left=15] (Lfun) edge [above] node
  16629. {\ttfamily\footnotesize shrink} (Lfun-2);
  16630. \path[->,bend left=15] (Lfun-2) edge [above] node
  16631. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16632. \path[->,bend left=15] (Lfun-3) edge [above] node
  16633. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16634. \path[->,bend left=15] (F1-0) edge [left] node
  16635. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16636. \path[->,bend left=15] (F1-1) edge [below] node
  16637. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16638. \path[->,bend left=15] (F1-2) edge [below] node
  16639. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16640. \path[->,bend right=15] (F1-3) edge [above] node
  16641. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16642. \path[->,bend right=15] (F1-5) edge [right] node
  16643. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16644. \path[->,bend left=15] (F1-6) edge [right] node
  16645. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16646. \path[->,bend right=15] (C3-2) edge [right] node
  16647. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16648. \path[->,bend right=15] (x86-2) edge [below] node
  16649. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16650. \path[->,bend right=15] (x86-3) edge [below] node
  16651. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16652. \path[->,bend left=15] (x86-4) edge [above] node
  16653. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16654. \end{tikzpicture}
  16655. \fi}
  16656. \end{tcolorbox}
  16657. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16658. functions.}
  16659. \label{fig:Llambda-passes}
  16660. \end{figure}
  16661. \clearpage
  16662. \section{Challenge: Optimize Closures}
  16663. \label{sec:optimize-closures}
  16664. In this chapter we compile lexically scoped functions into a
  16665. relatively efficient representation: flat closures. However, even this
  16666. representation comes with some overhead. For example, consider the
  16667. following program with a function \code{tail\_sum} that does not have
  16668. any free variables and where all the uses of \code{tail\_sum} are in
  16669. applications in which we know that only \code{tail\_sum} is being applied
  16670. (and not any other functions):
  16671. \begin{center}
  16672. \begin{minipage}{0.95\textwidth}
  16673. {\if\edition\racketEd
  16674. \begin{lstlisting}
  16675. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16676. (if (eq? n 0)
  16677. s
  16678. (tail_sum (- n 1) (+ n s))))
  16679. (+ (tail_sum 3 0) 36)
  16680. \end{lstlisting}
  16681. \fi}
  16682. {\if\edition\pythonEd\pythonColor
  16683. \begin{lstlisting}
  16684. def tail_sum(n : int, s : int) -> int:
  16685. if n == 0:
  16686. return s
  16687. else:
  16688. return tail_sum(n - 1, n + s)
  16689. print(tail_sum(3, 0) + 36)
  16690. \end{lstlisting}
  16691. \fi}
  16692. \end{minipage}
  16693. \end{center}
  16694. As described in this chapter, we uniformly apply closure conversion to
  16695. all functions, obtaining the following output for this program:
  16696. \begin{center}
  16697. \begin{minipage}{0.95\textwidth}
  16698. {\if\edition\racketEd
  16699. \begin{lstlisting}
  16700. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16701. (if (eq? n2 0)
  16702. s3
  16703. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16704. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16705. (define (main) : Integer
  16706. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16707. ((vector-ref clos6 0) clos6 3 0)) 27))
  16708. \end{lstlisting}
  16709. \fi}
  16710. {\if\edition\pythonEd\pythonColor
  16711. \begin{lstlisting}
  16712. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16713. if n_0 == 0:
  16714. return s_1
  16715. else:
  16716. return (begin: clos_2 = (tail_sum,)
  16717. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16718. def main() -> int :
  16719. print((begin: clos_4 = (tail_sum,)
  16720. clos_4[0](clos_4, 3, 0)) + 36)
  16721. return 0
  16722. \end{lstlisting}
  16723. \fi}
  16724. \end{minipage}
  16725. \end{center}
  16726. If this program were compiled according to the previous chapter, there
  16727. would be no allocation and the calls to \code{tail\_sum} would be
  16728. direct calls. In contrast, the program presented here allocates memory
  16729. for each closure and the calls to \code{tail\_sum} are indirect. These
  16730. two differences incur considerable overhead in a program such as this,
  16731. in which the allocations and indirect calls occur inside a tight loop.
  16732. One might think that this problem is trivial to solve: can't we just
  16733. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16734. and compile them to direct calls instead of treating it like a call to
  16735. a closure? We would also drop the new \code{fvs} parameter of
  16736. \code{tail\_sum}.
  16737. %
  16738. However, this problem is not so trivial, because a global function may
  16739. \emph{escape} and become involved in applications that also involve
  16740. closures. Consider the following example in which the application
  16741. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16742. application because the \code{lambda} may flow into \code{f}, but the
  16743. \code{inc} function might also flow into \code{f}:
  16744. \begin{center}
  16745. \begin{minipage}{\textwidth}
  16746. % lambda_test_30.rkt
  16747. {\if\edition\racketEd
  16748. \begin{lstlisting}
  16749. (define (inc [x : Integer]) : Integer
  16750. (+ x 1))
  16751. (let ([y (read)])
  16752. (let ([f (if (eq? (read) 0)
  16753. inc
  16754. (lambda: ([x : Integer]) : Integer (- x y)))])
  16755. (f 41)))
  16756. \end{lstlisting}
  16757. \fi}
  16758. {\if\edition\pythonEd\pythonColor
  16759. \begin{lstlisting}
  16760. def add1(x : int) -> int:
  16761. return x + 1
  16762. y = input_int()
  16763. g : Callable[[int], int] = lambda x: x - y
  16764. f = add1 if input_int() == 0 else g
  16765. print(f(41))
  16766. \end{lstlisting}
  16767. \fi}
  16768. \end{minipage}
  16769. \end{center}
  16770. If a global function name is used in any way other than as the
  16771. operator in a direct call, then we say that the function
  16772. \emph{escapes}. If a global function does not escape, then we do not
  16773. need to perform closure conversion on the function.
  16774. \begin{exercise}\normalfont\normalsize
  16775. Implement an auxiliary function for detecting which global
  16776. functions escape. Using that function, implement an improved version
  16777. of closure conversion that does not apply closure conversion to
  16778. global functions that do not escape but instead compiles them as
  16779. regular functions. Create several new test cases that check whether
  16780. your compiler properly detects whether global functions escape or not.
  16781. \end{exercise}
  16782. So far we have reduced the overhead of calling global functions, but
  16783. it would also be nice to reduce the overhead of calling a
  16784. \code{lambda} when we can determine at compile time which
  16785. \code{lambda} will be called. We refer to such calls as \emph{known
  16786. calls}. Consider the following example in which a \code{lambda} is
  16787. bound to \code{f} and then applied.
  16788. {\if\edition\racketEd
  16789. % lambda_test_9.rkt
  16790. \begin{lstlisting}
  16791. (let ([y (read)])
  16792. (let ([f (lambda: ([x : Integer]) : Integer
  16793. (+ x y))])
  16794. (f 21)))
  16795. \end{lstlisting}
  16796. \fi}
  16797. {\if\edition\pythonEd\pythonColor
  16798. \begin{lstlisting}
  16799. y = input_int()
  16800. f : Callable[[int],int] = lambda x: x + y
  16801. print(f(21))
  16802. \end{lstlisting}
  16803. \fi}
  16804. %
  16805. \noindent Closure conversion compiles the application
  16806. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16807. %
  16808. {\if\edition\racketEd
  16809. \begin{lstlisting}
  16810. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16811. (let ([y2 (vector-ref fvs6 1)])
  16812. (+ x3 y2)))
  16813. (define (main) : Integer
  16814. (let ([y2 (read)])
  16815. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16816. ((vector-ref f4 0) f4 21))))
  16817. \end{lstlisting}
  16818. \fi}
  16819. {\if\edition\pythonEd\pythonColor
  16820. \begin{lstlisting}
  16821. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16822. y_1 = fvs_4[1]
  16823. return x_2 + y_1[0]
  16824. def main() -> int:
  16825. y_1 = (777,)
  16826. y_1[0] = input_int()
  16827. f_0 = (lambda_3, y_1)
  16828. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16829. return 0
  16830. \end{lstlisting}
  16831. \fi}
  16832. %
  16833. \noindent However, we can instead compile the application
  16834. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16835. %
  16836. {\if\edition\racketEd
  16837. \begin{lstlisting}
  16838. (define (main) : Integer
  16839. (let ([y2 (read)])
  16840. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16841. ((fun-ref lambda5 1) f4 21))))
  16842. \end{lstlisting}
  16843. \fi}
  16844. {\if\edition\pythonEd\pythonColor
  16845. \begin{lstlisting}
  16846. def main() -> int:
  16847. y_1 = (777,)
  16848. y_1[0] = input_int()
  16849. f_0 = (lambda_3, y_1)
  16850. print(lambda_3(f_0, 21))
  16851. return 0
  16852. \end{lstlisting}
  16853. \fi}
  16854. The problem of determining which \code{lambda} will be called from a
  16855. particular application is quite challenging in general and the topic
  16856. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16857. following exercise we recommend that you compile an application to a
  16858. direct call when the operator is a variable and \racket{the variable
  16859. is \code{let}-bound to a closure}\python{the previous assignment to
  16860. the variable is a closure}. This can be accomplished by maintaining
  16861. an environment that maps variables to function names. Extend the
  16862. environment whenever you encounter a closure on the right-hand side of
  16863. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16864. name of the global function for the closure. This pass should come
  16865. after closure conversion.
  16866. \begin{exercise}\normalfont\normalsize
  16867. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16868. compiles known calls into direct calls. Verify that your compiler is
  16869. successful in this regard on several example programs.
  16870. \end{exercise}
  16871. These exercises only scratch the surface of closure optimization. A
  16872. good next step for the interested reader is to look at the work of
  16873. \citet{Keep:2012ab}.
  16874. \section{Further Reading}
  16875. The notion of lexically scoped functions predates modern computers by
  16876. about a decade. They were invented by \citet{Church:1932aa}, who
  16877. proposed the lambda calculus as a foundation for logic. Anonymous
  16878. functions were included in the LISP~\citep{McCarthy:1960dz}
  16879. programming language but were initially dynamically scoped. The Scheme
  16880. dialect of LISP adopted lexical scoping, and
  16881. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16882. Scheme programs. However, environments were represented as linked
  16883. lists, so variable look-up was linear in the size of the
  16884. environment. \citet{Appel91} gives a detailed description of several
  16885. closure representations. In this chapter we represent environments
  16886. using flat closures, which were invented by
  16887. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16888. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16889. closures, variable look-up is constant time but the time to create a
  16890. closure is proportional to the number of its free variables. Flat
  16891. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16892. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16893. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16894. % compilers)
  16895. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16896. \chapter{Dynamic Typing}
  16897. \label{ch:Ldyn}
  16898. \index{subject}{dynamic typing}
  16899. \setcounter{footnote}{0}
  16900. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16901. typed language that is a subset of \racket{Racket}\python{Python}. The
  16902. focus on dynamic typing is in contrast to the previous chapters, which
  16903. have studied the compilation of statically typed languages. In
  16904. dynamically typed languages such as \LangDyn{}, a particular
  16905. expression may produce a value of a different type each time it is
  16906. executed. Consider the following example with a conditional \code{if}
  16907. expression that may return a Boolean or an integer depending on the
  16908. input to the program:
  16909. % part of dynamic_test_25.rkt
  16910. {\if\edition\racketEd
  16911. \begin{lstlisting}
  16912. (not (if (eq? (read) 1) #f 0))
  16913. \end{lstlisting}
  16914. \fi}
  16915. {\if\edition\pythonEd\pythonColor
  16916. \begin{lstlisting}
  16917. not (False if input_int() == 1 else 0)
  16918. \end{lstlisting}
  16919. \fi}
  16920. Languages that allow expressions to produce different kinds of values
  16921. are called \emph{polymorphic}, a word composed of the Greek roots
  16922. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16923. There are several kinds of polymorphism in programming languages, such as
  16924. subtype polymorphism\index{subject}{subtype polymorphism} and
  16925. parametric polymorphism\index{subject}{parametric polymorphism}
  16926. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16927. study in this chapter does not have a special name; it is the kind
  16928. that arises in dynamically typed languages.
  16929. Another characteristic of dynamically typed languages is that
  16930. their primitive operations, such as \code{not}, are often defined to operate
  16931. on many different types of values. In fact, in
  16932. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16933. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16934. given anything else it returns \FALSE{}.
  16935. Furthermore, even when primitive operations restrict their inputs to
  16936. values of a certain type, this restriction is enforced at runtime
  16937. instead of during compilation. For example, the tuple read
  16938. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16939. results in a runtime error because the first argument must
  16940. be a tuple, not a Boolean.
  16941. \section{The \LangDyn{} Language}
  16942. \newcommand{\LdynGrammarRacket}{
  16943. \begin{array}{rcl}
  16944. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16945. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16946. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16947. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16948. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16949. \end{array}
  16950. }
  16951. \newcommand{\LdynASTRacket}{
  16952. \begin{array}{lcl}
  16953. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16954. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16955. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16956. \end{array}
  16957. }
  16958. \begin{figure}[tp]
  16959. \centering
  16960. \begin{tcolorbox}[colback=white]
  16961. \small
  16962. {\if\edition\racketEd
  16963. \[
  16964. \begin{array}{l}
  16965. \gray{\LintGrammarRacket{}} \\ \hline
  16966. \gray{\LvarGrammarRacket{}} \\ \hline
  16967. \gray{\LifGrammarRacket{}} \\ \hline
  16968. \gray{\LwhileGrammarRacket} \\ \hline
  16969. \gray{\LtupGrammarRacket} \\ \hline
  16970. \LdynGrammarRacket \\
  16971. \begin{array}{rcl}
  16972. \LangDynM{} &::=& \Def\ldots\; \Exp
  16973. \end{array}
  16974. \end{array}
  16975. \]
  16976. \fi}
  16977. {\if\edition\pythonEd\pythonColor
  16978. \[
  16979. \begin{array}{rcl}
  16980. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16981. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16982. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16983. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16984. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16985. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16986. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16987. \MID \CLEN{\Exp} \\
  16988. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16989. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16990. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16991. \MID \Var\mathop{\key{=}}\Exp \\
  16992. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16993. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16994. &\MID& \CRETURN{\Exp} \\
  16995. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16996. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16997. \end{array}
  16998. \]
  16999. \fi}
  17000. \end{tcolorbox}
  17001. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17002. \label{fig:r7-concrete-syntax}
  17003. \end{figure}
  17004. \begin{figure}[tp]
  17005. \centering
  17006. \begin{tcolorbox}[colback=white]
  17007. \small
  17008. {\if\edition\racketEd
  17009. \[
  17010. \begin{array}{l}
  17011. \gray{\LintASTRacket{}} \\ \hline
  17012. \gray{\LvarASTRacket{}} \\ \hline
  17013. \gray{\LifASTRacket{}} \\ \hline
  17014. \gray{\LwhileASTRacket} \\ \hline
  17015. \gray{\LtupASTRacket} \\ \hline
  17016. \LdynASTRacket \\
  17017. \begin{array}{lcl}
  17018. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17019. \end{array}
  17020. \end{array}
  17021. \]
  17022. \fi}
  17023. {\if\edition\pythonEd\pythonColor
  17024. \[
  17025. \begin{array}{rcl}
  17026. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17027. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17028. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17029. \MID \code{Is()} \\
  17030. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17031. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17032. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17033. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17034. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17035. &\MID& \VAR{\Var{}}
  17036. \MID \BOOL{\itm{bool}}
  17037. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17038. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17039. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17040. &\MID& \LEN{\Exp} \\
  17041. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17042. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17043. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17044. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17045. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17046. &\MID& \RETURN{\Exp} \\
  17047. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17048. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17049. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17050. \end{array}
  17051. \]
  17052. \fi}
  17053. \end{tcolorbox}
  17054. \caption{The abstract syntax of \LangDyn{}.}
  17055. \label{fig:r7-syntax}
  17056. \end{figure}
  17057. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17058. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17059. %
  17060. There is no type checker for \LangDyn{} because it checks types only
  17061. at runtime.
  17062. The definitional interpreter for \LangDyn{} is presented in
  17063. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17064. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17065. \INT{n}. Instead of simply returning the integer \code{n} (as
  17066. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17067. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17068. value} that combines an underlying value with a tag that identifies
  17069. what kind of value it is. We define the following \racket{struct}\python{class}
  17070. to represent tagged values:
  17071. %
  17072. {\if\edition\racketEd
  17073. \begin{lstlisting}
  17074. (struct Tagged (value tag) #:transparent)
  17075. \end{lstlisting}
  17076. \fi}
  17077. {\if\edition\pythonEd\pythonColor
  17078. \begin{minipage}{\textwidth}
  17079. \begin{lstlisting}
  17080. @dataclass(eq=True)
  17081. class Tagged(Value):
  17082. value : Value
  17083. tag : str
  17084. def __str__(self):
  17085. return str(self.value)
  17086. \end{lstlisting}
  17087. \end{minipage}
  17088. \fi}
  17089. %
  17090. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17091. \code{Vector}, and \code{Procedure}.}
  17092. %
  17093. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17094. \skey{tuple}, and \skey{function}.}
  17095. %
  17096. Tags are closely related to types but do not always capture all the
  17097. information that a type does.
  17098. %
  17099. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17100. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17101. Any)} is tagged with \code{Procedure}.}
  17102. %
  17103. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17104. is tagged with \skey{tuple} and a function of type
  17105. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17106. is tagged with \skey{function}.}
  17107. Next consider the match case for accessing the element of a tuple.
  17108. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17109. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17110. argument is a tuple and the second is an integer.
  17111. \racket{
  17112. If they are not, a \code{trapped-error} is raised. Recall from
  17113. section~\ref{sec:interp_Lint} that when a definition interpreter
  17114. raises a \code{trapped-error} error, the compiled code must also
  17115. signal an error by exiting with return code \code{255}. A
  17116. \code{trapped-error} is also raised if the index is not less than the
  17117. length of the vector.
  17118. }
  17119. %
  17120. \python{If they are not, an exception is raised. The compiled code
  17121. must also signal an error by exiting with return code \code{255}. A
  17122. exception is also raised if the index is not less than the length of the
  17123. tuple or if it is negative.}
  17124. \begin{figure}[tbp]
  17125. \begin{tcolorbox}[colback=white]
  17126. {\if\edition\racketEd
  17127. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17128. (define ((interp-Ldyn-exp env) ast)
  17129. (define recur (interp-Ldyn-exp env))
  17130. (match ast
  17131. [(Var x) (dict-ref env x)]
  17132. [(Int n) (Tagged n 'Integer)]
  17133. [(Bool b) (Tagged b 'Boolean)]
  17134. [(Lambda xs rt body)
  17135. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17136. [(Prim 'vector es)
  17137. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17138. [(Prim 'vector-ref (list e1 e2))
  17139. (define vec (recur e1)) (define i (recur e2))
  17140. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17141. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17142. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17143. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17144. [(Prim 'vector-set! (list e1 e2 e3))
  17145. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17146. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17147. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17148. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17149. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17150. (Tagged (void) 'Void)]
  17151. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17152. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17153. [(Prim 'or (list e1 e2))
  17154. (define v1 (recur e1))
  17155. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17156. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17157. [(Prim op (list e1))
  17158. #:when (set-member? type-predicates op)
  17159. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17160. [(Prim op es)
  17161. (define args (map recur es))
  17162. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17163. (unless (for/or ([expected-tags (op-tags op)])
  17164. (equal? expected-tags tags))
  17165. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17166. (tag-value
  17167. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17168. [(If q t f)
  17169. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17170. [(Apply f es)
  17171. (define new-f (recur f)) (define args (map recur es))
  17172. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17173. (match f-val
  17174. [`(function ,xs ,body ,lam-env)
  17175. (unless (eq? (length xs) (length args))
  17176. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17177. (define new-env (append (map cons xs args) lam-env))
  17178. ((interp-Ldyn-exp new-env) body)]
  17179. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17180. \end{lstlisting}
  17181. \fi}
  17182. {\if\edition\pythonEd\pythonColor
  17183. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17184. class InterpLdyn(InterpLlambda):
  17185. def interp_exp(self, e, env):
  17186. match e:
  17187. case Constant(n):
  17188. return self.tag(super().interp_exp(e, env))
  17189. case Tuple(es, Load()):
  17190. return self.tag(super().interp_exp(e, env))
  17191. case Lambda(params, body):
  17192. return self.tag(super().interp_exp(e, env))
  17193. case Call(Name('input_int'), []):
  17194. return self.tag(super().interp_exp(e, env))
  17195. case BinOp(left, Add(), right):
  17196. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17197. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17198. case BinOp(left, Sub(), right):
  17199. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17200. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17201. case UnaryOp(USub(), e1):
  17202. v = self.interp_exp(e1, env)
  17203. return self.tag(- self.untag(v, 'int', e))
  17204. case IfExp(test, body, orelse):
  17205. v = self.interp_exp(test, env)
  17206. if self.untag(v, 'bool', e):
  17207. return self.interp_exp(body, env)
  17208. else:
  17209. return self.interp_exp(orelse, env)
  17210. case UnaryOp(Not(), e1):
  17211. v = self.interp_exp(e1, env)
  17212. return self.tag(not self.untag(v, 'bool', e))
  17213. case BoolOp(And(), values):
  17214. left = values[0]; right = values[1]
  17215. l = self.interp_exp(left, env)
  17216. if self.untag(l, 'bool', e):
  17217. return self.interp_exp(right, env)
  17218. else:
  17219. return self.tag(False)
  17220. case BoolOp(Or(), values):
  17221. left = values[0]; right = values[1]
  17222. l = self.interp_exp(left, env)
  17223. if self.untag(l, 'bool', e):
  17224. return self.tag(True)
  17225. else:
  17226. return self.interp_exp(right, env)
  17227. \end{lstlisting}
  17228. \fi}
  17229. \end{tcolorbox}
  17230. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17231. \label{fig:interp-Ldyn}
  17232. \end{figure}
  17233. {\if\edition\pythonEd\pythonColor
  17234. \begin{figure}[tbp]
  17235. \begin{tcolorbox}[colback=white]
  17236. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17237. # interp_exp continued
  17238. case Compare(left, [cmp], [right]):
  17239. l = self.interp_exp(left, env)
  17240. r = self.interp_exp(right, env)
  17241. if l.tag == r.tag:
  17242. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17243. else:
  17244. raise Exception('interp Compare unexpected '
  17245. + repr(l) + ' ' + repr(r))
  17246. case Subscript(tup, index, Load()):
  17247. t = self.interp_exp(tup, env)
  17248. n = self.interp_exp(index, env)
  17249. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17250. case Call(Name('len'), [tup]):
  17251. t = self.interp_exp(tup, env)
  17252. return self.tag(len(self.untag(t, 'tuple', e)))
  17253. case _:
  17254. return self.tag(super().interp_exp(e, env))
  17255. def interp_stmt(self, s, env, cont):
  17256. match s:
  17257. case If(test, body, orelse):
  17258. v = self.interp_exp(test, env)
  17259. match self.untag(v, 'bool', s):
  17260. case True:
  17261. return self.interp_stmts(body + cont, env)
  17262. case False:
  17263. return self.interp_stmts(orelse + cont, env)
  17264. case While(test, body, []):
  17265. v = self.interp_exp(test, env)
  17266. if self.untag(v, 'bool', test):
  17267. self.interp_stmts(body + [s] + cont, env)
  17268. else:
  17269. return self.interp_stmts(cont, env)
  17270. case Assign([Subscript(tup, index)], value):
  17271. tup = self.interp_exp(tup, env)
  17272. index = self.interp_exp(index, env)
  17273. tup_v = self.untag(tup, 'tuple', s)
  17274. index_v = self.untag(index, 'int', s)
  17275. tup_v[index_v] = self.interp_exp(value, env)
  17276. return self.interp_stmts(cont, env)
  17277. case FunctionDef(name, params, bod, dl, returns, comment):
  17278. if isinstance(params, ast.arguments):
  17279. ps = [p.arg for p in params.args]
  17280. else:
  17281. ps = [x for (x,t) in params]
  17282. env[name] = self.tag(Function(name, ps, bod, env))
  17283. return self.interp_stmts(cont, env)
  17284. case _:
  17285. return super().interp_stmt(s, env, cont)
  17286. \end{lstlisting}
  17287. \end{tcolorbox}
  17288. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17289. \label{fig:interp-Ldyn-2}
  17290. \end{figure}
  17291. \fi}
  17292. \begin{figure}[tbp]
  17293. \begin{tcolorbox}[colback=white]
  17294. {\if\edition\racketEd
  17295. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17296. (define (interp-op op)
  17297. (match op
  17298. ['+ fx+]
  17299. ['- fx-]
  17300. ['read read-fixnum]
  17301. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17302. ['< (lambda (v1 v2)
  17303. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17304. ['<= (lambda (v1 v2)
  17305. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17306. ['> (lambda (v1 v2)
  17307. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17308. ['>= (lambda (v1 v2)
  17309. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17310. ['boolean? boolean?]
  17311. ['integer? fixnum?]
  17312. ['void? void?]
  17313. ['vector? vector?]
  17314. ['vector-length vector-length]
  17315. ['procedure? (match-lambda
  17316. [`(functions ,xs ,body ,env) #t] [else #f])]
  17317. [else (error 'interp-op "unknown operator" op)]))
  17318. (define (op-tags op)
  17319. (match op
  17320. ['+ '((Integer Integer))]
  17321. ['- '((Integer Integer) (Integer))]
  17322. ['read '(())]
  17323. ['not '((Boolean))]
  17324. ['< '((Integer Integer))]
  17325. ['<= '((Integer Integer))]
  17326. ['> '((Integer Integer))]
  17327. ['>= '((Integer Integer))]
  17328. ['vector-length '((Vector))]))
  17329. (define type-predicates
  17330. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17331. (define (tag-value v)
  17332. (cond [(boolean? v) (Tagged v 'Boolean)]
  17333. [(fixnum? v) (Tagged v 'Integer)]
  17334. [(procedure? v) (Tagged v 'Procedure)]
  17335. [(vector? v) (Tagged v 'Vector)]
  17336. [(void? v) (Tagged v 'Void)]
  17337. [else (error 'tag-value "unidentified value ~a" v)]))
  17338. (define (check-tag val expected ast)
  17339. (define tag (Tagged-tag val))
  17340. (unless (eq? tag expected)
  17341. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17342. \end{lstlisting}
  17343. \fi}
  17344. {\if\edition\pythonEd\pythonColor
  17345. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17346. class InterpLdyn(InterpLlambda):
  17347. def tag(self, v):
  17348. if v is True or v is False:
  17349. return Tagged(v, 'bool')
  17350. elif isinstance(v, int):
  17351. return Tagged(v, 'int')
  17352. elif isinstance(v, Function):
  17353. return Tagged(v, 'function')
  17354. elif isinstance(v, tuple):
  17355. return Tagged(v, 'tuple')
  17356. elif isinstance(v, type(None)):
  17357. return Tagged(v, 'none')
  17358. else:
  17359. raise Exception('tag: unexpected ' + repr(v))
  17360. def untag(self, v, expected_tag, ast):
  17361. match v:
  17362. case Tagged(val, tag) if tag == expected_tag:
  17363. return val
  17364. case _:
  17365. raise TrappedError('expected Tagged value with '
  17366. + expected_tag + ', not ' + ' ' + repr(v))
  17367. def apply_fun(self, fun, args, e):
  17368. f = self.untag(fun, 'function', e)
  17369. return super().apply_fun(f, args, e)
  17370. \end{lstlisting}
  17371. \fi}
  17372. \end{tcolorbox}
  17373. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17374. \label{fig:interp-Ldyn-aux}
  17375. \end{figure}
  17376. %\clearpage
  17377. \section{Representation of Tagged Values}
  17378. The interpreter for \LangDyn{} introduced a new kind of value: the
  17379. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17380. represent tagged values at the bit level. Because almost every
  17381. operation in \LangDyn{} involves manipulating tagged values, the
  17382. representation must be efficient. Recall that all our values are 64
  17383. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17384. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17385. $011$ for procedures, and $101$ for the void value\python{,
  17386. \key{None}}. We define the following auxiliary function for mapping
  17387. types to tag codes:
  17388. %
  17389. {\if\edition\racketEd
  17390. \begin{align*}
  17391. \itm{tagof}(\key{Integer}) &= 001 \\
  17392. \itm{tagof}(\key{Boolean}) &= 100 \\
  17393. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17394. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17395. \itm{tagof}(\key{Void}) &= 101
  17396. \end{align*}
  17397. \fi}
  17398. {\if\edition\pythonEd\pythonColor
  17399. \begin{align*}
  17400. \itm{tagof}(\key{IntType()}) &= 001 \\
  17401. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17402. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17403. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17404. \itm{tagof}(\key{type(None)}) &= 101
  17405. \end{align*}
  17406. \fi}
  17407. %
  17408. This stealing of 3 bits comes at some price: integers are now restricted
  17409. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17410. affect tuples and procedures because those values are addresses, and
  17411. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17412. they are always $000$. Thus, we do not lose information by overwriting
  17413. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17414. to recover the original address.
  17415. To make tagged values into first-class entities, we can give them a
  17416. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17417. operations such as \code{Inject} and \code{Project} for creating and
  17418. using them, yielding the statically typed \LangAny{} intermediate
  17419. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17420. section~\ref{sec:compile-r7}; in the next section we describe the
  17421. \LangAny{} language in greater detail.
  17422. \section{The \LangAny{} Language}
  17423. \label{sec:Rany-lang}
  17424. \newcommand{\LanyASTRacket}{
  17425. \begin{array}{lcl}
  17426. \Type &::= & \ANYTY \\
  17427. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17428. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17429. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17430. \itm{op} &::= & \code{any-vector-length}
  17431. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17432. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17433. \MID \code{procedure?} \MID \code{void?} \\
  17434. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17435. \end{array}
  17436. }
  17437. \newcommand{\LanyASTPython}{
  17438. \begin{array}{lcl}
  17439. \Type &::= & \key{AnyType()} \\
  17440. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17441. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17442. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17443. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17444. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17445. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17446. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17447. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17448. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17449. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17450. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17451. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17452. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17453. \end{array}
  17454. }
  17455. \begin{figure}[tp]
  17456. \centering
  17457. \begin{tcolorbox}[colback=white]
  17458. \small
  17459. {\if\edition\racketEd
  17460. \[
  17461. \begin{array}{l}
  17462. \gray{\LintOpAST} \\ \hline
  17463. \gray{\LvarASTRacket{}} \\ \hline
  17464. \gray{\LifASTRacket{}} \\ \hline
  17465. \gray{\LwhileASTRacket{}} \\ \hline
  17466. \gray{\LtupASTRacket{}} \\ \hline
  17467. \gray{\LfunASTRacket} \\ \hline
  17468. \gray{\LlambdaASTRacket} \\ \hline
  17469. \LanyASTRacket \\
  17470. \begin{array}{lcl}
  17471. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17472. \end{array}
  17473. \end{array}
  17474. \]
  17475. \fi}
  17476. {\if\edition\pythonEd\pythonColor
  17477. \[
  17478. \begin{array}{l}
  17479. \gray{\LintASTPython} \\ \hline
  17480. \gray{\LvarASTPython{}} \\ \hline
  17481. \gray{\LifASTPython{}} \\ \hline
  17482. \gray{\LwhileASTPython{}} \\ \hline
  17483. \gray{\LtupASTPython{}} \\ \hline
  17484. \gray{\LfunASTPython} \\ \hline
  17485. \gray{\LlambdaASTPython} \\ \hline
  17486. \LanyASTPython \\
  17487. \begin{array}{lcl}
  17488. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17489. \end{array}
  17490. \end{array}
  17491. \]
  17492. \fi}
  17493. \end{tcolorbox}
  17494. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17495. \label{fig:Lany-syntax}
  17496. \end{figure}
  17497. The definition of the abstract syntax of \LangAny{} is given in
  17498. figure~\ref{fig:Lany-syntax}.
  17499. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17500. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17501. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17502. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17503. converts the tagged value produced by expression $e$ into a value of
  17504. type $T$ or halts the program if the type tag does not match $T$.
  17505. %
  17506. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17507. restricted to be a flat type (the nonterminal $\FType$) which
  17508. simplifies the implementation and complies with the needs for
  17509. compiling \LangDyn{}.
  17510. The \racket{\code{any-vector}} operators
  17511. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17512. operations so that they can be applied to a value of type
  17513. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17514. tuple operations in that the index is not restricted to a literal
  17515. integer in the grammar but is allowed to be any expression.
  17516. \racket{The type predicates such as
  17517. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17518. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17519. the predicate and return {\FALSE} otherwise.}
  17520. The type checker for \LangAny{} is shown in
  17521. figure~\ref{fig:type-check-Lany}
  17522. %
  17523. \racket{ and uses the auxiliary functions presented in
  17524. figure~\ref{fig:type-check-Lany-aux}}.
  17525. %
  17526. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17527. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17528. \begin{figure}[btp]
  17529. \begin{tcolorbox}[colback=white]
  17530. {\if\edition\racketEd
  17531. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17532. (define type-check-Lany-class
  17533. (class type-check-Llambda-class
  17534. (super-new)
  17535. (inherit check-type-equal?)
  17536. (define/override (type-check-exp env)
  17537. (lambda (e)
  17538. (define recur (type-check-exp env))
  17539. (match e
  17540. [(Inject e1 ty)
  17541. (unless (flat-ty? ty)
  17542. (error 'type-check "may only inject from flat type, not ~a" ty))
  17543. (define-values (new-e1 e-ty) (recur e1))
  17544. (check-type-equal? e-ty ty e)
  17545. (values (Inject new-e1 ty) 'Any)]
  17546. [(Project e1 ty)
  17547. (unless (flat-ty? ty)
  17548. (error 'type-check "may only project to flat type, not ~a" ty))
  17549. (define-values (new-e1 e-ty) (recur e1))
  17550. (check-type-equal? e-ty 'Any e)
  17551. (values (Project new-e1 ty) ty)]
  17552. [(Prim 'any-vector-length (list e1))
  17553. (define-values (e1^ t1) (recur e1))
  17554. (check-type-equal? t1 'Any e)
  17555. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17556. [(Prim 'any-vector-ref (list e1 e2))
  17557. (define-values (e1^ t1) (recur e1))
  17558. (define-values (e2^ t2) (recur e2))
  17559. (check-type-equal? t1 'Any e)
  17560. (check-type-equal? t2 'Integer e)
  17561. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17562. [(Prim 'any-vector-set! (list e1 e2 e3))
  17563. (define-values (e1^ t1) (recur e1))
  17564. (define-values (e2^ t2) (recur e2))
  17565. (define-values (e3^ t3) (recur e3))
  17566. (check-type-equal? t1 'Any e)
  17567. (check-type-equal? t2 'Integer e)
  17568. (check-type-equal? t3 'Any e)
  17569. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17570. [(Prim pred (list e1))
  17571. #:when (set-member? (type-predicates) pred)
  17572. (define-values (new-e1 e-ty) (recur e1))
  17573. (check-type-equal? e-ty 'Any e)
  17574. (values (Prim pred (list new-e1)) 'Boolean)]
  17575. [(Prim 'eq? (list arg1 arg2))
  17576. (define-values (e1 t1) (recur arg1))
  17577. (define-values (e2 t2) (recur arg2))
  17578. (match* (t1 t2)
  17579. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17580. [(other wise) (check-type-equal? t1 t2 e)])
  17581. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17582. [else ((super type-check-exp env) e)])))
  17583. ))
  17584. \end{lstlisting}
  17585. \fi}
  17586. {\if\edition\pythonEd\pythonColor
  17587. \begin{lstlisting}
  17588. class TypeCheckLany(TypeCheckLlambda):
  17589. def type_check_exp(self, e, env):
  17590. match e:
  17591. case Inject(value, typ):
  17592. self.check_exp(value, typ, env)
  17593. return AnyType()
  17594. case Project(value, typ):
  17595. self.check_exp(value, AnyType(), env)
  17596. return typ
  17597. case Call(Name('any_tuple_load'), [tup, index]):
  17598. self.check_exp(tup, AnyType(), env)
  17599. self.check_exp(index, IntType(), env)
  17600. return AnyType()
  17601. case Call(Name('any_len'), [tup]):
  17602. self.check_exp(tup, AnyType(), env)
  17603. return IntType()
  17604. case Call(Name('arity'), [fun]):
  17605. ty = self.type_check_exp(fun, env)
  17606. match ty:
  17607. case FunctionType(ps, rt):
  17608. return IntType()
  17609. case TupleType([FunctionType(ps,rs)]):
  17610. return IntType()
  17611. case _:
  17612. raise Exception('type check arity unexpected ' + repr(ty))
  17613. case Call(Name('make_any'), [value, tag]):
  17614. self.type_check_exp(value, env)
  17615. self.check_exp(tag, IntType(), env)
  17616. return AnyType()
  17617. case AnnLambda(params, returns, body):
  17618. new_env = {x:t for (x,t) in env.items()}
  17619. for (x,t) in params:
  17620. new_env[x] = t
  17621. return_t = self.type_check_exp(body, new_env)
  17622. self.check_type_equal(returns, return_t, e)
  17623. return FunctionType([t for (x,t) in params], return_t)
  17624. case _:
  17625. return super().type_check_exp(e, env)
  17626. \end{lstlisting}
  17627. \fi}
  17628. \end{tcolorbox}
  17629. \caption{Type checker for the \LangAny{} language.}
  17630. \label{fig:type-check-Lany}
  17631. \end{figure}
  17632. {\if\edition\racketEd
  17633. \begin{figure}[tbp]
  17634. \begin{tcolorbox}[colback=white]
  17635. \begin{lstlisting}
  17636. (define/override (operator-types)
  17637. (append
  17638. '((integer? . ((Any) . Boolean))
  17639. (vector? . ((Any) . Boolean))
  17640. (procedure? . ((Any) . Boolean))
  17641. (void? . ((Any) . Boolean)))
  17642. (super operator-types)))
  17643. (define/public (type-predicates)
  17644. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17645. (define/public (flat-ty? ty)
  17646. (match ty
  17647. [(or `Integer `Boolean `Void) #t]
  17648. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17649. [`(,ts ... -> ,rt)
  17650. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17651. [else #f]))
  17652. \end{lstlisting}
  17653. \end{tcolorbox}
  17654. \caption{Auxiliary methods for type checking \LangAny{}.}
  17655. \label{fig:type-check-Lany-aux}
  17656. \end{figure}
  17657. \fi}
  17658. \begin{figure}[tbp]
  17659. \begin{tcolorbox}[colback=white]
  17660. {\if\edition\racketEd
  17661. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17662. (define interp-Lany-class
  17663. (class interp-Llambda-class
  17664. (super-new)
  17665. (define/override (interp-op op)
  17666. (match op
  17667. ['boolean? (match-lambda
  17668. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17669. [else #f])]
  17670. ['integer? (match-lambda
  17671. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17672. [else #f])]
  17673. ['vector? (match-lambda
  17674. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17675. [else #f])]
  17676. ['procedure? (match-lambda
  17677. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17678. [else #f])]
  17679. ['eq? (match-lambda*
  17680. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17681. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17682. [ls (apply (super interp-op op) ls)])]
  17683. ['any-vector-ref (lambda (v i)
  17684. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17685. ['any-vector-set! (lambda (v i a)
  17686. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17687. ['any-vector-length (lambda (v)
  17688. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17689. [else (super interp-op op)]))
  17690. (define/override ((interp-exp env) e)
  17691. (define recur (interp-exp env))
  17692. (match e
  17693. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17694. [(Project e ty2) (apply-project (recur e) ty2)]
  17695. [else ((super interp-exp env) e)]))
  17696. ))
  17697. (define (interp-Lany p)
  17698. (send (new interp-Lany-class) interp-program p))
  17699. \end{lstlisting}
  17700. \fi}
  17701. {\if\edition\pythonEd\pythonColor
  17702. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17703. class InterpLany(InterpLlambda):
  17704. def interp_exp(self, e, env):
  17705. match e:
  17706. case Inject(value, typ):
  17707. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17708. case Project(value, typ):
  17709. match self.interp_exp(value, env):
  17710. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17711. return val
  17712. case _:
  17713. raise Exception('failed project to ' + self.type_to_tag(typ))
  17714. case Call(Name('any_tuple_load'), [tup, index]):
  17715. match self.interp_exp(tup, env):
  17716. case Tagged(v, tag):
  17717. return v[self.interp_exp(index, env)]
  17718. case _:
  17719. raise Exception('in any_tuple_load untagged value')
  17720. case Call(Name('any_len'), [value]):
  17721. match self.interp_exp(value, env):
  17722. case Tagged(value, tag):
  17723. return len(value)
  17724. case _:
  17725. raise Exception('interp any_len untagged value')
  17726. case Call(Name('arity'), [fun]):
  17727. return self.arity(self.interp_exp(fun, env))
  17728. case _:
  17729. return super().interp_exp(e, env)
  17730. \end{lstlisting}
  17731. \fi}
  17732. \end{tcolorbox}
  17733. \caption{Interpreter for \LangAny{}.}
  17734. \label{fig:interp-Lany}
  17735. \end{figure}
  17736. \begin{figure}[btp]
  17737. \begin{tcolorbox}[colback=white]
  17738. {\if\edition\racketEd
  17739. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17740. (define/public (apply-inject v tg) (Tagged v tg))
  17741. (define/public (apply-project v ty2)
  17742. (define tag2 (any-tag ty2))
  17743. (match v
  17744. [(Tagged v1 tag1)
  17745. (cond
  17746. [(eq? tag1 tag2)
  17747. (match ty2
  17748. [`(Vector ,ts ...)
  17749. (define l1 ((interp-op 'vector-length) v1))
  17750. (cond
  17751. [(eq? l1 (length ts)) v1]
  17752. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17753. l1 (length ts))])]
  17754. [`(,ts ... -> ,rt)
  17755. (match v1
  17756. [`(function ,xs ,body ,env)
  17757. (cond [(eq? (length xs) (length ts)) v1]
  17758. [else
  17759. (error 'apply-project "arity mismatch ~a != ~a"
  17760. (length xs) (length ts))])]
  17761. [else (error 'apply-project "expected function not ~a" v1)])]
  17762. [else v1])]
  17763. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17764. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17765. \end{lstlisting}
  17766. \fi}
  17767. {\if\edition\pythonEd\pythonColor
  17768. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17769. class InterpLany(InterpLlambda):
  17770. def type_to_tag(self, typ):
  17771. match typ:
  17772. case FunctionType(params, rt):
  17773. return 'function'
  17774. case TupleType(fields):
  17775. return 'tuple'
  17776. case IntType():
  17777. return 'int'
  17778. case BoolType():
  17779. return 'bool'
  17780. case _:
  17781. raise Exception('type_to_tag unexpected ' + repr(typ))
  17782. def arity(self, v):
  17783. match v:
  17784. case Function(name, params, body, env):
  17785. return len(params)
  17786. case _:
  17787. raise Exception('Lany arity unexpected ' + repr(v))
  17788. \end{lstlisting}
  17789. \fi}
  17790. \end{tcolorbox}
  17791. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17792. \label{fig:interp-Lany-aux}
  17793. \end{figure}
  17794. \clearpage
  17795. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17796. \label{sec:compile-r7}
  17797. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17798. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17799. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17800. is that given any subexpression $e$ in the \LangDyn{} program, the
  17801. pass will produce an expression $e'$ in \LangAny{} that has type
  17802. \ANYTY{}. For example, the first row in
  17803. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17804. \TRUE{}, which must be injected to produce an expression of type
  17805. \ANYTY{}.
  17806. %
  17807. The compilation of addition is shown in the second row of
  17808. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17809. representative of many primitive operations: the arguments have type
  17810. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17811. be performed.
  17812. The compilation of \key{lambda} (third row of
  17813. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17814. produce type annotations: we simply use \ANYTY{}.
  17815. %
  17816. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17817. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17818. this pass has to account for some differences in behavior between
  17819. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17820. permissive than \LangAny{} regarding what kind of values can be used
  17821. in various places. For example, the condition of an \key{if} does
  17822. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17823. of the same type (in that case the result is \code{\#f}).}
  17824. \begin{figure}[btp]
  17825. \centering
  17826. \begin{tcolorbox}[colback=white]
  17827. {\if\edition\racketEd
  17828. \begin{tabular}{lll}
  17829. \begin{minipage}{0.27\textwidth}
  17830. \begin{lstlisting}
  17831. #t
  17832. \end{lstlisting}
  17833. \end{minipage}
  17834. &
  17835. $\Rightarrow$
  17836. &
  17837. \begin{minipage}{0.65\textwidth}
  17838. \begin{lstlisting}
  17839. (inject #t Boolean)
  17840. \end{lstlisting}
  17841. \end{minipage}
  17842. \\[2ex]\hline
  17843. \begin{minipage}{0.27\textwidth}
  17844. \begin{lstlisting}
  17845. (+ |$e_1$| |$e_2$|)
  17846. \end{lstlisting}
  17847. \end{minipage}
  17848. &
  17849. $\Rightarrow$
  17850. &
  17851. \begin{minipage}{0.65\textwidth}
  17852. \begin{lstlisting}
  17853. (inject
  17854. (+ (project |$e'_1$| Integer)
  17855. (project |$e'_2$| Integer))
  17856. Integer)
  17857. \end{lstlisting}
  17858. \end{minipage}
  17859. \\[2ex]\hline
  17860. \begin{minipage}{0.27\textwidth}
  17861. \begin{lstlisting}
  17862. (lambda (|$x_1 \ldots$|) |$e$|)
  17863. \end{lstlisting}
  17864. \end{minipage}
  17865. &
  17866. $\Rightarrow$
  17867. &
  17868. \begin{minipage}{0.65\textwidth}
  17869. \begin{lstlisting}
  17870. (inject
  17871. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17872. (Any|$\ldots$|Any -> Any))
  17873. \end{lstlisting}
  17874. \end{minipage}
  17875. \\[2ex]\hline
  17876. \begin{minipage}{0.27\textwidth}
  17877. \begin{lstlisting}
  17878. (|$e_0$| |$e_1 \ldots e_n$|)
  17879. \end{lstlisting}
  17880. \end{minipage}
  17881. &
  17882. $\Rightarrow$
  17883. &
  17884. \begin{minipage}{0.65\textwidth}
  17885. \begin{lstlisting}
  17886. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17887. \end{lstlisting}
  17888. \end{minipage}
  17889. \\[2ex]\hline
  17890. \begin{minipage}{0.27\textwidth}
  17891. \begin{lstlisting}
  17892. (vector-ref |$e_1$| |$e_2$|)
  17893. \end{lstlisting}
  17894. \end{minipage}
  17895. &
  17896. $\Rightarrow$
  17897. &
  17898. \begin{minipage}{0.65\textwidth}
  17899. \begin{lstlisting}
  17900. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17901. \end{lstlisting}
  17902. \end{minipage}
  17903. \\[2ex]\hline
  17904. \begin{minipage}{0.27\textwidth}
  17905. \begin{lstlisting}
  17906. (if |$e_1$| |$e_2$| |$e_3$|)
  17907. \end{lstlisting}
  17908. \end{minipage}
  17909. &
  17910. $\Rightarrow$
  17911. &
  17912. \begin{minipage}{0.65\textwidth}
  17913. \begin{lstlisting}
  17914. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17915. \end{lstlisting}
  17916. \end{minipage}
  17917. \\[2ex]\hline
  17918. \begin{minipage}{0.27\textwidth}
  17919. \begin{lstlisting}
  17920. (eq? |$e_1$| |$e_2$|)
  17921. \end{lstlisting}
  17922. \end{minipage}
  17923. &
  17924. $\Rightarrow$
  17925. &
  17926. \begin{minipage}{0.65\textwidth}
  17927. \begin{lstlisting}
  17928. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17929. \end{lstlisting}
  17930. \end{minipage}
  17931. \\[2ex]\hline
  17932. \begin{minipage}{0.27\textwidth}
  17933. \begin{lstlisting}
  17934. (not |$e_1$|)
  17935. \end{lstlisting}
  17936. \end{minipage}
  17937. &
  17938. $\Rightarrow$
  17939. &
  17940. \begin{minipage}{0.65\textwidth}
  17941. \begin{lstlisting}
  17942. (if (eq? |$e'_1$| (inject #f Boolean))
  17943. (inject #t Boolean) (inject #f Boolean))
  17944. \end{lstlisting}
  17945. \end{minipage}
  17946. \end{tabular}
  17947. \fi}
  17948. {\if\edition\pythonEd\pythonColor
  17949. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17950. \begin{minipage}{0.23\textwidth}
  17951. \begin{lstlisting}
  17952. True
  17953. \end{lstlisting}
  17954. \end{minipage}
  17955. &
  17956. $\Rightarrow$
  17957. &
  17958. \begin{minipage}{0.7\textwidth}
  17959. \begin{lstlisting}
  17960. Inject(True, BoolType())
  17961. \end{lstlisting}
  17962. \end{minipage}
  17963. \\[2ex]\hline
  17964. \begin{minipage}{0.23\textwidth}
  17965. \begin{lstlisting}
  17966. |$e_1$| + |$e_2$|
  17967. \end{lstlisting}
  17968. \end{minipage}
  17969. &
  17970. $\Rightarrow$
  17971. &
  17972. \begin{minipage}{0.7\textwidth}
  17973. \begin{lstlisting}
  17974. Inject(Project(|$e'_1$|, IntType())
  17975. + Project(|$e'_2$|, IntType()),
  17976. IntType())
  17977. \end{lstlisting}
  17978. \end{minipage}
  17979. \\[2ex]\hline
  17980. \begin{minipage}{0.23\textwidth}
  17981. \begin{lstlisting}
  17982. lambda |$x_1 \ldots$|: |$e$|
  17983. \end{lstlisting}
  17984. \end{minipage}
  17985. &
  17986. $\Rightarrow$
  17987. &
  17988. \begin{minipage}{0.7\textwidth}
  17989. \begin{lstlisting}
  17990. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17991. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17992. \end{lstlisting}
  17993. \end{minipage}
  17994. \\[2ex]\hline
  17995. \begin{minipage}{0.23\textwidth}
  17996. \begin{lstlisting}
  17997. |$e_0$|(|$e_1 \ldots e_n$|)
  17998. \end{lstlisting}
  17999. \end{minipage}
  18000. &
  18001. $\Rightarrow$
  18002. &
  18003. \begin{minipage}{0.7\textwidth}
  18004. \begin{lstlisting}
  18005. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18006. AnyType())), |$e'_1, \ldots, e'_n$|)
  18007. \end{lstlisting}
  18008. \end{minipage}
  18009. \\[2ex]\hline
  18010. \begin{minipage}{0.23\textwidth}
  18011. \begin{lstlisting}
  18012. |$e_1$|[|$e_2$|]
  18013. \end{lstlisting}
  18014. \end{minipage}
  18015. &
  18016. $\Rightarrow$
  18017. &
  18018. \begin{minipage}{0.7\textwidth}
  18019. \begin{lstlisting}
  18020. Call(Name('any_tuple_load'),
  18021. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18022. \end{lstlisting}
  18023. \end{minipage}
  18024. %% \begin{minipage}{0.23\textwidth}
  18025. %% \begin{lstlisting}
  18026. %% |$e_2$| if |$e_1$| else |$e_3$|
  18027. %% \end{lstlisting}
  18028. %% \end{minipage}
  18029. %% &
  18030. %% $\Rightarrow$
  18031. %% &
  18032. %% \begin{minipage}{0.7\textwidth}
  18033. %% \begin{lstlisting}
  18034. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18035. %% \end{lstlisting}
  18036. %% \end{minipage}
  18037. %% \\[2ex]\hline
  18038. %% \begin{minipage}{0.23\textwidth}
  18039. %% \begin{lstlisting}
  18040. %% (eq? |$e_1$| |$e_2$|)
  18041. %% \end{lstlisting}
  18042. %% \end{minipage}
  18043. %% &
  18044. %% $\Rightarrow$
  18045. %% &
  18046. %% \begin{minipage}{0.7\textwidth}
  18047. %% \begin{lstlisting}
  18048. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18049. %% \end{lstlisting}
  18050. %% \end{minipage}
  18051. %% \\[2ex]\hline
  18052. %% \begin{minipage}{0.23\textwidth}
  18053. %% \begin{lstlisting}
  18054. %% (not |$e_1$|)
  18055. %% \end{lstlisting}
  18056. %% \end{minipage}
  18057. %% &
  18058. %% $\Rightarrow$
  18059. %% &
  18060. %% \begin{minipage}{0.7\textwidth}
  18061. %% \begin{lstlisting}
  18062. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18063. %% (inject #t Boolean) (inject #f Boolean))
  18064. %% \end{lstlisting}
  18065. %% \end{minipage}
  18066. %% \\[2ex]\hline
  18067. \\\hline
  18068. \end{tabular}
  18069. \fi}
  18070. \end{tcolorbox}
  18071. \caption{Cast insertion.}
  18072. \label{fig:compile-r7-Lany}
  18073. \end{figure}
  18074. \section{Reveal Casts}
  18075. \label{sec:reveal-casts-Lany}
  18076. % TODO: define R'_6
  18077. In the \code{reveal\_casts} pass, we recommend compiling
  18078. \code{Project} into a conditional expression that checks whether the
  18079. value's tag matches the target type; if it does, the value is
  18080. converted to a value of the target type by removing the tag; if it
  18081. does not, the program exits.
  18082. %
  18083. {\if\edition\racketEd
  18084. %
  18085. To perform these actions we need a new primitive operation,
  18086. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18087. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18088. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18089. underlying value from a tagged value. The \code{ValueOf} form
  18090. includes the type for the underlying value that is used by the type
  18091. checker.
  18092. %
  18093. \fi}
  18094. %
  18095. {\if\edition\pythonEd\pythonColor
  18096. %
  18097. To perform these actions we need two new AST classes: \code{TagOf} and
  18098. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18099. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18100. the underlying value from a tagged value. The \code{ValueOf}
  18101. operation includes the type for the underlying value that is used by
  18102. the type checker.
  18103. %
  18104. \fi}
  18105. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18106. \code{Project} can be translated as follows:
  18107. \begin{center}
  18108. \begin{minipage}{1.0\textwidth}
  18109. {\if\edition\racketEd
  18110. \begin{lstlisting}
  18111. (Project |$e$| |$\FType$|)
  18112. |$\Rightarrow$|
  18113. (Let |$\itm{tmp}$| |$e'$|
  18114. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18115. (Int |$\itm{tagof}(\FType)$|)))
  18116. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18117. (Exit)))
  18118. \end{lstlisting}
  18119. \fi}
  18120. {\if\edition\pythonEd\pythonColor
  18121. \begin{lstlisting}
  18122. Project(|$e$|, |$\FType$|)
  18123. |$\Rightarrow$|
  18124. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18125. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18126. [Constant(|$\itm{tagof}(\FType)$|)]),
  18127. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18128. Call(Name('exit'), [])))
  18129. \end{lstlisting}
  18130. \fi}
  18131. \end{minipage}
  18132. \end{center}
  18133. If the target type of the projection is a tuple or function type, then
  18134. there is a bit more work to do. For tuples, check that the length of
  18135. the tuple type matches the length of the tuple. For functions, check
  18136. that the number of parameters in the function type matches the
  18137. function's arity.
  18138. Regarding \code{Inject}, we recommend compiling it to a slightly
  18139. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18140. takes a tag instead of a type.
  18141. \begin{center}
  18142. \begin{minipage}{1.0\textwidth}
  18143. {\if\edition\racketEd
  18144. \begin{lstlisting}
  18145. (Inject |$e$| |$\FType$|)
  18146. |$\Rightarrow$|
  18147. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18148. \end{lstlisting}
  18149. \fi}
  18150. {\if\edition\pythonEd\pythonColor
  18151. \begin{lstlisting}
  18152. Inject(|$e$|, |$\FType$|)
  18153. |$\Rightarrow$|
  18154. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18155. \end{lstlisting}
  18156. \fi}
  18157. \end{minipage}
  18158. \end{center}
  18159. {\if\edition\pythonEd\pythonColor
  18160. %
  18161. The introduction of \code{make\_any} makes it difficult to use
  18162. bidirectional type checking because we no longer have an expected type
  18163. to use for type checking the expression $e'$. Thus, we run into
  18164. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18165. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18166. annotated lambda) that contains its return type and the types of its
  18167. parameters.
  18168. %
  18169. \fi}
  18170. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18171. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18172. translation of \code{Project}.}
  18173. {\if\edition\racketEd
  18174. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18175. combine the projection action with the vector operation. Also, the
  18176. read and write operations allow arbitrary expressions for the index, so
  18177. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18178. cannot guarantee that the index is within bounds. Thus, we insert code
  18179. to perform bounds checking at runtime. The translation for
  18180. \code{any-vector-ref} is as follows, and the other two operations are
  18181. translated in a similar way:
  18182. \begin{center}
  18183. \begin{minipage}{0.95\textwidth}
  18184. \begin{lstlisting}
  18185. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18186. |$\Rightarrow$|
  18187. (Let |$v$| |$e'_1$|
  18188. (Let |$i$| |$e'_2$|
  18189. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18190. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18191. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18192. (Exit))
  18193. (Exit))))
  18194. \end{lstlisting}
  18195. \end{minipage}
  18196. \end{center}
  18197. \fi}
  18198. %
  18199. {\if\edition\pythonEd\pythonColor
  18200. %
  18201. The \code{any\_tuple\_load} operation combines the projection action
  18202. with the load operation. Also, the load operation allows arbitrary
  18203. expressions for the index, so the type checker for \LangAny{}
  18204. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18205. within bounds. Thus, we insert code to perform bounds checking at
  18206. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18207. \begin{lstlisting}
  18208. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18209. |$\Rightarrow$|
  18210. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18211. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18212. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18213. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18214. Call(Name('exit'), [])),
  18215. Call(Name('exit'), [])))
  18216. \end{lstlisting}
  18217. \fi}
  18218. {\if\edition\pythonEd\pythonColor
  18219. \section{Assignment Conversion}
  18220. \label{sec:convert-assignments-Lany}
  18221. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18222. \code{AnnLambda} AST classes.
  18223. \section{Closure Conversion}
  18224. \label{sec:closure-conversion-Lany}
  18225. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18226. \code{AnnLambda} AST classes.
  18227. \fi}
  18228. \section{Remove Complex Operands}
  18229. \label{sec:rco-Lany}
  18230. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18231. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18232. %
  18233. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18234. complex expressions. Their subexpressions must be atomic.}
  18235. \section{Explicate Control and \LangCAny{}}
  18236. \label{sec:explicate-Lany}
  18237. The output of \code{explicate\_control} is the \LangCAny{} language,
  18238. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18239. %
  18240. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18241. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18242. note that the index argument of \code{vector-ref} and
  18243. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18244. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18245. %
  18246. \python{Update the auxiliary functions \code{explicate\_tail},
  18247. \code{explicate\_effect}, and \code{explicate\_pred} as
  18248. appropriate to handle the new expressions in \LangCAny{}. }
  18249. \newcommand{\CanyASTPython}{
  18250. \begin{array}{lcl}
  18251. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18252. &\MID& \key{TagOf}\LP \Atm \RP
  18253. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18254. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18255. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18256. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18257. \end{array}
  18258. }
  18259. \newcommand{\CanyASTRacket}{
  18260. \begin{array}{lcl}
  18261. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18262. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18263. &\MID& \VALUEOF{\Atm}{\FType} \\
  18264. \Tail &::= & \LP\key{Exit}\RP
  18265. \end{array}
  18266. }
  18267. \begin{figure}[tp]
  18268. \begin{tcolorbox}[colback=white]
  18269. \small
  18270. {\if\edition\racketEd
  18271. \[
  18272. \begin{array}{l}
  18273. \gray{\CvarASTRacket} \\ \hline
  18274. \gray{\CifASTRacket} \\ \hline
  18275. \gray{\CloopASTRacket} \\ \hline
  18276. \gray{\CtupASTRacket} \\ \hline
  18277. \gray{\CfunASTRacket} \\ \hline
  18278. \gray{\ClambdaASTRacket} \\ \hline
  18279. \CanyASTRacket \\
  18280. \begin{array}{lcl}
  18281. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18282. \end{array}
  18283. \end{array}
  18284. \]
  18285. \fi}
  18286. {\if\edition\pythonEd\pythonColor
  18287. \[
  18288. \begin{array}{l}
  18289. \gray{\CifASTPython} \\ \hline
  18290. \gray{\CtupASTPython} \\ \hline
  18291. \gray{\CfunASTPython} \\ \hline
  18292. \gray{\ClambdaASTPython} \\ \hline
  18293. \CanyASTPython \\
  18294. \begin{array}{lcl}
  18295. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18296. \end{array}
  18297. \end{array}
  18298. \]
  18299. \fi}
  18300. \end{tcolorbox}
  18301. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18302. \label{fig:c5-syntax}
  18303. \end{figure}
  18304. \section{Select Instructions}
  18305. \label{sec:select-Lany}
  18306. \index{subject}{select instructions}
  18307. In the \code{select\_instructions} pass, we translate the primitive
  18308. operations on the \ANYTY{} type to x86 instructions that manipulate
  18309. the three tag bits of the tagged value. In the following descriptions,
  18310. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18311. of translating $e$ into an x86 argument:
  18312. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18313. We recommend compiling the
  18314. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18315. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18316. shifts the destination to the left by the number of bits specified by its
  18317. source argument (in this case three, the length of the tag), and it
  18318. preserves the sign of the integer. We use the \key{orq} instruction to
  18319. combine the tag and the value to form the tagged value.
  18320. {\if\edition\racketEd
  18321. \begin{lstlisting}
  18322. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18323. |$\Rightarrow$|
  18324. movq |$e'$|, |\itm{lhs'}|
  18325. salq $3, |\itm{lhs'}|
  18326. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18327. \end{lstlisting}
  18328. \fi}
  18329. %
  18330. {\if\edition\pythonEd\pythonColor
  18331. \begin{lstlisting}
  18332. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18333. |$\Rightarrow$|
  18334. movq |$e'$|, |\itm{lhs'}|
  18335. salq $3, |\itm{lhs'}|
  18336. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18337. \end{lstlisting}
  18338. \fi}
  18339. %
  18340. The instruction selection\index{subject}{instruction selection} for
  18341. tuples and procedures is different because there is no need to shift
  18342. them to the left. The rightmost 3 bits are already zeros, so we simply
  18343. combine the value and the tag using \key{orq}. \\
  18344. %
  18345. {\if\edition\racketEd
  18346. \begin{center}
  18347. \begin{minipage}{\textwidth}
  18348. \begin{lstlisting}
  18349. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18350. |$\Rightarrow$|
  18351. movq |$e'$|, |\itm{lhs'}|
  18352. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18353. \end{lstlisting}
  18354. \end{minipage}
  18355. \end{center}
  18356. \fi}
  18357. %
  18358. {\if\edition\pythonEd\pythonColor
  18359. \begin{lstlisting}
  18360. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18361. |$\Rightarrow$|
  18362. movq |$e'$|, |\itm{lhs'}|
  18363. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18364. \end{lstlisting}
  18365. \fi}
  18366. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18367. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18368. operation extracts the type tag from a value of type \ANYTY{}. The
  18369. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18370. bitwise-and of the value with $111$ ($7$ decimal).
  18371. %
  18372. {\if\edition\racketEd
  18373. \begin{lstlisting}
  18374. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18375. |$\Rightarrow$|
  18376. movq |$e'$|, |\itm{lhs'}|
  18377. andq $7, |\itm{lhs'}|
  18378. \end{lstlisting}
  18379. \fi}
  18380. %
  18381. {\if\edition\pythonEd\pythonColor
  18382. \begin{lstlisting}
  18383. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18384. |$\Rightarrow$|
  18385. movq |$e'$|, |\itm{lhs'}|
  18386. andq $7, |\itm{lhs'}|
  18387. \end{lstlisting}
  18388. \fi}
  18389. \paragraph{\code{ValueOf}}
  18390. The instructions for \key{ValueOf} also differ, depending on whether
  18391. the type $T$ is a pointer (tuple or function) or not (integer or
  18392. Boolean). The following shows the instruction
  18393. selection for integers and
  18394. Booleans, in which we produce an untagged value by shifting it to the
  18395. right by 3 bits:
  18396. %
  18397. {\if\edition\racketEd
  18398. \begin{lstlisting}
  18399. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18400. |$\Rightarrow$|
  18401. movq |$e'$|, |\itm{lhs'}|
  18402. sarq $3, |\itm{lhs'}|
  18403. \end{lstlisting}
  18404. \fi}
  18405. %
  18406. {\if\edition\pythonEd\pythonColor
  18407. \begin{lstlisting}
  18408. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18409. |$\Rightarrow$|
  18410. movq |$e'$|, |\itm{lhs'}|
  18411. sarq $3, |\itm{lhs'}|
  18412. \end{lstlisting}
  18413. \fi}
  18414. %
  18415. In the case for tuples and procedures, we zero out the rightmost 3
  18416. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18417. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18418. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18419. Finally, we apply \code{andq} with the tagged value to get the desired
  18420. result.
  18421. %
  18422. {\if\edition\racketEd
  18423. \begin{lstlisting}
  18424. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18425. |$\Rightarrow$|
  18426. movq $|$-8$|, |\itm{lhs'}|
  18427. andq |$e'$|, |\itm{lhs'}|
  18428. \end{lstlisting}
  18429. \fi}
  18430. %
  18431. {\if\edition\pythonEd\pythonColor
  18432. \begin{lstlisting}
  18433. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18434. |$\Rightarrow$|
  18435. movq $|$-8$|, |\itm{lhs'}|
  18436. andq |$e'$|, |\itm{lhs'}|
  18437. \end{lstlisting}
  18438. \fi}
  18439. %% \paragraph{Type Predicates} We leave it to the reader to
  18440. %% devise a sequence of instructions to implement the type predicates
  18441. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18442. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18443. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18444. operation combines the effect of \code{ValueOf} with accessing the
  18445. length of a tuple from the tag stored at the zero index of the tuple.
  18446. {\if\edition\racketEd
  18447. \begin{lstlisting}
  18448. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18449. |$\Longrightarrow$|
  18450. movq $|$-8$|, %r11
  18451. andq |$e_1'$|, %r11
  18452. movq 0(%r11), %r11
  18453. andq $126, %r11
  18454. sarq $1, %r11
  18455. movq %r11, |$\itm{lhs'}$|
  18456. \end{lstlisting}
  18457. \fi}
  18458. {\if\edition\pythonEd\pythonColor
  18459. \begin{lstlisting}
  18460. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18461. |$\Longrightarrow$|
  18462. movq $|$-8$|, %r11
  18463. andq |$e_1'$|, %r11
  18464. movq 0(%r11), %r11
  18465. andq $126, %r11
  18466. sarq $1, %r11
  18467. movq %r11, |$\itm{lhs'}$|
  18468. \end{lstlisting}
  18469. \fi}
  18470. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18471. This operation combines the effect of \code{ValueOf} with reading an
  18472. element of the tuple (see
  18473. section~\ref{sec:select-instructions-gc}). However, the index may be
  18474. an arbitrary atom, so instead of computing the offset at compile time,
  18475. we must generate instructions to compute the offset at runtime as
  18476. follows. Note the use of the new instruction \code{imulq}.
  18477. \begin{center}
  18478. \begin{minipage}{0.96\textwidth}
  18479. {\if\edition\racketEd
  18480. \begin{lstlisting}
  18481. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18482. |$\Longrightarrow$|
  18483. movq |$\neg 111$|, %r11
  18484. andq |$e_1'$|, %r11
  18485. movq |$e_2'$|, %rax
  18486. addq $1, %rax
  18487. imulq $8, %rax
  18488. addq %rax, %r11
  18489. movq 0(%r11) |$\itm{lhs'}$|
  18490. \end{lstlisting}
  18491. \fi}
  18492. %
  18493. {\if\edition\pythonEd\pythonColor
  18494. \begin{lstlisting}
  18495. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18496. |$\Longrightarrow$|
  18497. movq $|$-8$|, %r11
  18498. andq |$e_1'$|, %r11
  18499. movq |$e_2'$|, %rax
  18500. addq $1, %rax
  18501. imulq $8, %rax
  18502. addq %rax, %r11
  18503. movq 0(%r11) |$\itm{lhs'}$|
  18504. \end{lstlisting}
  18505. \fi}
  18506. \end{minipage}
  18507. \end{center}
  18508. % $ pacify font lock
  18509. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18510. %% The code generation for
  18511. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18512. %% analogous to the above translation for reading from a tuple.
  18513. \section{Register Allocation for \LangAny{} }
  18514. \label{sec:register-allocation-Lany}
  18515. \index{subject}{register allocation}
  18516. There is an interesting interaction between tagged values and garbage
  18517. collection that has an impact on register allocation. A variable of
  18518. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18519. that needs to be inspected and copied during garbage collection. Thus,
  18520. we need to treat variables of type \ANYTY{} in a similar way to
  18521. variables of tuple type for purposes of register allocation,
  18522. with particular attention to the following:
  18523. \begin{itemize}
  18524. \item If a variable of type \ANYTY{} is live during a function call,
  18525. then it must be spilled. This can be accomplished by changing
  18526. \code{build\_interference} to mark all variables of type \ANYTY{}
  18527. that are live after a \code{callq} to be interfering with all the
  18528. registers.
  18529. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18530. the root stack instead of the normal procedure call stack.
  18531. \end{itemize}
  18532. Another concern regarding the root stack is that the garbage collector
  18533. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18534. tagged value that points to a tuple, and (3) a tagged value that is
  18535. not a tuple. We enable this differentiation by choosing not to use the
  18536. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18537. reserved for identifying plain old pointers to tuples. That way, if
  18538. one of the first three bits is set, then we have a tagged value and
  18539. inspecting the tag can differentiate between tuples ($010$) and the
  18540. other kinds of values.
  18541. %% \begin{exercise}\normalfont
  18542. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18543. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18544. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18545. %% compiler on these new programs and all of your previously created test
  18546. %% programs.
  18547. %% \end{exercise}
  18548. \begin{exercise}\normalfont\normalsize
  18549. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18550. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18551. by removing type annotations. Add five more test programs that
  18552. specifically rely on the language being dynamically typed. That is,
  18553. they should not be legal programs in a statically typed language, but
  18554. nevertheless they should be valid \LangDyn{} programs that run to
  18555. completion without error.
  18556. \end{exercise}
  18557. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18558. for the compilation of \LangDyn{}.
  18559. \begin{figure}[bthp]
  18560. \begin{tcolorbox}[colback=white]
  18561. {\if\edition\racketEd
  18562. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18563. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18564. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18565. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18566. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18567. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18568. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18569. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18570. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18571. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18572. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18573. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18574. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18575. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18576. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18577. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18578. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18579. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18580. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18581. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18582. \path[->,bend left=15] (Lfun) edge [above] node
  18583. {\ttfamily\footnotesize shrink} (Lfun-2);
  18584. \path[->,bend left=15] (Lfun-2) edge [above] node
  18585. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18586. \path[->,bend left=15] (Lfun-3) edge [above] node
  18587. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18588. \path[->,bend left=15] (Lfun-4) edge [left] node
  18589. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18590. \path[->,bend left=15] (Lfun-5) edge [below] node
  18591. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18592. \path[->,bend left=15] (Lfun-6) edge [below] node
  18593. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18594. \path[->,bend right=15] (Lfun-7) edge [above] node
  18595. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18596. \path[->,bend right=15] (F1-2) edge [right] node
  18597. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18598. \path[->,bend right=15] (F1-3) edge [below] node
  18599. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18600. \path[->,bend right=15] (F1-4) edge [below] node
  18601. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18602. \path[->,bend left=15] (F1-5) edge [above] node
  18603. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18604. \path[->,bend left=10] (F1-6) edge [below] node
  18605. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18606. \path[->,bend left=15] (C3-2) edge [right] node
  18607. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18608. \path[->,bend right=15] (x86-2) edge [right] node
  18609. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18610. \path[->,bend right=15] (x86-2-1) edge [below] node
  18611. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18612. \path[->,bend right=15] (x86-2-2) edge [right] node
  18613. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18614. \path[->,bend left=15] (x86-3) edge [above] node
  18615. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18616. \path[->,bend left=15] (x86-4) edge [right] node
  18617. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18618. \end{tikzpicture}
  18619. \fi}
  18620. {\if\edition\pythonEd\pythonColor
  18621. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18622. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18623. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18624. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18625. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18626. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18627. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18628. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18629. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18630. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18631. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18632. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18633. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18634. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18635. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18636. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18637. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18638. \path[->,bend left=15] (Lfun) edge [above] node
  18639. {\ttfamily\footnotesize shrink} (Lfun-2);
  18640. \path[->,bend left=15] (Lfun-2) edge [above] node
  18641. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18642. \path[->,bend left=15] (Lfun-3) edge [above] node
  18643. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18644. \path[->,bend left=15] (Lfun-4) edge [left] node
  18645. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18646. \path[->,bend left=15] (Lfun-5) edge [below] node
  18647. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18648. \path[->,bend right=15] (Lfun-6) edge [above] node
  18649. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18650. \path[->,bend right=15] (Lfun-7) edge [above] node
  18651. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18652. \path[->,bend right=15] (F1-2) edge [right] node
  18653. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18654. \path[->,bend right=15] (F1-3) edge [below] node
  18655. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18656. \path[->,bend left=15] (F1-5) edge [above] node
  18657. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18658. \path[->,bend left=10] (F1-6) edge [below] node
  18659. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18660. \path[->,bend right=15] (C3-2) edge [right] node
  18661. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18662. \path[->,bend right=15] (x86-2) edge [below] node
  18663. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18664. \path[->,bend right=15] (x86-3) edge [below] node
  18665. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18666. \path[->,bend left=15] (x86-4) edge [above] node
  18667. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18668. \end{tikzpicture}
  18669. \fi}
  18670. \end{tcolorbox}
  18671. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18672. \label{fig:Ldyn-passes}
  18673. \end{figure}
  18674. % Further Reading
  18675. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18676. %% {\if\edition\pythonEd\pythonColor
  18677. %% \chapter{Objects}
  18678. %% \label{ch:Lobject}
  18679. %% \index{subject}{objects}
  18680. %% \index{subject}{classes}
  18681. %% \setcounter{footnote}{0}
  18682. %% \fi}
  18683. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18684. \chapter{Gradual Typing}
  18685. \label{ch:Lgrad}
  18686. \index{subject}{gradual typing}
  18687. \setcounter{footnote}{0}
  18688. This chapter studies the language \LangGrad{}, in which the programmer
  18689. can choose between static and dynamic type checking in different parts
  18690. of a program, thereby mixing the statically typed \LangLam{} language
  18691. with the dynamically typed \LangDyn{}. There are several approaches to
  18692. mixing static and dynamic typing, including multilanguage
  18693. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18694. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18695. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18696. programmer controls the amount of static versus dynamic checking by
  18697. adding or removing type annotations on parameters and
  18698. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18699. The definition of the concrete syntax of \LangGrad{} is shown in
  18700. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18701. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18702. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18703. annotations are optional, which is specified in the grammar using the
  18704. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18705. annotations are not optional, but we use the \CANYTY{} type when a type
  18706. annotation is absent.
  18707. %
  18708. Both the type checker and the interpreter for \LangGrad{} require some
  18709. interesting changes to enable gradual typing, which we discuss in the
  18710. next two sections.
  18711. \newcommand{\LgradGrammarRacket}{
  18712. \begin{array}{lcl}
  18713. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18714. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18715. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18716. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18717. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18718. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18719. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18720. \end{array}
  18721. }
  18722. \newcommand{\LgradASTRacket}{
  18723. \begin{array}{lcl}
  18724. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18725. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18726. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18727. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18728. \itm{op} &::=& \code{procedure-arity} \\
  18729. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18730. \end{array}
  18731. }
  18732. \newcommand{\LgradGrammarPython}{
  18733. \begin{array}{lcl}
  18734. \Type &::=& \key{Any}
  18735. \MID \key{int}
  18736. \MID \key{bool}
  18737. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18738. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18739. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18740. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18741. \MID \CARITY{\Exp} \\
  18742. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18743. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18744. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18745. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18746. \end{array}
  18747. }
  18748. \newcommand{\LgradASTPython}{
  18749. \begin{array}{lcl}
  18750. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18751. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18752. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18753. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18754. &\MID& \ARITY{\Exp} \\
  18755. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18756. \MID \RETURN{\Exp} \\
  18757. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18758. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18759. \end{array}
  18760. }
  18761. \begin{figure}[tbp]
  18762. \centering
  18763. \begin{tcolorbox}[colback=white]
  18764. \vspace{-5pt}
  18765. \small
  18766. {\if\edition\racketEd
  18767. \[
  18768. \begin{array}{l}
  18769. \gray{\LintGrammarRacket{}} \\ \hline
  18770. \gray{\LvarGrammarRacket{}} \\ \hline
  18771. \gray{\LifGrammarRacket{}} \\ \hline
  18772. \gray{\LwhileGrammarRacket} \\ \hline
  18773. \gray{\LtupGrammarRacket} \\ \hline
  18774. \LgradGrammarRacket \\
  18775. \begin{array}{lcl}
  18776. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18777. \end{array}
  18778. \end{array}
  18779. \]
  18780. \fi}
  18781. {\if\edition\pythonEd\pythonColor
  18782. \[
  18783. \begin{array}{l}
  18784. \gray{\LintGrammarPython{}} \\ \hline
  18785. \gray{\LvarGrammarPython{}} \\ \hline
  18786. \gray{\LifGrammarPython{}} \\ \hline
  18787. \gray{\LwhileGrammarPython} \\ \hline
  18788. \gray{\LtupGrammarPython} \\ \hline
  18789. \LgradGrammarPython \\
  18790. \begin{array}{lcl}
  18791. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18792. \end{array}
  18793. \end{array}
  18794. \]
  18795. \fi}
  18796. \end{tcolorbox}
  18797. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18798. \label{fig:Lgrad-concrete-syntax}
  18799. \end{figure}
  18800. \begin{figure}[tbp]
  18801. \centering
  18802. \begin{tcolorbox}[colback=white]
  18803. \small
  18804. {\if\edition\racketEd
  18805. \[
  18806. \begin{array}{l}
  18807. \gray{\LintOpAST} \\ \hline
  18808. \gray{\LvarASTRacket{}} \\ \hline
  18809. \gray{\LifASTRacket{}} \\ \hline
  18810. \gray{\LwhileASTRacket{}} \\ \hline
  18811. \gray{\LtupASTRacket{}} \\ \hline
  18812. \LgradASTRacket \\
  18813. \begin{array}{lcl}
  18814. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18815. \end{array}
  18816. \end{array}
  18817. \]
  18818. \fi}
  18819. {\if\edition\pythonEd\pythonColor
  18820. \[
  18821. \begin{array}{l}
  18822. \gray{\LintASTPython{}} \\ \hline
  18823. \gray{\LvarASTPython{}} \\ \hline
  18824. \gray{\LifASTPython{}} \\ \hline
  18825. \gray{\LwhileASTPython} \\ \hline
  18826. \gray{\LtupASTPython} \\ \hline
  18827. \LgradASTPython \\
  18828. \begin{array}{lcl}
  18829. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18830. \end{array}
  18831. \end{array}
  18832. \]
  18833. \fi}
  18834. \end{tcolorbox}
  18835. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18836. \label{fig:Lgrad-syntax}
  18837. \end{figure}
  18838. % TODO: more road map -Jeremy
  18839. %\clearpage
  18840. \section{Type Checking \LangGrad{}}
  18841. \label{sec:gradual-type-check}
  18842. We begin by discussing the type checking of a partially typed variant
  18843. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18844. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18845. statically typed, so there is nothing special happening there with
  18846. respect to type checking. On the other hand, the \code{inc} function
  18847. does not have type annotations, so the type checker assigns the type
  18848. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18849. \code{+} operator inside \code{inc}. It expects both arguments to have
  18850. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18851. a gradually typed language, such differences are allowed so long as
  18852. the types are \emph{consistent}; that is, they are equal except in
  18853. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18854. is consistent with every other type. Figure~\ref{fig:consistent}
  18855. shows the definition of the
  18856. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18857. %
  18858. So the type checker allows the \code{+} operator to be applied
  18859. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18860. %
  18861. Next consider the call to the \code{map} function shown in
  18862. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18863. tuple. The \code{inc} function has type
  18864. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18865. but parameter \code{f} of \code{map} has type
  18866. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18867. The type checker for \LangGrad{} accepts this call because the two types are
  18868. consistent.
  18869. \begin{figure}[hbtp]
  18870. % gradual_test_9.rkt
  18871. \begin{tcolorbox}[colback=white]
  18872. {\if\edition\racketEd
  18873. \begin{lstlisting}
  18874. (define (map [f : (Integer -> Integer)]
  18875. [v : (Vector Integer Integer)])
  18876. : (Vector Integer Integer)
  18877. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18878. (define (inc x) (+ x 1))
  18879. (vector-ref (map inc (vector 0 41)) 1)
  18880. \end{lstlisting}
  18881. \fi}
  18882. {\if\edition\pythonEd\pythonColor
  18883. \begin{lstlisting}
  18884. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18885. return f(v[0]), f(v[1])
  18886. def inc(x):
  18887. return x + 1
  18888. t = map(inc, (0, 41))
  18889. print(t[1])
  18890. \end{lstlisting}
  18891. \fi}
  18892. \end{tcolorbox}
  18893. \caption{A partially typed version of the \code{map} example.}
  18894. \label{fig:gradual-map}
  18895. \end{figure}
  18896. \begin{figure}[tbp]
  18897. \begin{tcolorbox}[colback=white]
  18898. {\if\edition\racketEd
  18899. \begin{lstlisting}
  18900. (define/public (consistent? t1 t2)
  18901. (match* (t1 t2)
  18902. [('Integer 'Integer) #t]
  18903. [('Boolean 'Boolean) #t]
  18904. [('Void 'Void) #t]
  18905. [('Any t2) #t]
  18906. [(t1 'Any) #t]
  18907. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18908. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18909. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18910. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18911. (consistent? rt1 rt2))]
  18912. [(other wise) #f]))
  18913. \end{lstlisting}
  18914. \fi}
  18915. {\if\edition\pythonEd\pythonColor
  18916. \begin{lstlisting}
  18917. def consistent(self, t1, t2):
  18918. match (t1, t2):
  18919. case (AnyType(), _):
  18920. return True
  18921. case (_, AnyType()):
  18922. return True
  18923. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18924. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18925. case (TupleType(ts1), TupleType(ts2)):
  18926. return all(map(self.consistent, ts1, ts2))
  18927. case (_, _):
  18928. return t1 == t2
  18929. \end{lstlisting}
  18930. \fi}
  18931. \vspace{-5pt}
  18932. \end{tcolorbox}
  18933. \caption{The consistency method on types.}
  18934. \label{fig:consistent}
  18935. \end{figure}
  18936. It is also helpful to consider how gradual typing handles programs with an
  18937. error, such as applying \code{map} to a function that sometimes
  18938. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18939. type checker for \LangGrad{} accepts this program because the type of
  18940. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18941. \code{map}; that is,
  18942. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18943. is consistent with
  18944. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18945. One might say that a gradual type checker is optimistic in that it
  18946. accepts programs that might execute without a runtime type error.
  18947. %
  18948. The definition of the type checker for \LangGrad{} is shown in
  18949. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18950. and \ref{fig:type-check-Lgradual-3}.
  18951. %% \begin{figure}[tp]
  18952. %% \centering
  18953. %% \fbox{
  18954. %% \begin{minipage}{0.96\textwidth}
  18955. %% \small
  18956. %% \[
  18957. %% \begin{array}{lcl}
  18958. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18959. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18960. %% \end{array}
  18961. %% \]
  18962. %% \end{minipage}
  18963. %% }
  18964. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18965. %% \label{fig:Lgrad-prime-syntax}
  18966. %% \end{figure}
  18967. \begin{figure}[tbp]
  18968. \begin{tcolorbox}[colback=white]
  18969. {\if\edition\racketEd
  18970. \begin{lstlisting}
  18971. (define (map [f : (Integer -> Integer)]
  18972. [v : (Vector Integer Integer)])
  18973. : (Vector Integer Integer)
  18974. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18975. (define (inc x) (+ x 1))
  18976. (define (true) #t)
  18977. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18978. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18979. \end{lstlisting}
  18980. \fi}
  18981. {\if\edition\pythonEd\pythonColor
  18982. \begin{lstlisting}
  18983. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18984. return f(v[0]), f(v[1])
  18985. def inc(x):
  18986. return x + 1
  18987. def true():
  18988. return True
  18989. def maybe_inc(x):
  18990. return inc(x) if input_int() == 0 else true()
  18991. t = map(maybe_inc, (0, 41))
  18992. print(t[1])
  18993. \end{lstlisting}
  18994. \fi}
  18995. \vspace{-5pt}
  18996. \end{tcolorbox}
  18997. \caption{A variant of the \code{map} example with an error.}
  18998. \label{fig:map-maybe_inc}
  18999. \end{figure}
  19000. Running this program with input \code{1} triggers an
  19001. error when the \code{maybe\_inc} function returns
  19002. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19003. performs checking at runtime to ensure the integrity of the static
  19004. types, such as the
  19005. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19006. annotation on
  19007. parameter \code{f} of \code{map}.
  19008. Here we give a preview of how the runtime checking is accomplished;
  19009. the following sections provide the details.
  19010. The runtime checking is carried out by a new \code{Cast} AST node that
  19011. is generated in a new pass named \code{cast\_insert}. The output of
  19012. \code{cast\_insert} is a program in the \LangCast{} language, which
  19013. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19014. %
  19015. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19016. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19017. inserted every time the type checker encounters two types that are
  19018. consistent but not equal. In the \code{inc} function, \code{x} is
  19019. cast to \INTTY{} and the result of the \code{+} is cast to
  19020. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19021. is cast from
  19022. \racket{\code{(Any -> Any)}}
  19023. \python{\code{Callable[[Any], Any]}}
  19024. to
  19025. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19026. %
  19027. In the next section we see how to interpret the \code{Cast} node.
  19028. \begin{figure}[btp]
  19029. \begin{tcolorbox}[colback=white]
  19030. {\if\edition\racketEd
  19031. \begin{lstlisting}
  19032. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19033. : (Vector Integer Integer)
  19034. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19035. (define (inc [x : Any]) : Any
  19036. (cast (+ (cast x Any Integer) 1) Integer Any))
  19037. (define (true) : Any (cast #t Boolean Any))
  19038. (define (maybe_inc [x : Any]) : Any
  19039. (if (eq? 0 (read)) (inc x) (true)))
  19040. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19041. (vector 0 41)) 0)
  19042. \end{lstlisting}
  19043. \fi}
  19044. {\if\edition\pythonEd\pythonColor
  19045. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19046. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19047. return f(v[0]), f(v[1])
  19048. def inc(x : Any) -> Any:
  19049. return Cast(Cast(x, Any, int) + 1, int, Any)
  19050. def true() -> Any:
  19051. return Cast(True, bool, Any)
  19052. def maybe_inc(x : Any) -> Any:
  19053. return inc(x) if input_int() == 0 else true()
  19054. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19055. (0, 41))
  19056. print(t[1])
  19057. \end{lstlisting}
  19058. \fi}
  19059. \vspace{-5pt}
  19060. \end{tcolorbox}
  19061. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19062. and \code{maybe\_inc} example.}
  19063. \label{fig:map-cast}
  19064. \end{figure}
  19065. {\if\edition\pythonEd\pythonColor
  19066. \begin{figure}[tbp]
  19067. \begin{tcolorbox}[colback=white]
  19068. \begin{lstlisting}
  19069. class TypeCheckLgrad(TypeCheckLlambda):
  19070. def type_check_exp(self, e, env) -> Type:
  19071. match e:
  19072. case Name(id):
  19073. return env[id]
  19074. case Constant(value) if isinstance(value, bool):
  19075. return BoolType()
  19076. case Constant(value) if isinstance(value, int):
  19077. return IntType()
  19078. case Call(Name('input_int'), []):
  19079. return IntType()
  19080. case BinOp(left, op, right):
  19081. left_type = self.type_check_exp(left, env)
  19082. self.check_consistent(left_type, IntType(), left)
  19083. right_type = self.type_check_exp(right, env)
  19084. self.check_consistent(right_type, IntType(), right)
  19085. return IntType()
  19086. case IfExp(test, body, orelse):
  19087. test_t = self.type_check_exp(test, env)
  19088. self.check_consistent(test_t, BoolType(), test)
  19089. body_t = self.type_check_exp(body, env)
  19090. orelse_t = self.type_check_exp(orelse, env)
  19091. self.check_consistent(body_t, orelse_t, e)
  19092. return self.join_types(body_t, orelse_t)
  19093. case Call(func, args):
  19094. func_t = self.type_check_exp(func, env)
  19095. args_t = [self.type_check_exp(arg, env) for arg in args]
  19096. match func_t:
  19097. case FunctionType(params_t, return_t) \
  19098. if len(params_t) == len(args_t):
  19099. for (arg_t, param_t) in zip(args_t, params_t):
  19100. self.check_consistent(param_t, arg_t, e)
  19101. return return_t
  19102. case AnyType():
  19103. return AnyType()
  19104. case _:
  19105. raise Exception('type_check_exp: in call, unexpected '
  19106. + repr(func_t))
  19107. ...
  19108. case _:
  19109. raise Exception('type_check_exp: unexpected ' + repr(e))
  19110. \end{lstlisting}
  19111. \end{tcolorbox}
  19112. \caption{Type checking expressions in the \LangGrad{} language.}
  19113. \label{fig:type-check-Lgradual-1}
  19114. \end{figure}
  19115. \begin{figure}[tbp]
  19116. \begin{tcolorbox}[colback=white]
  19117. \begin{lstlisting}
  19118. def check_exp(self, e, expected_ty, env):
  19119. match e:
  19120. case Lambda(params, body):
  19121. match expected_ty:
  19122. case FunctionType(params_t, return_t):
  19123. new_env = env.copy().update(zip(params, params_t))
  19124. e.has_type = expected_ty
  19125. body_ty = self.type_check_exp(body, new_env)
  19126. self.check_consistent(body_ty, return_t)
  19127. case AnyType():
  19128. new_env = env.copy().update((p, AnyType()) for p in params)
  19129. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19130. body_ty = self.type_check_exp(body, new_env)
  19131. case _:
  19132. raise Exception('lambda is not of type ' + str(expected_ty))
  19133. case _:
  19134. e_ty = self.type_check_exp(e, env)
  19135. self.check_consistent(e_ty, expected_ty, e)
  19136. \end{lstlisting}
  19137. \end{tcolorbox}
  19138. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19139. \label{fig:type-check-Lgradual-2}
  19140. \end{figure}
  19141. \begin{figure}[tbp]
  19142. \begin{tcolorbox}[colback=white]
  19143. \begin{lstlisting}
  19144. def type_check_stmt(self, s, env, return_type):
  19145. match s:
  19146. case Assign([Name(id)], value):
  19147. value_ty = self.type_check_exp(value, env)
  19148. if id in env:
  19149. self.check_consistent(env[id], value_ty, value)
  19150. else:
  19151. env[id] = value_ty
  19152. ...
  19153. case _:
  19154. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19155. def type_check_stmts(self, ss, env, return_type):
  19156. for s in ss:
  19157. self.type_check_stmt(s, env, return_type)
  19158. \end{lstlisting}
  19159. \end{tcolorbox}
  19160. \caption{Type checking statements in the \LangGrad{} language.}
  19161. \label{fig:type-check-Lgradual-3}
  19162. \end{figure}
  19163. \clearpage
  19164. \begin{figure}[tbp]
  19165. \begin{tcolorbox}[colback=white]
  19166. \begin{lstlisting}
  19167. def join_types(self, t1, t2):
  19168. match (t1, t2):
  19169. case (AnyType(), _):
  19170. return t2
  19171. case (_, AnyType()):
  19172. return t1
  19173. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19174. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19175. self.join_types(rt1,rt2))
  19176. case (TupleType(ts1), TupleType(ts2)):
  19177. return TupleType(list(map(self.join_types, ts1, ts2)))
  19178. case (_, _):
  19179. return t1
  19180. def check_consistent(self, t1, t2, e):
  19181. if not self.consistent(t1, t2):
  19182. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19183. + repr(t2) + ' in ' + repr(e))
  19184. \end{lstlisting}
  19185. \end{tcolorbox}
  19186. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19187. \label{fig:type-check-Lgradual-aux}
  19188. \end{figure}
  19189. \fi}
  19190. {\if\edition\racketEd
  19191. \begin{figure}[tbp]
  19192. \begin{tcolorbox}[colback=white]
  19193. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19194. (define/override (type-check-exp env)
  19195. (lambda (e)
  19196. (define recur (type-check-exp env))
  19197. (match e
  19198. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19199. (define-values (new-es ts)
  19200. (for/lists (exprs types) ([e es])
  19201. (recur e)))
  19202. (define t-ret (type-check-op op ts e))
  19203. (values (Prim op new-es) t-ret)]
  19204. [(Prim 'eq? (list e1 e2))
  19205. (define-values (e1^ t1) (recur e1))
  19206. (define-values (e2^ t2) (recur e2))
  19207. (check-consistent? t1 t2 e)
  19208. (define T (meet t1 t2))
  19209. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19210. [(Prim 'and (list e1 e2))
  19211. (recur (If e1 e2 (Bool #f)))]
  19212. [(Prim 'or (list e1 e2))
  19213. (define tmp (gensym 'tmp))
  19214. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19215. [(If e1 e2 e3)
  19216. (define-values (e1^ T1) (recur e1))
  19217. (define-values (e2^ T2) (recur e2))
  19218. (define-values (e3^ T3) (recur e3))
  19219. (check-consistent? T1 'Boolean e)
  19220. (check-consistent? T2 T3 e)
  19221. (define Tif (meet T2 T3))
  19222. (values (If e1^ e2^ e3^) Tif)]
  19223. [(SetBang x e1)
  19224. (define-values (e1^ T1) (recur e1))
  19225. (define varT (dict-ref env x))
  19226. (check-consistent? T1 varT e)
  19227. (values (SetBang x e1^) 'Void)]
  19228. [(WhileLoop e1 e2)
  19229. (define-values (e1^ T1) (recur e1))
  19230. (check-consistent? T1 'Boolean e)
  19231. (define-values (e2^ T2) ((type-check-exp env) e2))
  19232. (values (WhileLoop e1^ e2^) 'Void)]
  19233. [(Prim 'vector-length (list e1))
  19234. (define-values (e1^ t) (recur e1))
  19235. (match t
  19236. [`(Vector ,ts ...)
  19237. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19238. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19239. \end{lstlisting}
  19240. \end{tcolorbox}
  19241. \caption{Type checker for the \LangGrad{} language, part 1.}
  19242. \label{fig:type-check-Lgradual-1}
  19243. \end{figure}
  19244. \begin{figure}[tbp]
  19245. \begin{tcolorbox}[colback=white]
  19246. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19247. [(Prim 'vector-ref (list e1 e2))
  19248. (define-values (e1^ t1) (recur e1))
  19249. (define-values (e2^ t2) (recur e2))
  19250. (check-consistent? t2 'Integer e)
  19251. (match t1
  19252. [`(Vector ,ts ...)
  19253. (match e2^
  19254. [(Int i)
  19255. (unless (and (0 . <= . i) (i . < . (length ts)))
  19256. (error 'type-check "invalid index ~a in ~a" i e))
  19257. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19258. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19259. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19260. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19261. [(Prim 'vector-set! (list e1 e2 e3) )
  19262. (define-values (e1^ t1) (recur e1))
  19263. (define-values (e2^ t2) (recur e2))
  19264. (define-values (e3^ t3) (recur e3))
  19265. (check-consistent? t2 'Integer e)
  19266. (match t1
  19267. [`(Vector ,ts ...)
  19268. (match e2^
  19269. [(Int i)
  19270. (unless (and (0 . <= . i) (i . < . (length ts)))
  19271. (error 'type-check "invalid index ~a in ~a" i e))
  19272. (check-consistent? (list-ref ts i) t3 e)
  19273. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19274. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19275. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19276. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19277. [(Apply e1 e2s)
  19278. (define-values (e1^ T1) (recur e1))
  19279. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19280. (match T1
  19281. [`(,T1ps ... -> ,T1rt)
  19282. (for ([T2 T2s] [Tp T1ps])
  19283. (check-consistent? T2 Tp e))
  19284. (values (Apply e1^ e2s^) T1rt)]
  19285. [`Any (values (Apply e1^ e2s^) 'Any)]
  19286. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19287. [(Lambda params Tr e1)
  19288. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19289. (match p
  19290. [`[,x : ,T] (values x T)]
  19291. [(? symbol? x) (values x 'Any)])))
  19292. (define-values (e1^ T1)
  19293. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19294. (check-consistent? Tr T1 e)
  19295. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19296. `(,@Ts -> ,Tr))]
  19297. [else ((super type-check-exp env) e)]
  19298. )))
  19299. \end{lstlisting}
  19300. \end{tcolorbox}
  19301. \caption{Type checker for the \LangGrad{} language, part 2.}
  19302. \label{fig:type-check-Lgradual-2}
  19303. \end{figure}
  19304. \begin{figure}[tbp]
  19305. \begin{tcolorbox}[colback=white]
  19306. \begin{lstlisting}
  19307. (define/override (type-check-def env)
  19308. (lambda (e)
  19309. (match e
  19310. [(Def f params rt info body)
  19311. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19312. (match p
  19313. [`[,x : ,T] (values x T)]
  19314. [(? symbol? x) (values x 'Any)])))
  19315. (define new-env (append (map cons xs ps) env))
  19316. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19317. (check-consistent? ty^ rt e)
  19318. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19319. [else (error 'type-check "ill-formed function definition ~a" e)]
  19320. )))
  19321. (define/override (type-check-program e)
  19322. (match e
  19323. [(Program info body)
  19324. (define-values (body^ ty) ((type-check-exp '()) body))
  19325. (check-consistent? ty 'Integer e)
  19326. (ProgramDefsExp info '() body^)]
  19327. [(ProgramDefsExp info ds body)
  19328. (define new-env (for/list ([d ds])
  19329. (cons (Def-name d) (fun-def-type d))))
  19330. (define ds^ (for/list ([d ds])
  19331. ((type-check-def new-env) d)))
  19332. (define-values (body^ ty) ((type-check-exp new-env) body))
  19333. (check-consistent? ty 'Integer e)
  19334. (ProgramDefsExp info ds^ body^)]
  19335. [else (super type-check-program e)]))
  19336. \end{lstlisting}
  19337. \end{tcolorbox}
  19338. \caption{Type checker for the \LangGrad{} language, part 3.}
  19339. \label{fig:type-check-Lgradual-3}
  19340. \end{figure}
  19341. \begin{figure}[tbp]
  19342. \begin{tcolorbox}[colback=white]
  19343. \begin{lstlisting}
  19344. (define/public (join t1 t2)
  19345. (match* (t1 t2)
  19346. [('Integer 'Integer) 'Integer]
  19347. [('Boolean 'Boolean) 'Boolean]
  19348. [('Void 'Void) 'Void]
  19349. [('Any t2) t2]
  19350. [(t1 'Any) t1]
  19351. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19352. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19353. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19354. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19355. -> ,(join rt1 rt2))]))
  19356. (define/public (meet t1 t2)
  19357. (match* (t1 t2)
  19358. [('Integer 'Integer) 'Integer]
  19359. [('Boolean 'Boolean) 'Boolean]
  19360. [('Void 'Void) 'Void]
  19361. [('Any t2) 'Any]
  19362. [(t1 'Any) 'Any]
  19363. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19364. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19365. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19366. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19367. -> ,(meet rt1 rt2))]))
  19368. (define/public (check-consistent? t1 t2 e)
  19369. (unless (consistent? t1 t2)
  19370. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19371. (define explicit-prim-ops
  19372. (set-union
  19373. (type-predicates)
  19374. (set 'procedure-arity 'eq? 'not 'and 'or
  19375. 'vector 'vector-length 'vector-ref 'vector-set!
  19376. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19377. (define/override (fun-def-type d)
  19378. (match d
  19379. [(Def f params rt info body)
  19380. (define ps
  19381. (for/list ([p params])
  19382. (match p
  19383. [`[,x : ,T] T]
  19384. [(? symbol?) 'Any]
  19385. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19386. `(,@ps -> ,rt)]
  19387. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19388. \end{lstlisting}
  19389. \end{tcolorbox}
  19390. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19391. \label{fig:type-check-Lgradual-aux}
  19392. \end{figure}
  19393. \fi}
  19394. \section{Interpreting \LangCast{} }
  19395. \label{sec:interp-casts}
  19396. The runtime behavior of casts involving simple types such as
  19397. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19398. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19399. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19400. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19401. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19402. operator, by checking the value's tag and either retrieving
  19403. the underlying integer or signaling an error if the tag is not the
  19404. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19405. %
  19406. Things get more interesting with casts involving
  19407. \racket{function and tuple types}\python{function, tuple, and array types}.
  19408. Consider the cast of the function \code{maybe\_inc} from
  19409. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19410. to
  19411. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19412. shown in figure~\ref{fig:map-maybe_inc}.
  19413. When the \code{maybe\_inc} function flows through
  19414. this cast at runtime, we don't know whether it will return
  19415. an integer, because that depends on the input from the user.
  19416. The \LangCast{} interpreter therefore delays the checking
  19417. of the cast until the function is applied. To do so it
  19418. wraps \code{maybe\_inc} in a new function that casts its parameter
  19419. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19420. casts the return value from \CANYTY{} to \INTTY{}.
  19421. {\if\edition\pythonEd\pythonColor
  19422. %
  19423. There are further complications regarding casts on mutable data,
  19424. such as the \code{list} type introduced in
  19425. the challenge assignment of section~\ref{sec:arrays}.
  19426. %
  19427. \fi}
  19428. %
  19429. Consider the example presented in figure~\ref{fig:map-bang} that
  19430. defines a partially typed version of \code{map} whose parameter
  19431. \code{v} has type
  19432. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19433. and that updates \code{v} in place
  19434. instead of returning a new tuple. We name this function
  19435. \code{map\_inplace}. We apply \code{map\_inplace} to
  19436. \racket{a tuple}\python{an array} of integers, so the type checker
  19437. inserts a cast from
  19438. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19439. to
  19440. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19441. A naive way for the \LangCast{} interpreter to cast between
  19442. \racket{tuple}\python{array} types would be to build a new
  19443. \racket{tuple}\python{array} whose elements are the result
  19444. of casting each of the original elements to the target
  19445. type. However, this approach is not valid for mutable data structures.
  19446. In the example of figure~\ref{fig:map-bang},
  19447. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19448. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19449. the original one.
  19450. Instead the interpreter needs to create a new kind of value, a
  19451. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19452. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19453. and then applies a
  19454. cast to the resulting value. On a write, the proxy casts the argument
  19455. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19456. \racket{
  19457. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19458. \code{0} from \INTTY{} to \CANYTY{}.
  19459. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19460. from \CANYTY{} to \INTTY{}.
  19461. }
  19462. \python{
  19463. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19464. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19465. For the subscript on the left of the assignment,
  19466. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19467. }
  19468. Finally we consider casts between the \CANYTY{} type and higher-order types
  19469. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19470. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19471. have a type annotation, so it is given type \CANYTY{}. In the call to
  19472. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19473. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19474. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19475. \code{Inject}, but that doesn't work because
  19476. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19477. a flat type. Instead, we must first cast to
  19478. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19479. and then inject to \CANYTY{}.
  19480. \begin{figure}[tbp]
  19481. \begin{tcolorbox}[colback=white]
  19482. % gradual_test_11.rkt
  19483. {\if\edition\racketEd
  19484. \begin{lstlisting}
  19485. (define (map_inplace [f : (Any -> Any)]
  19486. [v : (Vector Any Any)]) : Void
  19487. (begin
  19488. (vector-set! v 0 (f (vector-ref v 0)))
  19489. (vector-set! v 1 (f (vector-ref v 1)))))
  19490. (define (inc x) (+ x 1))
  19491. (let ([v (vector 0 41)])
  19492. (begin (map_inplace inc v) (vector-ref v 1)))
  19493. \end{lstlisting}
  19494. \fi}
  19495. {\if\edition\pythonEd\pythonColor
  19496. \begin{lstlisting}
  19497. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19498. i = 0
  19499. while i != len(v):
  19500. v[i] = f(v[i])
  19501. i = i + 1
  19502. def inc(x : int) -> int:
  19503. return x + 1
  19504. v = [0, 41]
  19505. map_inplace(inc, v)
  19506. print(v[1])
  19507. \end{lstlisting}
  19508. \fi}
  19509. \end{tcolorbox}
  19510. \caption{An example involving casts on arrays.}
  19511. \label{fig:map-bang}
  19512. \end{figure}
  19513. \begin{figure}[btp]
  19514. \begin{tcolorbox}[colback=white]
  19515. {\if\edition\racketEd
  19516. \begin{lstlisting}
  19517. (define (map_inplace [f : (Any -> Any)] v) : Void
  19518. (begin
  19519. (vector-set! v 0 (f (vector-ref v 0)))
  19520. (vector-set! v 1 (f (vector-ref v 1)))))
  19521. (define (inc x) (+ x 1))
  19522. (let ([v (vector 0 41)])
  19523. (begin (map_inplace inc v) (vector-ref v 1)))
  19524. \end{lstlisting}
  19525. \fi}
  19526. {\if\edition\pythonEd\pythonColor
  19527. \begin{lstlisting}
  19528. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19529. i = 0
  19530. while i != len(v):
  19531. v[i] = f(v[i])
  19532. i = i + 1
  19533. def inc(x):
  19534. return x + 1
  19535. v = [0, 41]
  19536. map_inplace(inc, v)
  19537. print(v[1])
  19538. \end{lstlisting}
  19539. \fi}
  19540. \end{tcolorbox}
  19541. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19542. \label{fig:map-any}
  19543. \end{figure}
  19544. \begin{figure}[tbp]
  19545. \begin{tcolorbox}[colback=white]
  19546. {\if\edition\racketEd
  19547. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19548. (define/public (apply_cast v s t)
  19549. (match* (s t)
  19550. [(t1 t2) #:when (equal? t1 t2) v]
  19551. [('Any t2)
  19552. (match t2
  19553. [`(,ts ... -> ,rt)
  19554. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19555. (define v^ (apply-project v any->any))
  19556. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19557. [`(Vector ,ts ...)
  19558. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19559. (define v^ (apply-project v vec-any))
  19560. (apply_cast v^ vec-any `(Vector ,@ts))]
  19561. [else (apply-project v t2)])]
  19562. [(t1 'Any)
  19563. (match t1
  19564. [`(,ts ... -> ,rt)
  19565. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19566. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19567. (apply-inject v^ (any-tag any->any))]
  19568. [`(Vector ,ts ...)
  19569. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19570. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19571. (apply-inject v^ (any-tag vec-any))]
  19572. [else (apply-inject v (any-tag t1))])]
  19573. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19574. (define x (gensym 'x))
  19575. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19576. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19577. (define cast-writes
  19578. (for/list ([t1 ts1] [t2 ts2])
  19579. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19580. `(vector-proxy ,(vector v (apply vector cast-reads)
  19581. (apply vector cast-writes)))]
  19582. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19583. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19584. `(function ,xs ,(Cast
  19585. (Apply (Value v)
  19586. (for/list ([x xs][t1 ts1][t2 ts2])
  19587. (Cast (Var x) t2 t1)))
  19588. rt1 rt2) ())]
  19589. ))
  19590. \end{lstlisting}
  19591. \fi}
  19592. {\if\edition\pythonEd\pythonColor
  19593. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19594. def apply_cast(self, value, src, tgt):
  19595. match (src, tgt):
  19596. case (AnyType(), FunctionType(ps2, rt2)):
  19597. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19598. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19599. case (AnyType(), TupleType(ts2)):
  19600. anytup = TupleType([AnyType() for t1 in ts2])
  19601. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19602. case (AnyType(), ListType(t2)):
  19603. anylist = ListType([AnyType() for t1 in ts2])
  19604. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19605. case (AnyType(), AnyType()):
  19606. return value
  19607. case (AnyType(), _):
  19608. return self.apply_project(value, tgt)
  19609. case (FunctionType(ps1,rt1), AnyType()):
  19610. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19611. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19612. case (TupleType(ts1), AnyType()):
  19613. anytup = TupleType([AnyType() for t1 in ts1])
  19614. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19615. case (ListType(t1), AnyType()):
  19616. anylist = ListType(AnyType())
  19617. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19618. case (_, AnyType()):
  19619. return self.apply_inject(value, src)
  19620. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19621. params = [generate_name('x') for p in ps2]
  19622. args = [Cast(Name(x), t2, t1)
  19623. for (x,t1,t2) in zip(params, ps1, ps2)]
  19624. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19625. return Function('cast', params, [Return(body)], {})
  19626. case (TupleType(ts1), TupleType(ts2)):
  19627. x = generate_name('x')
  19628. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19629. for (t1,t2) in zip(ts1,ts2)]
  19630. return ProxiedTuple(value, reads)
  19631. case (ListType(t1), ListType(t2)):
  19632. x = generate_name('x')
  19633. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19634. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19635. return ProxiedList(value, read, write)
  19636. case (t1, t2) if t1 == t2:
  19637. return value
  19638. case (t1, t2):
  19639. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19640. def apply_inject(self, value, src):
  19641. return Tagged(value, self.type_to_tag(src))
  19642. def apply_project(self, value, tgt):
  19643. match value:
  19644. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19645. return val
  19646. case _:
  19647. raise Exception('apply_project, unexpected ' + repr(value))
  19648. \end{lstlisting}
  19649. \fi}
  19650. \end{tcolorbox}
  19651. \caption{The \code{apply\_cast} auxiliary method.}
  19652. \label{fig:apply_cast}
  19653. \end{figure}
  19654. The \LangCast{} interpreter uses an auxiliary function named
  19655. \code{apply\_cast} to cast a value from a source type to a target type,
  19656. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19657. the kinds of casts that we've discussed in this section.
  19658. %
  19659. The definition of the interpreter for \LangCast{} is shown in
  19660. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19661. dispatching to \code{apply\_cast}.
  19662. \racket{To handle the addition of tuple
  19663. proxies, we update the tuple primitives in \code{interp-op} using the
  19664. functions given in figure~\ref{fig:guarded-tuple}.}
  19665. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19666. \begin{figure}[tbp]
  19667. \begin{tcolorbox}[colback=white]
  19668. {\if\edition\racketEd
  19669. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19670. (define interp-Lcast-class
  19671. (class interp-Llambda-class
  19672. (super-new)
  19673. (inherit apply-fun apply-inject apply-project)
  19674. (define/override (interp-op op)
  19675. (match op
  19676. ['vector-length guarded-vector-length]
  19677. ['vector-ref guarded-vector-ref]
  19678. ['vector-set! guarded-vector-set!]
  19679. ['any-vector-ref (lambda (v i)
  19680. (match v [`(tagged ,v^ ,tg)
  19681. (guarded-vector-ref v^ i)]))]
  19682. ['any-vector-set! (lambda (v i a)
  19683. (match v [`(tagged ,v^ ,tg)
  19684. (guarded-vector-set! v^ i a)]))]
  19685. ['any-vector-length (lambda (v)
  19686. (match v [`(tagged ,v^ ,tg)
  19687. (guarded-vector-length v^)]))]
  19688. [else (super interp-op op)]
  19689. ))
  19690. (define/override ((interp-exp env) e)
  19691. (define (recur e) ((interp-exp env) e))
  19692. (match e
  19693. [(Value v) v]
  19694. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19695. [else ((super interp-exp env) e)]))
  19696. ))
  19697. (define (interp-Lcast p)
  19698. (send (new interp-Lcast-class) interp-program p))
  19699. \end{lstlisting}
  19700. \fi}
  19701. {\if\edition\pythonEd\pythonColor
  19702. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19703. class InterpLcast(InterpLany):
  19704. def interp_exp(self, e, env):
  19705. match e:
  19706. case Cast(value, src, tgt):
  19707. v = self.interp_exp(value, env)
  19708. return self.apply_cast(v, src, tgt)
  19709. case ValueExp(value):
  19710. return value
  19711. ...
  19712. case _:
  19713. return super().interp_exp(e, env)
  19714. \end{lstlisting}
  19715. \fi}
  19716. \end{tcolorbox}
  19717. \caption{The interpreter for \LangCast{}.}
  19718. \label{fig:interp-Lcast}
  19719. \end{figure}
  19720. {\if\edition\racketEd
  19721. \begin{figure}[tbp]
  19722. \begin{tcolorbox}[colback=white]
  19723. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19724. (define (guarded-vector-ref vec i)
  19725. (match vec
  19726. [`(vector-proxy ,proxy)
  19727. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19728. (define rd (vector-ref (vector-ref proxy 1) i))
  19729. (apply-fun rd (list val) 'guarded-vector-ref)]
  19730. [else (vector-ref vec i)]))
  19731. (define (guarded-vector-set! vec i arg)
  19732. (match vec
  19733. [`(vector-proxy ,proxy)
  19734. (define wr (vector-ref (vector-ref proxy 2) i))
  19735. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19736. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19737. [else (vector-set! vec i arg)]))
  19738. (define (guarded-vector-length vec)
  19739. (match vec
  19740. [`(vector-proxy ,proxy)
  19741. (guarded-vector-length (vector-ref proxy 0))]
  19742. [else (vector-length vec)]))
  19743. \end{lstlisting}
  19744. %% {\if\edition\pythonEd\pythonColor
  19745. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19746. %% UNDER CONSTRUCTION
  19747. %% \end{lstlisting}
  19748. %% \fi}
  19749. \end{tcolorbox}
  19750. \caption{The \code{guarded-vector} auxiliary functions.}
  19751. \label{fig:guarded-tuple}
  19752. \end{figure}
  19753. \fi}
  19754. {\if\edition\pythonEd\pythonColor
  19755. \section{Overload Resolution }
  19756. \label{sec:gradual-resolution}
  19757. Recall that when we added support for arrays in
  19758. section~\ref{sec:arrays}, the syntax for the array operations were the
  19759. same as for tuple operations (for example, accessing an element and
  19760. getting the length). So we performed overload resolution, with a pass
  19761. named \code{resolve}, to separate the array and tuple operations. In
  19762. particular, we introduced the primitives \code{array\_load},
  19763. \code{array\_store}, and \code{array\_len}.
  19764. For gradual typing, we further overload these operators to work on
  19765. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19766. updated with new cases for the \CANYTY{} type, translating the element
  19767. access and length operations to the primitives \code{any\_load},
  19768. \code{any\_store}, and \code{any\_len}.
  19769. \fi}
  19770. \section{Cast Insertion }
  19771. \label{sec:gradual-insert-casts}
  19772. In our discussion of type checking of \LangGrad{}, we mentioned how
  19773. the runtime aspect of type checking is carried out by the \code{Cast}
  19774. AST node, which is added to the program by a new pass named
  19775. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19776. language. We now discuss the details of this pass.
  19777. The \code{cast\_insert} pass is closely related to the type checker
  19778. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19779. In particular, the type checker allows implicit casts between
  19780. consistent types. The job of the \code{cast\_insert} pass is to make
  19781. those casts explicit. It does so by inserting
  19782. \code{Cast} nodes into the AST.
  19783. %
  19784. For the most part, the implicit casts occur in places where the type
  19785. checker checks two types for consistency. Consider the case for
  19786. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19787. checker requires that the type of the left operand is consistent with
  19788. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19789. \code{Cast} around the left operand, converting from its type to
  19790. \INTTY{}. The story is similar for the right operand. It is not always
  19791. necessary to insert a cast, for example, if the left operand already has type
  19792. \INTTY{} then there is no need for a \code{Cast}.
  19793. Some of the implicit casts are not as straightforward. One such case
  19794. arises with the
  19795. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19796. see that the type checker requires that the two branches have
  19797. consistent types and that type of the conditional expression is the
  19798. meet of the branches' types. In the target language \LangCast{}, both
  19799. branches will need to have the same type, and that type
  19800. will be the type of the conditional expression. Thus, each branch requires
  19801. a \code{Cast} to convert from its type to the meet of the branches' types.
  19802. The case for the function call exhibits another interesting situation. If
  19803. the function expression is of type \CANYTY{}, then it needs to be cast
  19804. to a function type so that it can be used in a function call in
  19805. \LangCast{}. Which function type should it be cast to? The parameter
  19806. and return types are unknown, so we can simply use \CANYTY{} for all
  19807. of them. Furthermore, in \LangCast{} the argument types will need to
  19808. exactly match the parameter types, so we must cast all the arguments
  19809. to type \CANYTY{} (if they are not already of that type).
  19810. {\if\edition\racketEd
  19811. %
  19812. Likewise, the cases for the tuple operators \code{vector-length},
  19813. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19814. where the tuple expression is of type \CANYTY{}. Instead of
  19815. handling these situations with casts, we recommend translating
  19816. the special-purpose variants of the tuple operators that handle
  19817. tuples of type \CANYTY{}: \code{any-vector-length},
  19818. \code{any-vector-ref}, and \code{any-vector-set!}.
  19819. %
  19820. \fi}
  19821. \section{Lower Casts }
  19822. \label{sec:lower_casts}
  19823. The next step in the journey toward x86 is the \code{lower\_casts}
  19824. pass that translates the casts in \LangCast{} to the lower-level
  19825. \code{Inject} and \code{Project} operators and new operators for
  19826. proxies, extending the \LangLam{} language to \LangProxy{}.
  19827. The \LangProxy{} language can also be described as an extension of
  19828. \LangAny{}, with the addition of proxies. We recommend creating an
  19829. auxiliary function named \code{lower\_cast} that takes an expression
  19830. (in \LangCast{}), a source type, and a target type and translates it
  19831. to an expression in \LangProxy{}.
  19832. The \code{lower\_cast} function can follow a code structure similar to
  19833. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19834. the interpreter for \LangCast{}, because it must handle the same cases
  19835. as \code{apply\_cast} and it needs to mimic the behavior of
  19836. \code{apply\_cast}. The most interesting cases concern
  19837. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19838. {\if\edition\racketEd
  19839. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19840. type to another tuple type is accomplished by creating a proxy that
  19841. intercepts the operations on the underlying tuple. Here we make the
  19842. creation of the proxy explicit with the \code{vector-proxy} AST
  19843. node. It takes three arguments: the first is an expression for the
  19844. tuple, the second is a tuple of functions for casting an element that is
  19845. being read from the tuple, and the third is a tuple of functions for
  19846. casting an element that is being written to the array. You can create
  19847. the functions for reading and writing using lambda expressions. Also,
  19848. as we show in the next section, we need to differentiate these tuples
  19849. of functions from the user-created ones, so we recommend using a new
  19850. AST node named \code{raw-vector} instead of \code{vector}.
  19851. %
  19852. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19853. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19854. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19855. \fi}
  19856. {\if\edition\pythonEd\pythonColor
  19857. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19858. type to another array type is accomplished by creating a proxy that
  19859. intercepts the operations on the underlying array. Here we make the
  19860. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19861. takes fives arguments: the first is an expression for the array, the
  19862. second is a function for casting an element that is being read from
  19863. the array, the third is a function for casting an element that is
  19864. being written to the array, the fourth is the type of the underlying
  19865. array, and the fifth is the type of the proxied array. You can create
  19866. the functions for reading and writing using lambda expressions.
  19867. A cast between two tuple types can be handled in a similar manner. We
  19868. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19869. immutable, so there is no need for a function to cast the value during
  19870. a write. Because there is a separate element type for each slot in
  19871. the tuple, we need more than one function for casting during a read:
  19872. we need a tuple of functions.
  19873. %
  19874. Also, as we show in the next section, we need to differentiate these
  19875. tuples from the user-created ones, so we recommend using a new AST
  19876. node named \code{RawTuple} instead of \code{Tuple} to create the
  19877. tuples of functions.
  19878. %
  19879. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19880. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19881. that involves casting an array of integers to an array of \CANYTY{}.
  19882. \fi}
  19883. \begin{figure}[tbp]
  19884. \begin{tcolorbox}[colback=white]
  19885. {\if\edition\racketEd
  19886. \begin{lstlisting}
  19887. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19888. (begin
  19889. (vector-set! v 0 (f (vector-ref v 0)))
  19890. (vector-set! v 1 (f (vector-ref v 1)))))
  19891. (define (inc [x : Any]) : Any
  19892. (inject (+ (project x Integer) 1) Integer))
  19893. (let ([v (vector 0 41)])
  19894. (begin
  19895. (map_inplace inc (vector-proxy v
  19896. (raw-vector (lambda: ([x9 : Integer]) : Any
  19897. (inject x9 Integer))
  19898. (lambda: ([x9 : Integer]) : Any
  19899. (inject x9 Integer)))
  19900. (raw-vector (lambda: ([x9 : Any]) : Integer
  19901. (project x9 Integer))
  19902. (lambda: ([x9 : Any]) : Integer
  19903. (project x9 Integer)))))
  19904. (vector-ref v 1)))
  19905. \end{lstlisting}
  19906. \fi}
  19907. {\if\edition\pythonEd\pythonColor
  19908. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19909. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19910. i = 0
  19911. while i != array_len(v):
  19912. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19913. i = (i + 1)
  19914. def inc(x : int) -> int:
  19915. return (x + 1)
  19916. def main() -> int:
  19917. v = [0, 41]
  19918. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19919. print(array_load(v, 1))
  19920. return 0
  19921. \end{lstlisting}
  19922. \fi}
  19923. \end{tcolorbox}
  19924. \caption{Output of \code{lower\_casts} on the example shown in
  19925. figure~\ref{fig:map-bang}.}
  19926. \label{fig:map-bang-lower-cast}
  19927. \end{figure}
  19928. A cast from one function type to another function type is accomplished
  19929. by generating a \code{lambda} whose parameter and return types match
  19930. the target function type. The body of the \code{lambda} should cast
  19931. the parameters from the target type to the source type. (Yes,
  19932. backward! Functions are contravariant\index{subject}{contravariant}
  19933. in the parameters.) Afterward, call the underlying function and then
  19934. cast the result from the source return type to the target return type.
  19935. Figure~\ref{fig:map-lower-cast} shows the output of the
  19936. \code{lower\_casts} pass on the \code{map} example given in
  19937. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19938. call to \code{map} is wrapped in a \code{lambda}.
  19939. \begin{figure}[tbp]
  19940. \begin{tcolorbox}[colback=white]
  19941. {\if\edition\racketEd
  19942. \begin{lstlisting}
  19943. (define (map [f : (Integer -> Integer)]
  19944. [v : (Vector Integer Integer)])
  19945. : (Vector Integer Integer)
  19946. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19947. (define (inc [x : Any]) : Any
  19948. (inject (+ (project x Integer) 1) Integer))
  19949. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19950. (project (inc (inject x9 Integer)) Integer))
  19951. (vector 0 41)) 1)
  19952. \end{lstlisting}
  19953. \fi}
  19954. {\if\edition\pythonEd\pythonColor
  19955. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19956. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19957. return (f(v[0]), f(v[1]),)
  19958. def inc(x : any) -> any:
  19959. return inject((project(x, int) + 1), int)
  19960. def main() -> int:
  19961. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19962. print(t[1])
  19963. return 0
  19964. \end{lstlisting}
  19965. \fi}
  19966. \end{tcolorbox}
  19967. \caption{Output of \code{lower\_casts} on the example shown in
  19968. figure~\ref{fig:gradual-map}.}
  19969. \label{fig:map-lower-cast}
  19970. \end{figure}
  19971. %\pagebreak
  19972. \section{Differentiate Proxies }
  19973. \label{sec:differentiate-proxies}
  19974. So far, the responsibility of differentiating tuples and tuple proxies
  19975. has been the job of the interpreter.
  19976. %
  19977. \racket{For example, the interpreter for \LangCast{} implements
  19978. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19979. figure~\ref{fig:guarded-tuple}.}
  19980. %
  19981. In the \code{differentiate\_proxies} pass we shift this responsibility
  19982. to the generated code.
  19983. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19984. we used the type \TUPLETYPENAME{} for both
  19985. real tuples and tuple proxies.
  19986. \python{Similarly, we use the type \code{list} for both arrays and
  19987. array proxies.}
  19988. In \LangPVec{} we return the
  19989. \TUPLETYPENAME{} type to its original
  19990. meaning, as the type of just tuples, and we introduce a new type,
  19991. \PTUPLETYNAME{}, whose values
  19992. can be either real tuples or tuple
  19993. proxies.
  19994. %
  19995. {\if\edition\pythonEd\pythonColor
  19996. Likewise, we return the
  19997. \ARRAYTYPENAME{} type to its original
  19998. meaning, as the type of arrays, and we introduce a new type,
  19999. \PARRAYTYNAME{}, whose values
  20000. can be either arrays or array proxies.
  20001. These new types come with a suite of new primitive operations.
  20002. \fi}
  20003. {\if\edition\racketEd
  20004. A tuple proxy is represented by a tuple containing three things: (1) the
  20005. underlying tuple, (2) a tuple of functions for casting elements that
  20006. are read from the tuple, and (3) a tuple of functions for casting
  20007. values to be written to the tuple. So, we define the following
  20008. abbreviation for the type of a tuple proxy:
  20009. \[
  20010. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20011. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20012. \]
  20013. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20014. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20015. %
  20016. Next we describe each of the new primitive operations.
  20017. \begin{description}
  20018. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20019. (\key{PVector} $T \ldots$)]\ \\
  20020. %
  20021. This operation brands a vector as a value of the \code{PVector} type.
  20022. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20023. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20024. %
  20025. This operation brands a vector proxy as value of the \code{PVector} type.
  20026. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20027. \BOOLTY{}] \ \\
  20028. %
  20029. This returns true if the value is a tuple proxy and false if it is a
  20030. real tuple.
  20031. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20032. (\key{Vector} $T \ldots$)]\ \\
  20033. %
  20034. Assuming that the input is a tuple, this operation returns the
  20035. tuple.
  20036. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20037. $\to$ \INTTY{}]\ \\
  20038. %
  20039. Given a tuple proxy, this operation returns the length of the tuple.
  20040. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20041. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20042. %
  20043. Given a tuple proxy, this operation returns the $i$th element of the
  20044. tuple.
  20045. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20046. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20047. Given a tuple proxy, this operation writes a value to the $i$th element
  20048. of the tuple.
  20049. \end{description}
  20050. \fi}
  20051. {\if\edition\pythonEd\pythonColor
  20052. %
  20053. A tuple proxy is represented by a tuple containing (1) the underlying
  20054. tuple and (2) a tuple of functions for casting elements that are read
  20055. from the tuple. The \LangPVec{} language includes the following AST
  20056. classes and primitive functions.
  20057. \begin{description}
  20058. \item[\code{InjectTuple}] \ \\
  20059. %
  20060. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20061. \item[\code{InjectTupleProxy}]\ \\
  20062. %
  20063. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20064. \item[\code{is\_tuple\_proxy}]\ \\
  20065. %
  20066. This primitive returns true if the value is a tuple proxy and false
  20067. if it is a tuple.
  20068. \item[\code{project\_tuple}]\ \\
  20069. %
  20070. Converts a tuple that is branded as \PTUPLETYNAME{}
  20071. back to a tuple.
  20072. \item[\code{proxy\_tuple\_len}]\ \\
  20073. %
  20074. Given a tuple proxy, returns the length of the underlying tuple.
  20075. \item[\code{proxy\_tuple\_load}]\ \\
  20076. %
  20077. Given a tuple proxy, returns the $i$th element of the underlying
  20078. tuple.
  20079. \end{description}
  20080. An array proxy is represented by a tuple containing (1) the underlying
  20081. array, (2) a function for casting elements that are read from the
  20082. array, and (3) a function for casting elements that are written to the
  20083. array. The \LangPVec{} language includes the following AST classes
  20084. and primitive functions.
  20085. \begin{description}
  20086. \item[\code{InjectList}]\ \\
  20087. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20088. \item[\code{InjectListProxy}]\ \\
  20089. %
  20090. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20091. \item[\code{is\_array\_proxy}]\ \\
  20092. %
  20093. Returns true if the value is an array proxy and false if it is an
  20094. array.
  20095. \item[\code{project\_array}]\ \\
  20096. %
  20097. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20098. array.
  20099. \item[\code{proxy\_array\_len}]\ \\
  20100. %
  20101. Given an array proxy, returns the length of the underlying array.
  20102. \item[\code{proxy\_array\_load}]\ \\
  20103. %
  20104. Given an array proxy, returns the $i$th element of the underlying
  20105. array.
  20106. \item[\code{proxy\_array\_store}]\ \\
  20107. %
  20108. Given an array proxy, writes a value to the $i$th element of the
  20109. underlying array.
  20110. \end{description}
  20111. \fi}
  20112. Now we discuss the translation that differentiates tuples and arrays
  20113. from proxies. First, every type annotation in the program is
  20114. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20115. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20116. places. For example, we wrap every tuple creation with an
  20117. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20118. %
  20119. {\if\edition\racketEd
  20120. \begin{minipage}{0.96\textwidth}
  20121. \begin{lstlisting}
  20122. (vector |$e_1 \ldots e_n$|)
  20123. |$\Rightarrow$|
  20124. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20125. \end{lstlisting}
  20126. \end{minipage}
  20127. \fi}
  20128. {\if\edition\pythonEd\pythonColor
  20129. \begin{lstlisting}
  20130. Tuple(|$e_1, \ldots, e_n$|)
  20131. |$\Rightarrow$|
  20132. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20133. \end{lstlisting}
  20134. \fi}
  20135. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20136. AST node that we introduced in the previous
  20137. section does not get injected.
  20138. {\if\edition\racketEd
  20139. \begin{lstlisting}
  20140. (raw-vector |$e_1 \ldots e_n$|)
  20141. |$\Rightarrow$|
  20142. (vector |$e'_1 \ldots e'_n$|)
  20143. \end{lstlisting}
  20144. \fi}
  20145. {\if\edition\pythonEd\pythonColor
  20146. \begin{lstlisting}
  20147. RawTuple(|$e_1, \ldots, e_n$|)
  20148. |$\Rightarrow$|
  20149. Tuple(|$e'_1, \ldots, e'_n$|)
  20150. \end{lstlisting}
  20151. \fi}
  20152. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20153. translates as follows:
  20154. %
  20155. {\if\edition\racketEd
  20156. \begin{lstlisting}
  20157. (vector-proxy |$e_1~e_2~e_3$|)
  20158. |$\Rightarrow$|
  20159. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20160. \end{lstlisting}
  20161. \fi}
  20162. {\if\edition\pythonEd\pythonColor
  20163. \begin{lstlisting}
  20164. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20165. |$\Rightarrow$|
  20166. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20167. \end{lstlisting}
  20168. \fi}
  20169. We translate the element access operations into conditional
  20170. expressions that check whether the value is a proxy and then dispatch
  20171. to either the appropriate proxy tuple operation or the regular tuple
  20172. operation.
  20173. {\if\edition\racketEd
  20174. \begin{lstlisting}
  20175. (vector-ref |$e_1$| |$i$|)
  20176. |$\Rightarrow$|
  20177. (let ([|$v~e_1$|])
  20178. (if (proxy? |$v$|)
  20179. (proxy-vector-ref |$v$| |$i$|)
  20180. (vector-ref (project-vector |$v$|) |$i$|)
  20181. \end{lstlisting}
  20182. \fi}
  20183. %
  20184. Note that in the branch for a tuple, we must apply
  20185. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20186. from the tuple.
  20187. The translation of array operations is similar to the ones for tuples.
  20188. \section{Reveal Casts }
  20189. \label{sec:reveal-casts-gradual}
  20190. {\if\edition\racketEd
  20191. Recall that the \code{reveal\_casts} pass
  20192. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20193. \code{Inject} and \code{Project} into lower-level operations.
  20194. %
  20195. In particular, \code{Project} turns into a conditional expression that
  20196. inspects the tag and retrieves the underlying value. Here we need to
  20197. augment the translation of \code{Project} to handle the situation in which
  20198. the target type is \code{PVector}. Instead of using
  20199. \code{vector-length} we need to use \code{proxy-vector-length}.
  20200. \begin{lstlisting}
  20201. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20202. |$\Rightarrow$|
  20203. (let |$\itm{tmp}$| |$e'$|
  20204. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20205. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20206. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20207. (exit)))
  20208. \end{lstlisting}
  20209. \fi}
  20210. %
  20211. {\if\edition\pythonEd\pythonColor
  20212. Recall that the $\itm{tagof}$ function determines the bits used to
  20213. identify values of different types, and it is used in the \code{reveal\_casts}
  20214. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20215. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20216. decimal), just like the tuple and array types.
  20217. \fi}
  20218. %
  20219. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20220. \pagebreak
  20221. \section{Closure Conversion }
  20222. \label{sec:closure-conversion-gradual}
  20223. The auxiliary function that translates type annotations needs to be
  20224. updated to handle the \PTUPLETYNAME{}
  20225. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20226. %
  20227. Otherwise, the only other changes are adding cases that copy the new
  20228. AST nodes.
  20229. \section{Select Instructions }
  20230. \label{sec:select-instructions-gradual}
  20231. \index{subject}{select instructions}
  20232. Recall that the \code{select\_instructions} pass is responsible for
  20233. lowering the primitive operations into x86 instructions. So, we need
  20234. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20235. to x86. To do so, the first question we need to answer is how to
  20236. differentiate between tuple and tuple proxies\python{, and likewise for
  20237. arrays and array proxies}. We need just one bit to accomplish this;
  20238. we use the bit in position $63$ of the 64-bit tag at the front of
  20239. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20240. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20241. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20242. it that way.
  20243. {\if\edition\racketEd
  20244. \begin{lstlisting}
  20245. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20246. |$\Rightarrow$|
  20247. movq |$e'_1$|, |$\itm{lhs'}$|
  20248. \end{lstlisting}
  20249. \fi}
  20250. {\if\edition\pythonEd\pythonColor
  20251. \begin{lstlisting}
  20252. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20253. |$\Rightarrow$|
  20254. movq |$e'_1$|, |$\itm{lhs'}$|
  20255. \end{lstlisting}
  20256. \fi}
  20257. \python{The translation for \code{InjectList} is also a move instruction.}
  20258. \noindent On the other hand,
  20259. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20260. $63$ to $1$.
  20261. %
  20262. {\if\edition\racketEd
  20263. \begin{lstlisting}
  20264. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20265. |$\Rightarrow$|
  20266. movq |$e'_1$|, %r11
  20267. movq |$(1 << 63)$|, %rax
  20268. orq 0(%r11), %rax
  20269. movq %rax, 0(%r11)
  20270. movq %r11, |$\itm{lhs'}$|
  20271. \end{lstlisting}
  20272. \fi}
  20273. {\if\edition\pythonEd\pythonColor
  20274. \begin{lstlisting}
  20275. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20276. |$\Rightarrow$|
  20277. movq |$e'_1$|, %r11
  20278. movq |$(1 << 63)$|, %rax
  20279. orq 0(%r11), %rax
  20280. movq %rax, 0(%r11)
  20281. movq %r11, |$\itm{lhs'}$|
  20282. \end{lstlisting}
  20283. \fi}
  20284. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20285. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20286. The \racket{\code{proxy?} operation consumes}%
  20287. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20288. consume}
  20289. the information so carefully stashed away by the injections. It
  20290. isolates bit $63$ to tell whether the value is a proxy.
  20291. %
  20292. {\if\edition\racketEd
  20293. \begin{lstlisting}
  20294. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20295. |$\Rightarrow$|
  20296. movq |$e_1'$|, %r11
  20297. movq 0(%r11), %rax
  20298. sarq $63, %rax
  20299. andq $1, %rax
  20300. movq %rax, |$\itm{lhs'}$|
  20301. \end{lstlisting}
  20302. \fi}%
  20303. %
  20304. {\if\edition\pythonEd\pythonColor
  20305. \begin{lstlisting}
  20306. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20307. |$\Rightarrow$|
  20308. movq |$e_1'$|, %r11
  20309. movq 0(%r11), %rax
  20310. sarq $63, %rax
  20311. andq $1, %rax
  20312. movq %rax, |$\itm{lhs'}$|
  20313. \end{lstlisting}
  20314. \fi}%
  20315. %
  20316. The \racket{\code{project-vector} operation is}
  20317. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20318. straightforward to translate, so we leave that to the reader.
  20319. Regarding the element access operations for tuples\python{ and arrays}, the
  20320. runtime provides procedures that implement them (they are recursive
  20321. functions!), so here we simply need to translate these tuple
  20322. operations into the appropriate function call. For example, here is
  20323. the translation for
  20324. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20325. {\if\edition\racketEd
  20326. \begin{minipage}{0.96\textwidth}
  20327. \begin{lstlisting}
  20328. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20329. |$\Rightarrow$|
  20330. movq |$e_1'$|, %rdi
  20331. movq |$e_2'$|, %rsi
  20332. callq proxy_vector_ref
  20333. movq %rax, |$\itm{lhs'}$|
  20334. \end{lstlisting}
  20335. \end{minipage}
  20336. \fi}
  20337. {\if\edition\pythonEd\pythonColor
  20338. \begin{lstlisting}
  20339. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20340. |$\Rightarrow$|
  20341. movq |$e_1'$|, %rdi
  20342. movq |$e_2'$|, %rsi
  20343. callq proxy_vector_ref
  20344. movq %rax, |$\itm{lhs'}$|
  20345. \end{lstlisting}
  20346. \fi}
  20347. {\if\edition\pythonEd\pythonColor
  20348. % TODO: revisit the names vecof for python -Jeremy
  20349. We translate
  20350. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20351. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20352. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20353. \fi}
  20354. We have another batch of operations to deal with: those for the
  20355. \CANYTY{} type. Recall that we generate an
  20356. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20357. there is a element access on something of type \CANYTY{}, and
  20358. similarly for
  20359. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20360. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20361. section~\ref{sec:select-Lany} we selected instructions for these
  20362. operations on the basis of the idea that the underlying value was a tuple or
  20363. array. But in the current setting, the underlying value is of type
  20364. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20365. functions to deal with this:
  20366. \code{proxy\_vector\_ref},
  20367. \code{proxy\_vector\_set}, and
  20368. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20369. to determine whether the value is a proxy, and then
  20370. dispatches to the the appropriate code.
  20371. %
  20372. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20373. can be translated as follows.
  20374. We begin by projecting the underlying value out of the tagged value and
  20375. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20376. {\if\edition\racketEd
  20377. \begin{lstlisting}
  20378. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20379. |$\Rightarrow$|
  20380. movq |$\neg 111$|, %rdi
  20381. andq |$e_1'$|, %rdi
  20382. movq |$e_2'$|, %rsi
  20383. callq proxy_vector_ref
  20384. movq %rax, |$\itm{lhs'}$|
  20385. \end{lstlisting}
  20386. \fi}
  20387. {\if\edition\pythonEd\pythonColor
  20388. \begin{lstlisting}
  20389. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20390. |$\Rightarrow$|
  20391. movq |$\neg 111$|, %rdi
  20392. andq |$e_1'$|, %rdi
  20393. movq |$e_2'$|, %rsi
  20394. callq proxy_vector_ref
  20395. movq %rax, |$\itm{lhs'}$|
  20396. \end{lstlisting}
  20397. \fi}
  20398. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20399. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20400. are translated in a similar way. Alternatively, you could generate
  20401. instructions to open-code
  20402. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20403. and \code{proxy\_vector\_length} functions.
  20404. \begin{exercise}\normalfont\normalsize
  20405. Implement a compiler for the gradually typed \LangGrad{} language by
  20406. extending and adapting your compiler for \LangLam{}. Create ten new
  20407. partially typed test programs. In addition to testing with these
  20408. new programs, test your compiler on all the tests for \LangLam{}
  20409. and for \LangDyn{}.
  20410. %
  20411. \racket{Sometimes you may get a type-checking error on the
  20412. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20413. the \CANYTY{} type around each subexpression that has caused a type
  20414. error. Although \LangDyn{} does not have explicit casts, you can
  20415. induce one by wrapping the subexpression \code{e} with a call to
  20416. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20417. %
  20418. \python{Sometimes you may get a type-checking error on the
  20419. \LangDyn{} programs, but you can adapt them by inserting a
  20420. temporary variable of type \CANYTY{} that is initialized with the
  20421. troublesome expression.}
  20422. \end{exercise}
  20423. \begin{figure}[t]
  20424. \begin{tcolorbox}[colback=white]
  20425. {\if\edition\racketEd
  20426. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20427. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20428. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20429. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20430. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20431. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20432. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20433. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20434. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20435. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20436. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20437. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20438. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20439. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20440. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20441. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20442. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20443. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20444. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20445. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20446. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20447. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20448. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20449. \path[->,bend left=15] (Lgradual) edge [above] node
  20450. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20451. \path[->,bend left=15] (Lgradual2) edge [above] node
  20452. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20453. \path[->,bend left=15] (Lgradual3) edge [above] node
  20454. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20455. \path[->,bend left=15] (Lgradual4) edge [left] node
  20456. {\ttfamily\footnotesize shrink} (Lgradualr);
  20457. \path[->,bend left=15] (Lgradualr) edge [above] node
  20458. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20459. \path[->,bend right=15] (Lgradualp) edge [above] node
  20460. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20461. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20462. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20463. \path[->,bend right=15] (Llambdapp) edge [above] node
  20464. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20465. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20466. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20467. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20468. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20469. \path[->,bend left=15] (F1-2) edge [above] node
  20470. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20471. \path[->,bend left=15] (F1-3) edge [left] node
  20472. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20473. \path[->,bend left=15] (F1-4) edge [below] node
  20474. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20475. \path[->,bend right=15] (F1-5) edge [above] node
  20476. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20477. \path[->,bend right=15] (F1-6) edge [above] node
  20478. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20479. \path[->,bend right=15] (C3-2) edge [right] node
  20480. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20481. \path[->,bend right=15] (x86-2) edge [right] node
  20482. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20483. \path[->,bend right=15] (x86-2-1) edge [below] node
  20484. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20485. \path[->,bend right=15] (x86-2-2) edge [right] node
  20486. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20487. \path[->,bend left=15] (x86-3) edge [above] node
  20488. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20489. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20490. \end{tikzpicture}
  20491. \fi}
  20492. {\if\edition\pythonEd\pythonColor
  20493. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20494. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20495. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20496. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20497. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20498. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20499. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20500. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20501. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20502. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20503. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20504. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20505. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20506. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20507. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20508. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20509. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20510. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20511. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20512. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20513. \path[->,bend left=15] (Lgradual) edge [above] node
  20514. {\ttfamily\footnotesize shrink} (Lgradual2);
  20515. \path[->,bend left=15] (Lgradual2) edge [above] node
  20516. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20517. \path[->,bend left=15] (Lgradual3) edge [above] node
  20518. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20519. \path[->,bend left=15] (Lgradual4) edge [left] node
  20520. {\ttfamily\footnotesize resolve} (Lgradualr);
  20521. \path[->,bend left=15] (Lgradualr) edge [below] node
  20522. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20523. \path[->,bend right=15] (Lgradualp) edge [above] node
  20524. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20525. \path[->,bend right=15] (Llambdapp) edge [above] node
  20526. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20527. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20528. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20529. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20530. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20531. \path[->,bend left=15] (F1-1) edge [above] node
  20532. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20533. \path[->,bend left=15] (F1-2) edge [above] node
  20534. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20535. \path[->,bend left=15] (F1-3) edge [right] node
  20536. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20537. \path[->,bend right=15] (F1-5) edge [above] node
  20538. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20539. \path[->,bend right=15] (F1-6) edge [above] node
  20540. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20541. \path[->,bend right=15] (C3-2) edge [right] node
  20542. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20543. \path[->,bend right=15] (x86-2) edge [below] node
  20544. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20545. \path[->,bend right=15] (x86-3) edge [below] node
  20546. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20547. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20548. \end{tikzpicture}
  20549. \fi}
  20550. \end{tcolorbox}
  20551. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20552. \label{fig:Lgradual-passes}
  20553. \end{figure}
  20554. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20555. needed for the compilation of \LangGrad{}.
  20556. \section{Further Reading}
  20557. This chapter just scratches the surface of gradual typing. The basic
  20558. approach described here is missing two key ingredients that one would
  20559. want in an implementation of gradual typing: blame
  20560. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20561. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20562. problem addressed by blame tracking is that when a cast on a
  20563. higher-order value fails, it often does so at a point in the program
  20564. that is far removed from the original cast. Blame tracking is a
  20565. technique for propagating extra information through casts and proxies
  20566. so that when a cast fails, the error message can point back to the
  20567. original location of the cast in the source program.
  20568. The problem addressed by space-efficient casts also relates to
  20569. higher-order casts. It turns out that in partially typed programs, a
  20570. function or tuple can flow through a great many casts at runtime. With
  20571. the approach described in this chapter, each cast adds another
  20572. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20573. considerable space, but it also makes the function calls and tuple
  20574. operations slow. For example, a partially typed version of quicksort
  20575. could, in the worst case, build a chain of proxies of length $O(n)$
  20576. around the tuple, changing the overall time complexity of the
  20577. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20578. solution to this problem by representing casts using the coercion
  20579. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20580. long chains of proxies by compressing them into a concise normal
  20581. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20582. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20583. the Grift compiler:
  20584. \begin{center}
  20585. \url{https://github.com/Gradual-Typing/Grift}
  20586. \end{center}
  20587. There are also interesting interactions between gradual typing and
  20588. other language features, such as generics, information-flow types, and
  20589. type inference, to name a few. We recommend to the reader the
  20590. online gradual typing bibliography for more material:
  20591. \begin{center}
  20592. \url{http://samth.github.io/gradual-typing-bib/}
  20593. \end{center}
  20594. % TODO: challenge problem:
  20595. % type analysis and type specialization?
  20596. % coercions?
  20597. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20598. \chapter{Generics}
  20599. \label{ch:Lpoly}
  20600. \setcounter{footnote}{0}
  20601. This chapter studies the compilation of
  20602. generics\index{subject}{generics} (aka parametric
  20603. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20604. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20605. enable programmers to make code more reusable by parameterizing
  20606. functions and data structures with respect to the types on which they
  20607. operate. For example, figure~\ref{fig:map-poly} revisits the
  20608. \code{map} example and this time gives it a more fitting type. This
  20609. \code{map} function is parameterized with respect to the element type
  20610. of the tuple. The type of \code{map} is the following generic type
  20611. specified by the \code{All} type with parameter \code{T}:
  20612. {\if\edition\racketEd
  20613. \begin{lstlisting}
  20614. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20615. \end{lstlisting}
  20616. \fi}
  20617. {\if\edition\pythonEd\pythonColor
  20618. \begin{lstlisting}
  20619. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20620. \end{lstlisting}
  20621. \fi}
  20622. %
  20623. The idea is that \code{map} can be used at \emph{all} choices of a
  20624. type for parameter \code{T}. In the example shown in
  20625. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20626. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20627. \code{T}, but we could have just as well applied \code{map} to a tuple
  20628. of Booleans.
  20629. %
  20630. A \emph{monomorphic} function is simply one that is not generic.
  20631. %
  20632. We use the term \emph{instantiation} for the process (within the
  20633. language implementation) of turning a generic function into a
  20634. monomorphic one, where the type parameters have been replaced by
  20635. types.
  20636. {\if\edition\pythonEd\pythonColor
  20637. %
  20638. In Python, when writing a generic function such as \code{map}, one
  20639. does not explicitly write its generic type (using \code{All}).
  20640. Instead, that the function is generic is implied by the use of type
  20641. variables (such as \code{T}) in the type annotations of its
  20642. parameters.
  20643. %
  20644. \fi}
  20645. \begin{figure}[tbp]
  20646. % poly_test_2.rkt
  20647. \begin{tcolorbox}[colback=white]
  20648. {\if\edition\racketEd
  20649. \begin{lstlisting}
  20650. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20651. (define (map f v)
  20652. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20653. (define (inc [x : Integer]) : Integer (+ x 1))
  20654. (vector-ref (map inc (vector 0 41)) 1)
  20655. \end{lstlisting}
  20656. \fi}
  20657. {\if\edition\pythonEd\pythonColor
  20658. \begin{lstlisting}
  20659. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20660. return (f(tup[0]), f(tup[1]))
  20661. def add1(x : int) -> int:
  20662. return x + 1
  20663. t = map(add1, (0, 41))
  20664. print(t[1])
  20665. \end{lstlisting}
  20666. \fi}
  20667. \end{tcolorbox}
  20668. \caption{A generic version of the \code{map} function.}
  20669. \label{fig:map-poly}
  20670. \end{figure}
  20671. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20672. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20673. shows the definition of the abstract syntax.
  20674. %
  20675. {\if\edition\racketEd
  20676. We add a second form for function definitions in which a type
  20677. declaration comes before the \code{define}. In the abstract syntax,
  20678. the return type in the \code{Def} is \CANYTY{}, but that should be
  20679. ignored in favor of the return type in the type declaration. (The
  20680. \CANYTY{} comes from using the same parser as discussed in
  20681. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20682. enables the use of an \code{All} type for a function, thereby making
  20683. it generic.
  20684. \fi}
  20685. %
  20686. The grammar for types is extended to include the type of a generic
  20687. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20688. abstract syntax)}.
  20689. \newcommand{\LpolyGrammarRacket}{
  20690. \begin{array}{lcl}
  20691. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20692. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20693. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20694. \end{array}
  20695. }
  20696. \newcommand{\LpolyASTRacket}{
  20697. \begin{array}{lcl}
  20698. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20699. \Def &::=& \DECL{\Var}{\Type} \\
  20700. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20701. \end{array}
  20702. }
  20703. \newcommand{\LpolyGrammarPython}{
  20704. \begin{array}{lcl}
  20705. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20706. \end{array}
  20707. }
  20708. \newcommand{\LpolyASTPython}{
  20709. \begin{array}{lcl}
  20710. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20711. \MID \key{GenericVar}\LP\Var\RP
  20712. \end{array}
  20713. }
  20714. \begin{figure}[tp]
  20715. \centering
  20716. \begin{tcolorbox}[colback=white]
  20717. \footnotesize
  20718. {\if\edition\racketEd
  20719. \[
  20720. \begin{array}{l}
  20721. \gray{\LintGrammarRacket{}} \\ \hline
  20722. \gray{\LvarGrammarRacket{}} \\ \hline
  20723. \gray{\LifGrammarRacket{}} \\ \hline
  20724. \gray{\LwhileGrammarRacket} \\ \hline
  20725. \gray{\LtupGrammarRacket} \\ \hline
  20726. \gray{\LfunGrammarRacket} \\ \hline
  20727. \gray{\LlambdaGrammarRacket} \\ \hline
  20728. \LpolyGrammarRacket \\
  20729. \begin{array}{lcl}
  20730. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20731. \end{array}
  20732. \end{array}
  20733. \]
  20734. \fi}
  20735. {\if\edition\pythonEd\pythonColor
  20736. \[
  20737. \begin{array}{l}
  20738. \gray{\LintGrammarPython{}} \\ \hline
  20739. \gray{\LvarGrammarPython{}} \\ \hline
  20740. \gray{\LifGrammarPython{}} \\ \hline
  20741. \gray{\LwhileGrammarPython} \\ \hline
  20742. \gray{\LtupGrammarPython} \\ \hline
  20743. \gray{\LfunGrammarPython} \\ \hline
  20744. \gray{\LlambdaGrammarPython} \\\hline
  20745. \LpolyGrammarPython \\
  20746. \begin{array}{lcl}
  20747. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20748. \end{array}
  20749. \end{array}
  20750. \]
  20751. \fi}
  20752. \end{tcolorbox}
  20753. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20754. (figure~\ref{fig:Llam-concrete-syntax}).}
  20755. \label{fig:Lpoly-concrete-syntax}
  20756. \end{figure}
  20757. \begin{figure}[tp]
  20758. \centering
  20759. \begin{tcolorbox}[colback=white]
  20760. \footnotesize
  20761. {\if\edition\racketEd
  20762. \[
  20763. \begin{array}{l}
  20764. \gray{\LintOpAST} \\ \hline
  20765. \gray{\LvarASTRacket{}} \\ \hline
  20766. \gray{\LifASTRacket{}} \\ \hline
  20767. \gray{\LwhileASTRacket{}} \\ \hline
  20768. \gray{\LtupASTRacket{}} \\ \hline
  20769. \gray{\LfunASTRacket} \\ \hline
  20770. \gray{\LlambdaASTRacket} \\ \hline
  20771. \LpolyASTRacket \\
  20772. \begin{array}{lcl}
  20773. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20774. \end{array}
  20775. \end{array}
  20776. \]
  20777. \fi}
  20778. {\if\edition\pythonEd\pythonColor
  20779. \[
  20780. \begin{array}{l}
  20781. \gray{\LintASTPython} \\ \hline
  20782. \gray{\LvarASTPython{}} \\ \hline
  20783. \gray{\LifASTPython{}} \\ \hline
  20784. \gray{\LwhileASTPython{}} \\ \hline
  20785. \gray{\LtupASTPython{}} \\ \hline
  20786. \gray{\LfunASTPython} \\ \hline
  20787. \gray{\LlambdaASTPython} \\ \hline
  20788. \LpolyASTPython \\
  20789. \begin{array}{lcl}
  20790. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20791. \end{array}
  20792. \end{array}
  20793. \]
  20794. \fi}
  20795. \end{tcolorbox}
  20796. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20797. (figure~\ref{fig:Llam-syntax}).}
  20798. \label{fig:Lpoly-syntax}
  20799. \end{figure}
  20800. By including the \code{All} type in the $\Type$ nonterminal of the
  20801. grammar we choose to make generics first class, which has interesting
  20802. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20803. not include syntax for the \code{All} type. It is inferred for functions whose
  20804. type annotations contain type variables.} Many languages with generics, such as
  20805. C++~\citep{stroustrup88:_param_types} and Standard
  20806. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20807. may be helpful to see an example of first-class generics in action. In
  20808. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20809. whose parameter is a generic function. Indeed, because the grammar for
  20810. $\Type$ includes the \code{All} type, a generic function may also be
  20811. returned from a function or stored inside a tuple. The body of
  20812. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20813. and also to an integer, which would not be possible if \code{f} were
  20814. not generic.
  20815. \begin{figure}[tbp]
  20816. \begin{tcolorbox}[colback=white]
  20817. {\if\edition\racketEd
  20818. \begin{lstlisting}
  20819. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20820. (define (apply_twice f)
  20821. (if (f #t) (f 42) (f 777)))
  20822. (: id (All (T) (T -> T)))
  20823. (define (id x) x)
  20824. (apply_twice id)
  20825. \end{lstlisting}
  20826. \fi}
  20827. {\if\edition\pythonEd\pythonColor
  20828. \begin{lstlisting}
  20829. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20830. if f(True):
  20831. return f(42)
  20832. else:
  20833. return f(777)
  20834. def id(x: T) -> T:
  20835. return x
  20836. print(apply_twice(id))
  20837. \end{lstlisting}
  20838. \fi}
  20839. \end{tcolorbox}
  20840. \caption{An example illustrating first-class generics.}
  20841. \label{fig:apply-twice}
  20842. \end{figure}
  20843. The type checker for \LangPoly{} shown in
  20844. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20845. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20846. {\if\edition\pythonEd\pythonColor
  20847. %
  20848. Regarding function definitions, if the type annotations on its
  20849. parameters contain generic variables, then the function is generic and
  20850. therefore its type is an \code{All} type wrapped around a function
  20851. type. Otherwise the function is monomorphic and its type is simply
  20852. a function type.
  20853. %
  20854. \fi}
  20855. The type checking of a function application is extended to handle the
  20856. case in which the operator expression is a generic function. In that case
  20857. the type arguments are deduced by matching the types of the parameters
  20858. with the types of the arguments.
  20859. %
  20860. The \code{match\_types} auxiliary function
  20861. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20862. recursively descending through a parameter type \code{param\_ty} and
  20863. the corresponding argument type \code{arg\_ty}, making sure that they
  20864. are equal except when there is a type parameter in the parameter
  20865. type. Upon encountering a type parameter for the first time, the
  20866. algorithm deduces an association of the type parameter to the
  20867. corresponding part of the argument type. If it is not the first time
  20868. that the type parameter has been encountered, the algorithm looks up
  20869. its deduced type and makes sure that it is equal to the corresponding
  20870. part of the argument type. The return type of the application is the
  20871. return type of the generic function with the type parameters
  20872. replaced by the deduced type arguments, using the
  20873. \code{substitute\_type} auxiliary function, which is also listed in
  20874. figure~\ref{fig:type-check-Lpoly-aux}.
  20875. The type checker extends type equality to handle the \code{All} type.
  20876. This is not quite as simple as for other types, such as function and
  20877. tuple types, because two \code{All} types can be syntactically
  20878. different even though they are equivalent. For example,
  20879. \begin{center}
  20880. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20881. \end{center}
  20882. is equivalent to
  20883. \begin{center}
  20884. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20885. \end{center}
  20886. Two generic types are equal if they differ only in
  20887. the choice of the names of the type parameters. The definition of type
  20888. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20889. parameters in one type to match the type parameters of the other type.
  20890. {\if\edition\racketEd
  20891. %
  20892. The type checker also ensures that only defined type variables appear
  20893. in type annotations. The \code{check\_well\_formed} function for which
  20894. the definition is shown in figure~\ref{fig:well-formed-types}
  20895. recursively inspects a type, making sure that each type variable has
  20896. been defined.
  20897. %
  20898. \fi}
  20899. \begin{figure}[tbp]
  20900. \begin{tcolorbox}[colback=white]
  20901. {\if\edition\racketEd
  20902. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20903. (define type-check-poly-class
  20904. (class type-check-Llambda-class
  20905. (super-new)
  20906. (inherit check-type-equal?)
  20907. (define/override (type-check-apply env e1 es)
  20908. (define-values (e^ ty) ((type-check-exp env) e1))
  20909. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20910. ((type-check-exp env) e)))
  20911. (match ty
  20912. [`(,ty^* ... -> ,rt)
  20913. (for ([arg-ty ty*] [param-ty ty^*])
  20914. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20915. (values e^ es^ rt)]
  20916. [`(All ,xs (,tys ... -> ,rt))
  20917. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20918. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20919. (match_types env^^ param-ty arg-ty)))
  20920. (define targs
  20921. (for/list ([x xs])
  20922. (match (dict-ref env^^ x (lambda () #f))
  20923. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20924. x (Apply e1 es))]
  20925. [ty ty])))
  20926. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20927. [else (error 'type-check "expected a function, not ~a" ty)]))
  20928. (define/override ((type-check-exp env) e)
  20929. (match e
  20930. [(Lambda `([,xs : ,Ts] ...) rT body)
  20931. (for ([T Ts]) ((check_well_formed env) T))
  20932. ((check_well_formed env) rT)
  20933. ((super type-check-exp env) e)]
  20934. [(HasType e1 ty)
  20935. ((check_well_formed env) ty)
  20936. ((super type-check-exp env) e)]
  20937. [else ((super type-check-exp env) e)]))
  20938. (define/override ((type-check-def env) d)
  20939. (verbose 'type-check "poly/def" d)
  20940. (match d
  20941. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20942. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20943. (for ([p ps]) ((check_well_formed ts-env) p))
  20944. ((check_well_formed ts-env) rt)
  20945. (define new-env (append ts-env (map cons xs ps) env))
  20946. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20947. (check-type-equal? ty^ rt body)
  20948. (Generic ts (Def f p:t* rt info body^))]
  20949. [else ((super type-check-def env) d)]))
  20950. (define/override (type-check-program p)
  20951. (match p
  20952. [(Program info body)
  20953. (type-check-program (ProgramDefsExp info '() body))]
  20954. [(ProgramDefsExp info ds body)
  20955. (define ds^ (combine-decls-defs ds))
  20956. (define new-env (for/list ([d ds^])
  20957. (cons (def-name d) (fun-def-type d))))
  20958. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20959. (define-values (body^ ty) ((type-check-exp new-env) body))
  20960. (check-type-equal? ty 'Integer body)
  20961. (ProgramDefsExp info ds^^ body^)]))
  20962. ))
  20963. \end{lstlisting}
  20964. \fi}
  20965. {\if\edition\pythonEd\pythonColor
  20966. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20967. def type_check_exp(self, e, env):
  20968. match e:
  20969. case Call(Name(f), args) if f in builtin_functions:
  20970. return super().type_check_exp(e, env)
  20971. case Call(func, args):
  20972. func_t = self.type_check_exp(func, env)
  20973. func.has_type = func_t
  20974. match func_t:
  20975. case AllType(ps, FunctionType(p_tys, rt)):
  20976. for arg in args:
  20977. arg.has_type = self.type_check_exp(arg, env)
  20978. arg_tys = [arg.has_type for arg in args]
  20979. deduced = {}
  20980. for (p, a) in zip(p_tys, arg_tys):
  20981. self.match_types(p, a, deduced, e)
  20982. return self.substitute_type(rt, deduced)
  20983. case _:
  20984. return super().type_check_exp(e, env)
  20985. case _:
  20986. return super().type_check_exp(e, env)
  20987. def type_check(self, p):
  20988. match p:
  20989. case Module(body):
  20990. env = {}
  20991. for s in body:
  20992. match s:
  20993. case FunctionDef(name, params, bod, dl, returns, comment):
  20994. params_t = [t for (x,t) in params]
  20995. ty_params = set()
  20996. for t in params_t:
  20997. ty_params |$\mid$|= self.generic_variables(t)
  20998. ty = FunctionType(params_t, returns)
  20999. if len(ty_params) > 0:
  21000. ty = AllType(list(ty_params), ty)
  21001. env[name] = ty
  21002. self.check_stmts(body, IntType(), env)
  21003. case _:
  21004. raise Exception('type_check: unexpected ' + repr(p))
  21005. \end{lstlisting}
  21006. \fi}
  21007. \end{tcolorbox}
  21008. \caption{Type checker for the \LangPoly{} language.}
  21009. \label{fig:type-check-Lpoly}
  21010. \end{figure}
  21011. \begin{figure}[tbp]
  21012. \begin{tcolorbox}[colback=white]
  21013. {\if\edition\racketEd
  21014. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21015. (define/override (type-equal? t1 t2)
  21016. (match* (t1 t2)
  21017. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21018. (define env (map cons xs ys))
  21019. (type-equal? (substitute_type env T1) T2)]
  21020. [(other wise)
  21021. (super type-equal? t1 t2)]))
  21022. (define/public (match_types env pt at)
  21023. (match* (pt at)
  21024. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21025. [('Void 'Void) env] [('Any 'Any) env]
  21026. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21027. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21028. (match_types env^ pt1 at1))]
  21029. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21030. (define env^ (match_types env prt art))
  21031. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21032. (match_types env^^ pt1 at1))]
  21033. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21034. (define env^ (append (map cons pxs axs) env))
  21035. (match_types env^ pt1 at1)]
  21036. [((? symbol? x) at)
  21037. (match (dict-ref env x (lambda () #f))
  21038. [#f (error 'type-check "undefined type variable ~a" x)]
  21039. ['Type (cons (cons x at) env)]
  21040. [t^ (check-type-equal? at t^ 'matching) env])]
  21041. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21042. (define/public (substitute_type env pt)
  21043. (match pt
  21044. ['Integer 'Integer] ['Boolean 'Boolean]
  21045. ['Void 'Void] ['Any 'Any]
  21046. [`(Vector ,ts ...)
  21047. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21048. [`(,ts ... -> ,rt)
  21049. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21050. [`(All ,xs ,t)
  21051. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21052. [(? symbol? x) (dict-ref env x)]
  21053. [else (error 'type-check "expected a type not ~a" pt)]))
  21054. (define/public (combine-decls-defs ds)
  21055. (match ds
  21056. ['() '()]
  21057. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21058. (unless (equal? name f)
  21059. (error 'type-check "name mismatch, ~a != ~a" name f))
  21060. (match type
  21061. [`(All ,xs (,ps ... -> ,rt))
  21062. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21063. (cons (Generic xs (Def name params^ rt info body))
  21064. (combine-decls-defs ds^))]
  21065. [`(,ps ... -> ,rt)
  21066. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21067. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21068. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21069. [`(,(Def f params rt info body) . ,ds^)
  21070. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21071. \end{lstlisting}
  21072. \fi}
  21073. {\if\edition\pythonEd\pythonColor
  21074. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21075. def match_types(self, param_ty, arg_ty, deduced, e):
  21076. match (param_ty, arg_ty):
  21077. case (GenericVar(id), _):
  21078. if id in deduced:
  21079. self.check_type_equal(arg_ty, deduced[id], e)
  21080. else:
  21081. deduced[id] = arg_ty
  21082. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21083. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21084. new_arg_ty = self.substitute_type(arg_ty, rename)
  21085. self.match_types(ty, new_arg_ty, deduced, e)
  21086. case (TupleType(ps), TupleType(ts)):
  21087. for (p, a) in zip(ps, ts):
  21088. self.match_types(p, a, deduced, e)
  21089. case (ListType(p), ListType(a)):
  21090. self.match_types(p, a, deduced, e)
  21091. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21092. for (pp, ap) in zip(pps, aps):
  21093. self.match_types(pp, ap, deduced, e)
  21094. self.match_types(prt, art, deduced, e)
  21095. case (IntType(), IntType()):
  21096. pass
  21097. case (BoolType(), BoolType()):
  21098. pass
  21099. case _:
  21100. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21101. def substitute_type(self, ty, var_map):
  21102. match ty:
  21103. case GenericVar(id):
  21104. return var_map[id]
  21105. case AllType(ps, ty):
  21106. new_map = copy.deepcopy(var_map)
  21107. for p in ps:
  21108. new_map[p] = GenericVar(p)
  21109. return AllType(ps, self.substitute_type(ty, new_map))
  21110. case TupleType(ts):
  21111. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21112. case ListType(ty):
  21113. return ListType(self.substitute_type(ty, var_map))
  21114. case FunctionType(pts, rt):
  21115. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21116. self.substitute_type(rt, var_map))
  21117. case IntType():
  21118. return IntType()
  21119. case BoolType():
  21120. return BoolType()
  21121. case _:
  21122. raise Exception('substitute_type: unexpected ' + repr(ty))
  21123. def check_type_equal(self, t1, t2, e):
  21124. match (t1, t2):
  21125. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21126. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21127. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21128. case (_, _):
  21129. return super().check_type_equal(t1, t2, e)
  21130. \end{lstlisting}
  21131. \fi}
  21132. \end{tcolorbox}
  21133. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21134. \label{fig:type-check-Lpoly-aux}
  21135. \end{figure}
  21136. {\if\edition\racketEd
  21137. \begin{figure}[tbp]
  21138. \begin{tcolorbox}[colback=white]
  21139. \begin{lstlisting}
  21140. (define/public ((check_well_formed env) ty)
  21141. (match ty
  21142. ['Integer (void)]
  21143. ['Boolean (void)]
  21144. ['Void (void)]
  21145. [(? symbol? a)
  21146. (match (dict-ref env a (lambda () #f))
  21147. ['Type (void)]
  21148. [else (error 'type-check "undefined type variable ~a" a)])]
  21149. [`(Vector ,ts ...)
  21150. (for ([t ts]) ((check_well_formed env) t))]
  21151. [`(,ts ... -> ,t)
  21152. (for ([t ts]) ((check_well_formed env) t))
  21153. ((check_well_formed env) t)]
  21154. [`(All ,xs ,t)
  21155. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21156. ((check_well_formed env^) t)]
  21157. [else (error 'type-check "unrecognized type ~a" ty)]))
  21158. \end{lstlisting}
  21159. \end{tcolorbox}
  21160. \caption{Well-formed types.}
  21161. \label{fig:well-formed-types}
  21162. \end{figure}
  21163. \fi}
  21164. % TODO: interpreter for R'_10
  21165. \clearpage
  21166. \section{Compiling Generics}
  21167. \label{sec:compiling-poly}
  21168. Broadly speaking, there are four approaches to compiling generics, as
  21169. follows:
  21170. \begin{description}
  21171. \item[Monomorphization] generates a different version of a generic
  21172. function for each set of type arguments with which it is used,
  21173. producing type-specialized code. This approach results in the most
  21174. efficient code but requires whole-program compilation (no separate
  21175. compilation) and may increase code size. Unfortunately,
  21176. monomorphization is incompatible with first-class generics because
  21177. it is not always possible to determine which generic functions are
  21178. used with which type arguments during compilation. (It can be done
  21179. at runtime with just-in-time compilation.) Monomorphization is
  21180. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21181. generic functions in NESL~\citep{Blelloch:1993aa} and
  21182. ML~\citep{Weeks:2006aa}.
  21183. \item[Uniform representation] generates one version of each generic
  21184. function and requires all values to have a common \emph{boxed} format,
  21185. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21186. generic and monomorphic code is compiled similarly to code in a
  21187. dynamically typed language (like \LangDyn{}), in which primitive
  21188. operators require their arguments to be projected from \CANYTY{} and
  21189. their results to be injected into \CANYTY{}. (In object-oriented
  21190. languages, the projection is accomplished via virtual method
  21191. dispatch.) The uniform representation approach is compatible with
  21192. separate compilation and with first-class generics. However, it
  21193. produces the least efficient code because it introduces overhead in
  21194. the entire program. This approach is used in
  21195. Java~\citep{Bracha:1998fk},
  21196. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21197. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21198. \item[Mixed representation] generates one version of each generic
  21199. function, using a boxed representation for type variables. However,
  21200. monomorphic code is compiled as usual (as in \LangLam{}), and
  21201. conversions are performed at the boundaries between monomorphic code
  21202. and polymorphic code (for example, when a generic function is instantiated
  21203. and called). This approach is compatible with separate compilation
  21204. and first-class generics and maintains efficiency in monomorphic
  21205. code. The trade-off is increased overhead at the boundary between
  21206. monomorphic and generic code. This approach is used in
  21207. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21208. Java 5 with the addition of autoboxing.
  21209. \item[Type passing] uses the unboxed representation in both
  21210. monomorphic and generic code. Each generic function is compiled to a
  21211. single function with extra parameters that describe the type
  21212. arguments. The type information is used by the generated code to
  21213. determine how to access the unboxed values at runtime. This approach is
  21214. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21215. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21216. compilation and first-class generics and maintains the
  21217. efficiency for monomorphic code. There is runtime overhead in
  21218. polymorphic code from dispatching on type information.
  21219. \end{description}
  21220. In this chapter we use the mixed representation approach, partly
  21221. because of its favorable attributes and partly because it is
  21222. straightforward to implement using the tools that we have already
  21223. built to support gradual typing. The work of compiling generic
  21224. functions is performed in two passes, \code{resolve} and
  21225. \code{erase\_types}, that we discuss next. The output of
  21226. \code{erase\_types} is \LangCast{}
  21227. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21228. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21229. \section{Resolve Instantiation}
  21230. \label{sec:generic-resolve}
  21231. Recall that the type checker for \LangPoly{} deduces the type
  21232. arguments at call sites to a generic function. The purpose of the
  21233. \code{resolve} pass is to turn this implicit instantiation into an
  21234. explicit one, by adding \code{inst} nodes to the syntax of the
  21235. intermediate language. An \code{inst} node records the mapping of
  21236. type parameters to type arguments. The semantics of the \code{inst}
  21237. node is to instantiate the result of its first argument, a generic
  21238. function, to produce a monomorphic function. However, because the
  21239. interpreter never analyzes type annotations, instantiation can be a
  21240. no-op and simply return the generic function.
  21241. %
  21242. The output language of the \code{resolve} pass is \LangInst{},
  21243. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21244. {\if\edition\racketEd
  21245. The \code{resolve} pass combines the type declaration and polymorphic
  21246. function into a single definition, using the \code{Poly} form, to make
  21247. polymorphic functions more convenient to process in the next pass of the
  21248. compiler.
  21249. \fi}
  21250. \newcommand{\LinstASTRacket}{
  21251. \begin{array}{lcl}
  21252. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21253. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21254. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21255. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21256. \end{array}
  21257. }
  21258. \newcommand{\LinstASTPython}{
  21259. \begin{array}{lcl}
  21260. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21261. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21262. \end{array}
  21263. }
  21264. \begin{figure}[tp]
  21265. \centering
  21266. \begin{tcolorbox}[colback=white]
  21267. \small
  21268. {\if\edition\racketEd
  21269. \[
  21270. \begin{array}{l}
  21271. \gray{\LintOpAST} \\ \hline
  21272. \gray{\LvarASTRacket{}} \\ \hline
  21273. \gray{\LifASTRacket{}} \\ \hline
  21274. \gray{\LwhileASTRacket{}} \\ \hline
  21275. \gray{\LtupASTRacket{}} \\ \hline
  21276. \gray{\LfunASTRacket} \\ \hline
  21277. \gray{\LlambdaASTRacket} \\ \hline
  21278. \LinstASTRacket \\
  21279. \begin{array}{lcl}
  21280. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21281. \end{array}
  21282. \end{array}
  21283. \]
  21284. \fi}
  21285. {\if\edition\pythonEd\pythonColor
  21286. \[
  21287. \begin{array}{l}
  21288. \gray{\LintASTPython} \\ \hline
  21289. \gray{\LvarASTPython{}} \\ \hline
  21290. \gray{\LifASTPython{}} \\ \hline
  21291. \gray{\LwhileASTPython{}} \\ \hline
  21292. \gray{\LtupASTPython{}} \\ \hline
  21293. \gray{\LfunASTPython} \\ \hline
  21294. \gray{\LlambdaASTPython} \\ \hline
  21295. \LinstASTPython \\
  21296. \begin{array}{lcl}
  21297. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21298. \end{array}
  21299. \end{array}
  21300. \]
  21301. \fi}
  21302. \end{tcolorbox}
  21303. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21304. (figure~\ref{fig:Llam-syntax}).}
  21305. \label{fig:Lpoly-prime-syntax}
  21306. \end{figure}
  21307. The output of the \code{resolve} pass on the generic \code{map}
  21308. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21309. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21310. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21311. \begin{figure}[tbp]
  21312. % poly_test_2.rkt
  21313. \begin{tcolorbox}[colback=white]
  21314. {\if\edition\racketEd
  21315. \begin{lstlisting}
  21316. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21317. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21318. (define (inc [x : Integer]) : Integer (+ x 1))
  21319. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21320. (Integer))
  21321. inc (vector 0 41)) 1)
  21322. \end{lstlisting}
  21323. \fi}
  21324. {\if\edition\pythonEd\pythonColor
  21325. \begin{lstlisting}
  21326. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21327. return (f(tup[0]), f(tup[1]))
  21328. def add1(x : int) -> int:
  21329. return x + 1
  21330. t = inst(map, {T: int})(add1, (0, 41))
  21331. print(t[1])
  21332. \end{lstlisting}
  21333. \fi}
  21334. \end{tcolorbox}
  21335. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21336. \label{fig:map-resolve}
  21337. \end{figure}
  21338. \section{Erase Generic Types}
  21339. \label{sec:erase_types}
  21340. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21341. represent type variables. For example, figure~\ref{fig:map-erase}
  21342. shows the output of the \code{erase\_types} pass on the generic
  21343. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21344. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21345. \code{All} types are removed from the type of \code{map}.
  21346. \begin{figure}[tbp]
  21347. \begin{tcolorbox}[colback=white]
  21348. {\if\edition\racketEd
  21349. \begin{lstlisting}
  21350. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21351. : (Vector Any Any)
  21352. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21353. (define (inc [x : Integer]) : Integer (+ x 1))
  21354. (vector-ref ((cast map
  21355. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21356. ((Integer -> Integer) (Vector Integer Integer)
  21357. -> (Vector Integer Integer)))
  21358. inc (vector 0 41)) 1)
  21359. \end{lstlisting}
  21360. \fi}
  21361. {\if\edition\pythonEd\pythonColor
  21362. \begin{lstlisting}
  21363. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21364. return (f(tup[0]), f(tup[1]))
  21365. def add1(x : int) -> int:
  21366. return (x + 1)
  21367. def main() -> int:
  21368. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21369. print(t[1])
  21370. return 0
  21371. \end{lstlisting}
  21372. {\small
  21373. where\\
  21374. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21375. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21376. }
  21377. \fi}
  21378. \end{tcolorbox}
  21379. \caption{The generic \code{map} example after type erasure.}
  21380. \label{fig:map-erase}
  21381. \end{figure}
  21382. This process of type erasure creates a challenge at points of
  21383. instantiation. For example, consider the instantiation of
  21384. \code{map} shown in figure~\ref{fig:map-resolve}.
  21385. The type of \code{map} is
  21386. %
  21387. {\if\edition\racketEd
  21388. \begin{lstlisting}
  21389. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21390. \end{lstlisting}
  21391. \fi}
  21392. {\if\edition\pythonEd\pythonColor
  21393. \begin{lstlisting}
  21394. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21395. \end{lstlisting}
  21396. \fi}
  21397. %
  21398. \noindent and it is instantiated to
  21399. %
  21400. {\if\edition\racketEd
  21401. \begin{lstlisting}
  21402. ((Integer -> Integer) (Vector Integer Integer)
  21403. -> (Vector Integer Integer))
  21404. \end{lstlisting}
  21405. \fi}
  21406. {\if\edition\pythonEd\pythonColor
  21407. \begin{lstlisting}
  21408. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21409. \end{lstlisting}
  21410. \fi}
  21411. %
  21412. \noindent After erasure, the type of \code{map} is
  21413. %
  21414. {\if\edition\racketEd
  21415. \begin{lstlisting}
  21416. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21417. \end{lstlisting}
  21418. \fi}
  21419. {\if\edition\pythonEd\pythonColor
  21420. \begin{lstlisting}
  21421. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21422. \end{lstlisting}
  21423. \fi}
  21424. %
  21425. \noindent but we need to convert it to the instantiated type. This is
  21426. easy to do in the language \LangCast{} with a single \code{cast}. In
  21427. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21428. \code{map} has been compiled to a \code{cast} from the type of
  21429. \code{map} to the instantiated type. The source and the target type of
  21430. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21431. is the case because both the source and target are obtained from the
  21432. same generic type of \code{map}, replacing the type parameters with
  21433. \CANYTY{} in the former and with the deduced type arguments in the
  21434. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21435. To implement the \code{erase\_types} pass, we first recommend defining
  21436. a recursive function that translates types, named
  21437. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21438. follows.
  21439. %
  21440. {\if\edition\racketEd
  21441. \begin{lstlisting}
  21442. |$T$|
  21443. |$\Rightarrow$|
  21444. Any
  21445. \end{lstlisting}
  21446. \fi}
  21447. {\if\edition\pythonEd\pythonColor
  21448. \begin{lstlisting}
  21449. GenericVar(|$T$|)
  21450. |$\Rightarrow$|
  21451. Any
  21452. \end{lstlisting}
  21453. \fi}
  21454. %
  21455. \noindent The \code{erase\_type} function also removes the generic
  21456. \code{All} types.
  21457. %
  21458. {\if\edition\racketEd
  21459. \begin{lstlisting}
  21460. (All |$xs$| |$T_1$|)
  21461. |$\Rightarrow$|
  21462. |$T'_1$|
  21463. \end{lstlisting}
  21464. \fi}
  21465. {\if\edition\pythonEd\pythonColor
  21466. \begin{lstlisting}
  21467. AllType(|$xs$|, |$T_1$|)
  21468. |$\Rightarrow$|
  21469. |$T'_1$|
  21470. \end{lstlisting}
  21471. \fi}
  21472. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21473. $T_1$.
  21474. %
  21475. In this compiler pass, apply the \code{erase\_type} function to all
  21476. the type annotations in the program.
  21477. Regarding the translation of expressions, the case for \code{Inst} is
  21478. the interesting one. We translate it into a \code{Cast}, as shown
  21479. next.
  21480. The type of the subexpression $e$ is a generic type of the form
  21481. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21482. The source type of the cast is the erasure of $T$, the type $T_s$.
  21483. %
  21484. {\if\edition\racketEd
  21485. %
  21486. The target type $T_t$ is the result of substituting the argument types
  21487. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21488. erasure.
  21489. %
  21490. \begin{lstlisting}
  21491. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21492. |$\Rightarrow$|
  21493. (Cast |$e'$| |$T_s$| |$T_t$|)
  21494. \end{lstlisting}
  21495. %
  21496. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21497. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21498. \fi}
  21499. {\if\edition\pythonEd\pythonColor
  21500. %
  21501. The target type $T_t$ is the result of substituting the deduced
  21502. argument types $d$ in $T$ and then performing type erasure.
  21503. %
  21504. \begin{lstlisting}
  21505. Inst(|$e$|, |$d$|)
  21506. |$\Rightarrow$|
  21507. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21508. \end{lstlisting}
  21509. %
  21510. where
  21511. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21512. \fi}
  21513. Finally, each generic function is translated to a regular
  21514. function in which type erasure has been applied to all the type
  21515. annotations and the body.
  21516. %% \begin{lstlisting}
  21517. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21518. %% |$\Rightarrow$|
  21519. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21520. %% \end{lstlisting}
  21521. \begin{exercise}\normalfont\normalsize
  21522. Implement a compiler for the polymorphic language \LangPoly{} by
  21523. extending and adapting your compiler for \LangGrad{}. Create six new
  21524. test programs that use polymorphic functions. Some of them should
  21525. make use of first-class generics.
  21526. \end{exercise}
  21527. \begin{figure}[tbp]
  21528. \begin{tcolorbox}[colback=white]
  21529. {\if\edition\racketEd
  21530. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21531. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21532. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21533. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21534. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21535. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21536. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21537. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21538. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21539. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21540. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21541. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21542. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21543. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21544. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21545. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21546. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21547. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21548. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21549. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21550. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21551. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21552. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21553. \path[->,bend left=15] (Lpoly) edge [above] node
  21554. {\ttfamily\footnotesize resolve} (Lpolyp);
  21555. \path[->,bend left=15] (Lpolyp) edge [above] node
  21556. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21557. \path[->,bend left=15] (Lgradualp) edge [above] node
  21558. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21559. \path[->,bend left=15] (Llambdapp) edge [left] node
  21560. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21561. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21562. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21563. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21564. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21565. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21566. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21567. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21568. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21569. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21570. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21571. \path[->,bend left=15] (F1-1) edge [above] node
  21572. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21573. \path[->,bend left=15] (F1-2) edge [above] node
  21574. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21575. \path[->,bend left=15] (F1-3) edge [left] node
  21576. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21577. \path[->,bend left=15] (F1-4) edge [below] node
  21578. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21579. \path[->,bend right=15] (F1-5) edge [above] node
  21580. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21581. \path[->,bend right=15] (F1-6) edge [above] node
  21582. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21583. \path[->,bend right=15] (C3-2) edge [right] node
  21584. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21585. \path[->,bend right=15] (x86-2) edge [right] node
  21586. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21587. \path[->,bend right=15] (x86-2-1) edge [below] node
  21588. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21589. \path[->,bend right=15] (x86-2-2) edge [right] node
  21590. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21591. \path[->,bend left=15] (x86-3) edge [above] node
  21592. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21593. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21594. \end{tikzpicture}
  21595. \fi}
  21596. {\if\edition\pythonEd\pythonColor
  21597. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21598. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21599. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21600. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21601. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21602. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21603. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21604. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21605. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21606. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21607. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21608. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21609. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21610. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21611. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21612. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21613. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21614. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21615. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21616. \path[->,bend left=15] (Lgradual) edge [above] node
  21617. {\ttfamily\footnotesize shrink} (Lgradual2);
  21618. \path[->,bend left=15] (Lgradual2) edge [above] node
  21619. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21620. \path[->,bend left=15] (Lgradual3) edge [above] node
  21621. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21622. \path[->,bend left=15] (Lgradual4) edge [left] node
  21623. {\ttfamily\footnotesize resolve} (Lgradualr);
  21624. \path[->,bend left=15] (Lgradualr) edge [below] node
  21625. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21626. \path[->,bend right=15] (Llambdapp) edge [above] node
  21627. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21628. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21629. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21630. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21631. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21632. \path[->,bend right=15] (F1-1) edge [below] node
  21633. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21634. \path[->,bend right=15] (F1-2) edge [below] node
  21635. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21636. \path[->,bend left=15] (F1-3) edge [above] node
  21637. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21638. \path[->,bend left=15] (F1-5) edge [left] node
  21639. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21640. \path[->,bend left=5] (F1-6) edge [below] node
  21641. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21642. \path[->,bend right=15] (C3-2) edge [right] node
  21643. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21644. \path[->,bend right=15] (x86-2) edge [below] node
  21645. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21646. \path[->,bend right=15] (x86-3) edge [below] node
  21647. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21648. \path[->,bend left=15] (x86-4) edge [above] node
  21649. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21650. \end{tikzpicture}
  21651. \fi}
  21652. \end{tcolorbox}
  21653. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21654. \label{fig:Lpoly-passes}
  21655. \end{figure}
  21656. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21657. needed to compile \LangPoly{}.
  21658. % TODO: challenge problem: specialization of instantiations
  21659. % Further Reading
  21660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21661. \clearpage
  21662. \appendix
  21663. \chapter{Appendix}
  21664. \setcounter{footnote}{0}
  21665. {\if\edition\racketEd
  21666. \section{Interpreters}
  21667. \label{appendix:interp}
  21668. \index{subject}{interpreter}
  21669. We provide interpreters for each of the source languages \LangInt{},
  21670. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21671. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21672. intermediate languages \LangCVar{} and \LangCIf{} are in
  21673. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21674. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21675. \key{interp.rkt} file.
  21676. \section{Utility Functions}
  21677. \label{appendix:utilities}
  21678. The utility functions described in this section are in the
  21679. \key{utilities.rkt} file of the support code.
  21680. \paragraph{\code{interp-tests}}
  21681. This function runs the compiler passes and the interpreters on each of
  21682. the specified tests to check whether each pass is correct. The
  21683. \key{interp-tests} function has the following parameters:
  21684. \begin{description}
  21685. \item[name (a string)] A name to identify the compiler.
  21686. \item[typechecker] A function of exactly one argument that either
  21687. raises an error using the \code{error} function when it encounters a
  21688. type error, or returns \code{\#f} when it encounters a type
  21689. error. If there is no type error, the type checker returns the
  21690. program.
  21691. \item[passes] A list with one entry per pass. An entry is a list
  21692. consisting of four things:
  21693. \begin{enumerate}
  21694. \item a string giving the name of the pass;
  21695. \item the function that implements the pass (a translator from AST
  21696. to AST);
  21697. \item a function that implements the interpreter (a function from
  21698. AST to result value) for the output language; and,
  21699. \item a type checker for the output language. Type checkers for
  21700. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21701. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21702. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21703. type checker entry is optional. The support code does not provide
  21704. type checkers for the x86 languages.
  21705. \end{enumerate}
  21706. \item[source-interp] An interpreter for the source language. The
  21707. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21708. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21709. \item[tests] A list of test numbers that specifies which tests to
  21710. run (explained next).
  21711. \end{description}
  21712. %
  21713. The \key{interp-tests} function assumes that the subdirectory
  21714. \key{tests} has a collection of Racket programs whose names all start
  21715. with the family name, followed by an underscore and then the test
  21716. number, and ending with the file extension \key{.rkt}. Also, for each test
  21717. program that calls \code{read} one or more times, there is a file with
  21718. the same name except that the file extension is \key{.in}, which
  21719. provides the input for the Racket program. If the test program is
  21720. expected to fail type checking, then there should be an empty file of
  21721. the same name with extension \key{.tyerr}.
  21722. \paragraph{\code{compiler-tests}}
  21723. This function runs the compiler passes to generate x86 (a \key{.s}
  21724. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21725. It runs the machine code and checks that the output is $42$. The
  21726. parameters to the \code{compiler-tests} function are similar to those
  21727. of the \code{interp-tests} function, and they consist of
  21728. \begin{itemize}
  21729. \item a compiler name (a string),
  21730. \item a type checker,
  21731. \item description of the passes,
  21732. \item name of a test-family, and
  21733. \item a list of test numbers.
  21734. \end{itemize}
  21735. \paragraph{\code{compile-file}}
  21736. This function takes a description of the compiler passes (see the
  21737. comment for \key{interp-tests}) and returns a function that, given a
  21738. program file name (a string ending in \key{.rkt}), applies all the
  21739. passes and writes the output to a file whose name is the same as the
  21740. program file name with extension \key{.rkt} replaced by \key{.s}.
  21741. \paragraph{\code{read-program}}
  21742. This function takes a file path and parses that file (it must be a
  21743. Racket program) into an abstract syntax tree.
  21744. \paragraph{\code{parse-program}}
  21745. This function takes an S-expression representation of an abstract
  21746. syntax tree and converts it into the struct-based representation.
  21747. \paragraph{\code{assert}}
  21748. This function takes two parameters, a string (\code{msg}) and Boolean
  21749. (\code{bool}), and displays the message \key{msg} if the Boolean
  21750. \key{bool} is false.
  21751. \paragraph{\code{lookup}}
  21752. % remove discussion of lookup? -Jeremy
  21753. This function takes a key and an alist and returns the first value that is
  21754. associated with the given key, if there is one. If not, an error is
  21755. triggered. The alist may contain both immutable pairs (built with
  21756. \key{cons}) and mutable pairs (built with \key{mcons}).
  21757. %The \key{map2} function ...
  21758. \fi} %\racketEd
  21759. \section{x86 Instruction Set Quick Reference}
  21760. \label{sec:x86-quick-reference}
  21761. \index{subject}{x86}
  21762. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21763. do. We write $A \to B$ to mean that the value of $A$ is written into
  21764. location $B$. Address offsets are given in bytes. The instruction
  21765. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21766. registers (such as \code{\%rax}), or memory references (such as
  21767. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21768. reference per instruction. Other operands must be immediates or
  21769. registers.
  21770. \begin{table}[tbp]
  21771. \captionabove{Quick reference for the x86 instructions used in this book.}
  21772. \label{tab:x86-instr}
  21773. \centering
  21774. \begin{tabular}{l|l}
  21775. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21776. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21777. \texttt{negq} $A$ & $- A \to A$ \\
  21778. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21779. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21780. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21781. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21782. \texttt{retq} & Pops the return address and jumps to it. \\
  21783. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21784. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21785. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21786. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21787. be an immediate). \\
  21788. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21789. matches the condition code of the instruction; otherwise go to the
  21790. next instructions. The condition codes are \key{e} for \emph{equal},
  21791. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21792. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21793. \texttt{jl} $L$ & \\
  21794. \texttt{jle} $L$ & \\
  21795. \texttt{jg} $L$ & \\
  21796. \texttt{jge} $L$ & \\
  21797. \texttt{jmp} $L$ & Jump to label $L$. \\
  21798. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21799. \texttt{movzbq} $A$, $B$ &
  21800. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21801. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21802. and the extra bytes of $B$ are set to zero.} \\
  21803. & \\
  21804. & \\
  21805. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21806. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21807. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21808. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21809. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21810. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21811. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21812. description of the condition codes. $A$ must be a single byte register
  21813. (e.g., \texttt{al} or \texttt{cl}).} \\
  21814. \texttt{setl} $A$ & \\
  21815. \texttt{setle} $A$ & \\
  21816. \texttt{setg} $A$ & \\
  21817. \texttt{setge} $A$ &
  21818. \end{tabular}
  21819. \end{table}
  21820. \backmatter
  21821. \addtocontents{toc}{\vspace{11pt}}
  21822. \cleardoublepage % needed for right page number in TOC for References
  21823. %% \nocite{*} is a way to get all the entries in the .bib file to
  21824. %% print in the bibliography:
  21825. \nocite{*}\let\bibname\refname
  21826. \addcontentsline{toc}{fmbm}{\refname}
  21827. \printbibliography
  21828. %\printindex{authors}{Author Index}
  21829. \printindex{subject}{Index}
  21830. \end{document}
  21831. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21832. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21833. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21834. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21835. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21836. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21837. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21838. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21839. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21840. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21841. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21842. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21843. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21844. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21845. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21846. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21847. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21848. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21849. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21850. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21851. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21852. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21853. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21854. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21855. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21856. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21857. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21858. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21859. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21860. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21861. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21862. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21863. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21864. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21865. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21866. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21867. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21868. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21869. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21870. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21871. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21872. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21873. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21874. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21875. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21876. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21877. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21878. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21879. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21880. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21881. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21882. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21883. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21884. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21885. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21886. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21887. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21888. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21889. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21890. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21891. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21892. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21893. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21894. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21895. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21896. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21897. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21898. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21899. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21900. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21901. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21902. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21903. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21904. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21905. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21906. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21907. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21908. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21909. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21910. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21911. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21912. % LocalWords: pseudocode underapproximation underapproximations LALR
  21913. % LocalWords: semilattices overapproximate incrementing Earley docs
  21914. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21915. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21916. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21917. % LocalWords: LC partialevaluation pythonEd TOC TrappedError